0

我一直在为 Android 开发一个小部件。为此,我试图显示未读消息的数量以及当前时间。当前时间工作得很好,但是现在我已经添加了消息部分,当我尝试加载它时它会崩溃。这是我的代码:

public class MyTime extends TimerTask {

RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;
Context context;

java.text.DateFormat format = SimpleDateFormat.getTimeInstance(
        SimpleDateFormat.SHORT, Locale.getDefault());

public MyTime(Context context, AppWidgetManager appWidgetManager) {
    this.appWidgetManager = appWidgetManager;
    remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
    thisWidget = new ComponentName(context, LeafClockWidget.class);

}

@Override
public void run() {
    SimpleDateFormat sdf1 = new SimpleDateFormat("EEEE, MMMM dd");
    Date d = new Date(System.currentTimeMillis());
    String time1 = sdf1.format(d);

    final Uri SMS_INBOX = Uri.parse("content://sms/inbox");

    Cursor c = context.getContentResolver().query(SMS_INBOX, null, "read = 0", null, null);
    int unreadMessagesCount = c.getCount();
    c.deactivate();

    remoteViews.setTextViewText(R.id.widget_textview3, "You have " + c + " unread SMS messages.");

    remoteViews.setTextViewText(R.id.widget_textview1, time1);
    remoteViews.setTextViewText(R.id.widget_textview2, "The time is "
            + format.format(new Date(System.currentTimeMillis())));

    appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}

}

我很难找到我的代码中的错误,所以我真的希望你们能帮助我!

4

1 回答 1

0

编辑:

首先,删除,c.deactivate() 因为它已弃用

我对ContentResolver's 不熟悉,所以请注意,我提供的任何建议都是基于我自己的研究。我认为您的问题可能是您WHERECursor query()? 查看这个答案,看看它是否有帮助。你会想要一些与他/她非常相似的东西,if(c != null)并且c.moveToFirst()


LogCat 是您最好的朋友,每当您遇到问题/异常/错误时,您都应该将您的 LogCat 输出粘贴到问题中,以便我们提供更好的帮助。

快速提示,在您可以使用的代码中查找错误try-catch并观察您的LogCat

这是一个例子:

@Override
public void run() {
    try {
        SimpleDateFormat sdf1 = new SimpleDateFormat("EEEE, MMMM dd");
        Date d = new Date(System.currentTimeMillis());
        String time1 = sdf1.format(d);
    } catch(Exception e1) {
        Log.e("SimpleDateFormat", "FAILED: " + e1.getMessage());
    }


    final Uri SMS_INBOX = Uri.parse("content://sms/inbox");

    try {
        Cursor c = context.getContentResolver().query(SMS_INBOX, null, "read = 0", null, null);
        int unreadMessagesCount = c.getCount();
        c.deactivate();
    } catch (Exception e2) {
        Log.e("Cursor", "FAILED: " + e2.getMessage());
    }

    remoteViews.setTextViewText(R.id.widget_textview3, "You have " + c + " unread SMS messages.");

    remoteViews.setTextViewText(R.id.widget_textview1, time1);
    remoteViews.setTextViewText(R.id.widget_textview2, "The time is "
            + format.format(new Date(System.currentTimeMillis())));

    appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
于 2012-08-31T16:04:39.427 回答