I am implementing news widget for android. In the onUpdate I am fetching all the data (about 50 articles which contains some text and urls). I wish to implement left and right buttons to cycle between the news items. But onReceive I can only call onUpdate and onUpdate will fetch all the items again. How can I implement left and right click without fetching all the data again but using existing data. And another question, if I define global variable in AppWidgetProvider does it collected by garbage collector at some point or it "lives" forever with the widget?
Code:
public class MyWidgetProvider extends AppWidgetProvider {
private static final String RIGHT_CLICKED = "RIGHT_CLICKED";
private static final String LEFT_CLICKED = "LEF_CLICKED";
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (RIGHT_CLICKED.equals(intent.getAction())) {
//Get next content on list
}
if (LEFT_CLICKED.equals(intent.getAction())) {
//Get prev content on list
}
}
@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//Fetching all stories from RSS
RSSFetchCallback rssFetchCallback = new RSSFetchCallback() {
@Override
public void onComplete(ArrayList<Story> stories) {
ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget);
remoteViews.setTextViewText(R.id.textViewContent, stories.get(0).getContent()); //Setting 0 story for example
remoteViews.setTextViewText(R.id.textViewHeadline, stories.get(0).getTitle()); //Setting 0 story for example
remoteViews.setOnClickPendingIntent(R.id.buttonRight, getPendingSelfIntent(context, RIGHT_CLICKED));
remoteViews.setOnClickPendingIntent(R.id.buttonLeft, getPendingSelfIntent(context, LEFT_CLICKED));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
//Loading R.id.imageView with Glide
AppWidgetTarget awt = new AppWidgetTarget(context, R.id.imageView, remoteViews, widgetId) {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
super.onResourceReady(resource, transition);
}
};
RequestOptions options = new RequestOptions().override(300, 300).placeholder(R.mipmap.ic_launcher).error(R.mipmap.ic_launcher);
Glide.with(context.getApplicationContext())
.asBitmap()
.load(stories.get(0).getImgUrl())//Setting 0 story image for example
.apply(options)
.into(awt);
//End Loading R.id.imageView with Glide
}
}
};
RSSFetcher.getData(rssFetchCallback);
}
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
}