I have been working on a widget for Android. For this I am trying to display the amount of unread messages as well as the current time. The current time was working just fine, but now that I have added the messages part it crashes when I try to load it. This is my code:
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);
}
}
I am having trouble finding where the error is in my code, so I really hope you guys can help me out!
Edit:
First, remove
c.deactivate()since it is deprecated.I am unfamiliar with
ContentResolver‘s, so just note that any advice I give is based on my own research. I think your issue might be yourWHEREclause in yourCursorquery()? Check out this answer to see if it helps any. You’ll want something very similar to his/herif(c != null)andc.moveToFirst()LogCat is your best friend, whenever you have an issue / exception / error you should paste your LogCat output in the question so we can better help.
Quick tip, to find errors in your code you can use
try–catchand watch yourLogCatHere is an example: