Android:从数据库获取小部件数据

发布于 2024-12-13 05:44:30 字数 3787 浏览 0 评论 0原文

我想制作一个主屏幕小部件,显示来自数据库的随机收据。实际上,我在打开数据库的命令上遇到了错误。

那么我能做些什么来让它发挥作用呢?通常此代码在正常活动中工作......但作为小部件?

package com.droidfish.apps.acli;

import java.util.Random;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class RecieptOfTheDayWidget extends AppWidgetProvider {
static DataBaseHelper dbh;

public void onDeleted(Context context, int[] appWidgetIds) {
    // TODO Auto-generated method stub
    super.onDeleted(context, appWidgetIds);
    Toast.makeText(context, "widget deleted", Toast.LENGTH_SHORT).show();
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    // TODO Auto-generated method stub
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    final int iN = appWidgetIds.length;

    updateWidgetContent(context, appWidgetManager, appWidgetIds);
}

public static void updateWidgetContent(Context context,
        AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    dbh.openDataBase();
    String sNameVariant = "basestring";
    Cursor c1 = dbh.rawQuery("SELECT _id from reciept");
    Random r = new Random();
    int iRandomID = 1;
    int iVName = c1.getColumnIndex("name");
    int iCountDataSet;
    for (c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()) {
        iCountDataSet = c1.getCount();
        iRandomID = r.nextInt(iCountDataSet);
        Log.d("Random: ", (Integer.toString(iRandomID)));

    }
    Cursor c2 = dbh
            .rawQuery("SELECT name FROM reciept WHERE _id = "
                    + iRandomID);
    for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
        sNameVariant = c2.getString(iVName);
    }
    RemoteViews vView1 = new RemoteViews(context.getPackageName(),
            R.layout.recieptofthedaywidget);

    vView1.setTextViewText(R.id.tvWidgetReciept, sNameVariant);
    dbh.close();

    appWidgetManager.updateAppWidget(appWidgetIds, vView1);
}
}

谢谢彼得


更新#1:
谢谢柯蒂斯,

我添加了这样的方法

    private static DataBaseHelper getDatabaseHelper(Context context) {
    DataBaseHelper dbh = null;
    if (dbh == null) {
        dbh = new DataBaseHelper(context);
        dbh.openDataBase();
    }
    return dbh;
}

,但现在收到此错误

10-30 08:32:53.882: E/AndroidRuntime(296): java.lang.RuntimeException: Unable to start receiver com.droidfish.apps.acli.RecieptOfTheDayWidget: java.lang.IllegalStateException: get field slot from row 0 col -1 failed

它看起来无法从列计数范围中获取随机数。这是对的吗? 时,它会产生相同的错误,

iRandomID = r.nextInt(3);

实际上,当我写Mhh 这真的很有趣。有什么建议吗?


更新#2:
我像这样改变了我的代码并且它有效。缺少一些重要的行:))))

再次感谢

        Cursor c1 =getDatabaseHelper(context).getReadableDatabase().rawQuery("SELECT _id from reciept_variant", null);
    Random r = new Random();
    int iRandomID = 1;
    int iVName = c1.getColumnIndex("_id");
    int iCountDataSet;
    for (c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()) {
        iCountDataSet = c1.getCount();
        //iRandomID = r.nextInt(3);
        iRandomID = r.nextInt(iCountDataSet);
        Log.d("Random: ", (Integer.toString(iRandomID)));

    }
    Cursor c2 = getDatabaseHelper(context).getReadableDatabase().rawQuery("SELECT _id, name FROM reciept_variant WHERE _id = 3"
                , null);

    int iName2 = c2.getColumnIndex("name");
    for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
        sNameVariant = c2.getString(iName2);
    }

I want to make a homescreen-widget which displays a random Receipt from a database. Actually I got an error on the command which opens the database.

So what I can do to make it work? Usually this code work in a normal activity....but as widget??

package com.droidfish.apps.acli;

import java.util.Random;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class RecieptOfTheDayWidget extends AppWidgetProvider {
static DataBaseHelper dbh;

public void onDeleted(Context context, int[] appWidgetIds) {
    // TODO Auto-generated method stub
    super.onDeleted(context, appWidgetIds);
    Toast.makeText(context, "widget deleted", Toast.LENGTH_SHORT).show();
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    // TODO Auto-generated method stub
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    final int iN = appWidgetIds.length;

    updateWidgetContent(context, appWidgetManager, appWidgetIds);
}

public static void updateWidgetContent(Context context,
        AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    dbh.openDataBase();
    String sNameVariant = "basestring";
    Cursor c1 = dbh.rawQuery("SELECT _id from reciept");
    Random r = new Random();
    int iRandomID = 1;
    int iVName = c1.getColumnIndex("name");
    int iCountDataSet;
    for (c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()) {
        iCountDataSet = c1.getCount();
        iRandomID = r.nextInt(iCountDataSet);
        Log.d("Random: ", (Integer.toString(iRandomID)));

    }
    Cursor c2 = dbh
            .rawQuery("SELECT name FROM reciept WHERE _id = "
                    + iRandomID);
    for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
        sNameVariant = c2.getString(iVName);
    }
    RemoteViews vView1 = new RemoteViews(context.getPackageName(),
            R.layout.recieptofthedaywidget);

    vView1.setTextViewText(R.id.tvWidgetReciept, sNameVariant);
    dbh.close();

    appWidgetManager.updateAppWidget(appWidgetIds, vView1);
}
}

Thanks Peter

UPDATE #1:
Thanks Curtis,

i added your method like this

    private static DataBaseHelper getDatabaseHelper(Context context) {
    DataBaseHelper dbh = null;
    if (dbh == null) {
        dbh = new DataBaseHelper(context);
        dbh.openDataBase();
    }
    return dbh;
}

but now getting this error

10-30 08:32:53.882: E/AndroidRuntime(296): java.lang.RuntimeException: Unable to start receiver com.droidfish.apps.acli.RecieptOfTheDayWidget: java.lang.IllegalStateException: get field slot from row 0 col -1 failed

It looks like its unable to get a Random number from the range of the column count. Is this right? Actually it produce the same error when i write

iRandomID = r.nextInt(3);

Mhh thats really interesting. Any suggestions?

UPDATE #2:
I changed my code like this and it work. There were som important lines missing :))))

Thanks again

        Cursor c1 =getDatabaseHelper(context).getReadableDatabase().rawQuery("SELECT _id from reciept_variant", null);
    Random r = new Random();
    int iRandomID = 1;
    int iVName = c1.getColumnIndex("_id");
    int iCountDataSet;
    for (c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()) {
        iCountDataSet = c1.getCount();
        //iRandomID = r.nextInt(3);
        iRandomID = r.nextInt(iCountDataSet);
        Log.d("Random: ", (Integer.toString(iRandomID)));

    }
    Cursor c2 = getDatabaseHelper(context).getReadableDatabase().rawQuery("SELECT _id, name FROM reciept_variant WHERE _id = 3"
                , null);

    int iName2 = c2.getColumnIndex("name");
    for (c2.moveToFirst(); !c2.isAfterLast(); c2.moveToNext()) {
        sNameVariant = c2.getString(iName2);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终难愈 2024-12-20 05:44:30

彼得,看来您从未初始化数据库帮助程序类。因此它被设置为 null,并且您可能会遇到空指针异常。尝试添加以下代码:

private static DataBaseHelper getDatabaseHelper(){
  if(dbh==null){
     dbh = new DatabaseHelper(/* put your database helper arguments here */);
     dbh.openDatabase();
  }
  return dbh;
}

然后每当您需要使用 dbh 时,就调用 getDatabaseHelper。例如,在 updateWidgetContent() 方法中执行以下操作:

 Cursor c1 = getDatabaseHelper().getReadableDatabase().rawQuery("SELECT _id from reciept");

Peter, it looks like you never initialize your Database helper class. It is therefore set to null and you're probably getting a null pointer exception. Try adding the following code:

private static DataBaseHelper getDatabaseHelper(){
  if(dbh==null){
     dbh = new DatabaseHelper(/* put your database helper arguments here */);
     dbh.openDatabase();
  }
  return dbh;
}

Then whenever you need to use the dbh, you call getDatabaseHelper. For instance, in you updateWidgetContent() method do this:

 Cursor c1 = getDatabaseHelper().getReadableDatabase().rawQuery("SELECT _id from reciept");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文