Android: get Widget Data from database(Android:从数据库中获取小部件数据)

本文介绍了Android:从数据库中获取小部件数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


更新 #1:
谢谢柯蒂斯,

我像这样添加了你的方法

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;
}

但现在出现此错误

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?


更新 #2:
我像这样更改了我的代码并且它可以工作.缺少一些重要的行:))))

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

再次感谢

        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);
    }

推荐答案

Peter,看起来你从来没有初始化过你的数据库助手类.因此它被设置为 null 并且您可能会得到一个空指针异常.尝试添加以下代码:

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;
}

然后,当您需要使用 dbh 时,您调用 getDatabaseHelper.例如,在你的 updateWidgetContent() 方法中这样做:

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");

这篇关于Android:从数据库中获取小部件数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!