I tried lots of solutions but after weeks i have not been able to solve this issue: why "notifyappwidgetviewdatachanged" doesn't work? how can i update a listview placed on my widget? Where am i wrong?
Here are my classes.
Widget Provider:
public class Widget_Provider extends AppWidgetProvider
{
public static final String ACTION_MOSTRAORARI = "fACTION_TOAST";
public static final String EXTRA_STRING = "EXTRA_STRING";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds)
{
RemoteViews views = updateWidgetListView(context, appWidgetId);
final Intent onItemClick = new Intent(context, Widget_Provider.class);
onItemClick.setAction(ACTION_MOSTRAORARI);
onItemClick.setData(Uri.parse(onItemClick.toUri(Intent.URI_INTENT_SCHEME)));
final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0, onItemClick, PendingIntent.FLAG_UPDATE_CURRENT);
views.setPendingIntentTemplate(R.id.myStopList, onClickPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
public RemoteViews updateWidgetListView(Context context, int appWidgetId)
{
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent svcIntent = new Intent(context, Widget_Service.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
remoteViews.setRemoteAdapter(R.id.myStopList, svcIntent);
return remoteViews;
}
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(ACTION_MOSTRAORARI)) {
if (MainUtils.isNewtworkAvailable(context))
{
String item = intent.getExtras().getString(EXTRA_STRING);
Intent intentOrari = new Intent(context, Diag_MostraOrari.class);
intentOrari.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intentOrari);
}
}
super.onReceive(context, intent);
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {}
#Override
public void onEnabled(Context context) {}
#Override
public void onDisabled(Context context) {}
}
Widget Service:
public class Widget_Service extends RemoteViewsService
{
#Override
public RemoteViewsFactory onGetViewFactory(Intent intent)
{
Map<String, ArrayList<String>> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
/* ---
* Here i fetch data from a local db and store it on "map"
*/ ---
return (new Widget_ListProvider(this.getApplicationContext(), intent, map));
}
}
ListProvider:
public class Widget_ListProvider implements RemoteViewsFactory
{
private Map<String, ArrayList<String>> map = new HashMap<>();
private ArrayList<ListItem_Widget> listItemList = new ArrayList<>();
private Context context = null;
private int appWidgetId;
public Widget_ListProvider(Context context, Intent intent, Map<String, ArrayList<String>> map)
{
this.map = map;
this.context = context;
appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
populateListItem();
}
//This function populate the arraylist "listItemList" by the data stored on "map"
private void populateListItem() { [...] }
#Override
public int getCount() {
return listItemList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public RemoteViews getViewAt(int position)
{
final RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.listitem_widget);
ListItem_Widget listItem = listItemList.get(position);
remoteView.setTextViewText(R.id.heading, listItem.heading);
remoteView.setTextViewText(R.id.content, listItem.content);
final Intent fillInIntent = new Intent();
fillInIntent.setAction(Widget.ACTION_MOSTRAORARI);
final Bundle bundle = new Bundle();
bundle.putString(Widget.EXTRA_STRING, listItem.heading);
fillInIntent.putExtras(bundle);
remoteView.setOnClickFillInIntent(R.id.listrow, fillInIntent);
return remoteView;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public void onCreate() {}
#Override
public void onDataSetChanged() {}
#Override
public void onDestroy() {}
}
The xml of my listview custom item contains just two textviews: "heading" and "content".
Where am i wrong? why when i call "notifyappwidgetviewdatachanged" from another activity nothing happens?
[EDIT]
That's the activity where i need to update my widget.
public class Diag_Line extends AppCompatActivity
{
//[...]
#Override
protected void onCreate(Bundle savedInstanceState)
{
//[...]
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
ComponentName thisAppWidget = new ComponentName(getApplicationContext().getPackageName(), Widget.class.getName());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.myStopList);
//"myStopList" is the id of my listview inside the widget xml.
//[...]
}
}
Well, the problem is a quite obvious: In your RemoteViewsFactory you have an empty method onDataSetChanged(). But when you're triggering notifyAppWidgetViewDataChanged(), you're getting callback in onDataSetChanged(). For better understanding check this pic.
If Diag_Line is a Configuration Activity just make something like this:
appWidgetManager.updateAppWidget(appWidgetIds, views); // views is a RemoteViews that you need to build
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.myStopList);
Also check official documentation here
UPDATE
Some hints for you. If you're working with widget, make all fetching data and fillings RemoteViews on background (IntentService is a nice approach). So just make IntentService and make logic for widget here. Don't forget to make him foreground (only for Android O), if you're triggering your updates by broadcasts. Also you can check library that makes all for you.
In order for notifyAppWidgetViewDataChanged() to work properly
we need to retreive the data in onDataSetChanged() method of RemoteViewSourceFactory
like this:
override fun onDataSetChanged() {
listOfArticles = newsDatabaseRepo.getSynchronouslySavedNews() as ArrayList<Articles>
}
as suggested in here
And have a method to refresh the widget if a change occured:
private fun refreshWidget() {
val appWidgetManager =
AppWidgetManager.getInstance(applicationContext)
val thisAppWidget = ComponentName(
applicationContext.packageName,
MyAppWidgetProvider::class.java.name
)
val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget)
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.stack_view)
}
After calling the above method and once I come out of my App I am able to notice the changes in My Widget
So in order to check if onDataSetChanged is called after notifyAppWidgetViewDataChanged()
I kept a debug point and onDataSetChanged() was called and the list was updated as suggested in here here
Had a similar problem updating my widget, it was calling onDataSetChanged but not refreshing the layout. So in my case I had to set updateAppWidget to null before updating with remoteviews like this:
appWidgetManager.updateAppWidget(appWidgetId, null);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
Looks like there is some sort of caching happening here.
Related
I have an app with a widget showing a listview. I want to update the list based on the recipe that user opens in the app.
To do that first I send a broadcast with an extra integer when activity is open.
Then in widget provider I am setting remote adapter with an intent containing integer received from broadcast.
Now I would expect new RemoteViewsFactory to be created each time so I can extract an integer from an intent and load different list based on this number.
The problem is this only happens when an app is first open, every other time only onDataSetChanged() in MyWidgetRemoteViewsFactory is called so I cannot get the recipe number to update data correctly. The list in widget never gets updated.
How to force widget to recreate RemoteViewsFactory? Based on the other topic on stackoverflow I have tried passing null in appWidgetManager.updateAppWidget(appWidgetId1, null) - this didn't work.
MainListActivity.java - send a broadcast
#Override
public void onItemClickListener(int itemID) {
Intent recipeIntent = new Intent(this, BakingWidgetProvider.class);
recipeIntent.setAction(BakingWidgetProvider.UPDATE_WIDGET_RECIPE);
recipeIntent.putExtra(StepsListActivity.EXTRA_RECIPE_ID, itemID);
sendBroadcast(recipeIntent);
Intent intent = new Intent(MainListActivity.this, StepsListActivity.class);
intent.putExtra(StepsListActivity.EXTRA_RECIPE_ID, itemID);
startActivity(intent);
}
BakingWidgetProvider.java - Receive broadcast
#Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
if (intent.getAction().equals(UPDATE_WIDGET_RECIPE)) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.baking_widget);
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
int viewIndex = intent.getIntExtra(StepsListActivity.EXTRA_RECIPE_ID, 0);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, BakingWidgetProvider.class));
for (int appWidgetId1 : appWidgetIds) {
//trying to pass null to clear the data ?
appWidgetManager.updateAppWidget(appWidgetId1, null);
}
Intent intent2 = new Intent(context, MyWidgetRemoteViewsService.class);
Bundle bundle = new Bundle();
bundle.putInt(StepsListActivity.EXTRA_RECIPE_ID,viewIndex );
intent2.putExtras(bundle);
remoteViews.setRemoteAdapter(R.id.list_view, intent2);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_view);
//empty view
remoteViews.setEmptyView(R.id.list_view, R.id.empty_view);
for (int appWidgetId1 : appWidgetIds) {
appWidgetManager.updateAppWidget(appWidgetId1, remoteViews);
}
}
super.onReceive(context, intent);
}
MyWidgetRemoteViewsService.java - get an integer from an intent to update data properly
public class MyWidgetRemoteViewsService extends RemoteViewsService {
private static final String MyOnClick = "myOnClickTag";
#Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new MyWidgetRemoteViewsFactory(this.getApplicationContext(), intent);
}
class MyWidgetRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
List<Recipe> recipeList;
private Context mContext;
private int mRecipeOpen;
public MyWidgetRemoteViewsFactory(Context context, Intent intent) {
mRecipeOpen = intent.getExtras().getInt(StepsListActivity.EXTRA_RECIPE_ID);
mContext = context;
}
#Override
public void onCreate() {
}
#Override
public void onDataSetChanged() {
recipeList = AppDatabase.getInstance(getApplicationContext()).recipeDao().getAll();
}
#Override
public void onDestroy() {
}
#Override
public int getCount() {
return recipeList.get(mRecipeOpen).ingredients.size();
}
#Override
public RemoteViews getViewAt(int position) {
RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_list_item);
rv.setTextViewText(R.id.quantity, recipeList.get(mRecipeOpen).ingredients.get(position).getQuantity());
rv.setTextViewText(R.id.measurement, recipeList.get(mRecipeOpen).ingredients.get(position).getMeasure());
rv.setTextViewText(R.id.ingredient, recipeList.get(mRecipeOpen).ingredients.get(position).getIngredient());
return rv;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return true;
}
}
}
In the end I had to change my approach.
I have placed MyWidgetRemoteViewsFactory in a separate class and extended BroadcastReceiver. Here in onReceive method I can retrieve the broadcast with the required integer that is sent from BakingWidgetProvider.
Hello can you be so kind to see thoose snippets and tell me why my service doesnt start after calling startService(). I am trying to create a Widget , that runs one service for all widgets on the screen. That service provide a factory to populate a list view. I am new to widgets so if I am doing something wrong please warn me about it.
This is the Widget Provider class:
public class MyWidProvider extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_list_view);
rv.setEmptyView(R.id.mywid_listview, R.id.empty_view);
appWidgetManager.updateAppWidget(appWidgetIds, rv);
Log.d("MyWidProvider", "start service <<<<<<<<<");
//here I am starting the service
Intent intent = new Intent(context, MyWidService.class);
context.startService(intent);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
}
this is the Service:
public class MyWidService extends RemoteViewsService {
Realm realm;
#Override
public MyWidFactory onGetViewFactory(Intent intent) {
Log.d("MyWidService", " onGetViewFactory()<<<<<<<<<<");
Context context = getApplicationContext();
Realm.init(context);
realm = Realm.getDefaultInstance();
realm.isAutoRefresh();
populateRealm();
return new MyWidFactory(context, intent, realm);
}
private void populateRealm() {
realm.executeTransaction((t) ->{
final Task myTask = realm.createObject(Task.class);
myTask.setText("this is random widget Task");
final Task myTask2 = realm.createObject(Task.class);
myTask2.setText("this is my second widget task");
});
}
}
and this is the Factory:
class MyWidFactory implements RemoteViewsService.RemoteViewsFactory {
private Context mContext;
private RealmResults<Task> tasks;
private Realm realm;
MyWidFactory(Context context, Intent intent, Realm realm) {
mContext = context;
this.realm = realm;
}
// Initialize the data set.
public void onCreate() {
Log.d("MyWidFactory", "onCreate() <<<<<<<<");
tasks = realm.where(Task.class).findAll();
}
/*-------------------more methods-------------*/
}
Problem fixed. Turns out I forgot to call some of the methods below:
Intent intent = new Intent(context, MyWidService.class);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
rv.setRemoteAdapter(R.id.mywid_listview, intent);
context.startService(intent);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list_text);
appWidgetManager.updateAppWidget(appWidgetIds, rv);
i am developing a widget for my app. Widget name is history, when user browses any URL i will store it in local db, which widget listing from it.
when i open the widget, it fetches all the details from the local db and showing it in widget's list-view.
1) when i open the widget, first onUpdate method of WidgetProvider is called
2) then onUpdate() will call the service WidgetService
3) then service will call the Widget Factory to update the list-view using locally stored db.
In widget factory it will get the db values and update the lisviews in widget.
the above is the process happening when setting up the widget.
The first class:
public class WidgetProviderFavorite extends AppWidgetProvider {
#SuppressWarnings("deprecation")
#Override
public void onUpdate(Context ctxt, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
for (int i=0; i<appWidgetIds.length; i++) {
Intent svcIntent=new Intent(ctxt, WidgetServiceFavorite.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews widget=new RemoteViews(ctxt.getPackageName(),R.layout.widget_favorite);
widget.setRemoteAdapter(appWidgetIds[i], R.id.listFavoriteLogin,svcIntent);
Intent clickIntent=new Intent(ctxt, WidgetActivityFavorite.class);
PendingIntent clickPI=PendingIntent.getActivity(ctxt, 0,clickIntent,PendingIntent.FLAG_UPDATE_CURRENT);
widget.setPendingIntentTemplate(R.id.listFavoriteLogin, clickPI);
appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
}
super.onUpdate(ctxt, appWidgetManager, appWidgetIds);
}
The second class:
public class WidgetServiceFavorite extends RemoteViewsService {
#Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return(new WidgetFactoryFavorite(this.getApplicationContext(),intent));
}
}
The third class: which is going to fetch and update the listview.
fetching done in construtor and getViewAt() (Its called automatically) will be setting the values.
public class WidgetFactoryFavorite extends Activity implements RemoteViewsService.RemoteViewsFactory {
public WidgetFactoryFavorite(Context ctxt, Intent intent) {
int array_Index=0;
int array_Length=0;
WidgetDatabase db1=new WidgetDatabase(ctxt);
List<WidgetDatabaseModel> facorite = db1.getFavorite();
array_Length=facorite.size();
mNames=new String[array_Length];
mSummary=new String[array_Length];
for (WidgetDatabaseModel cn : facorite) {
mNames[array_Index] =cn.getNAME();
mSummary[array_Index]= cn.getSUMMARY();
array_Index++;
}
this.mCtxt=ctxt;
intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
#Override
public void onCreate() {
// no-op
}
#Override
public void onDestroy() {
// no-op
}
#Override
public int getCount() {
return(mNames.length);
}
#Override
public RemoteViews getViewAt(int position) {
RemoteViews row=new RemoteViews(mCtxt.getPackageName(),
R.layout.widget_rowfavorite);
row.setTextViewText(android.R.id.text1, mNames[position]);
Intent i=new Intent();
Bundle extras=new Bundle();
extras.putString(WidgetProviderFavorite.sExtra_Guid, mGuid[position]);
extras.putString(WidgetProviderFavorite.sExtra_Url, mUrl[position]);
i.putExtras(extras);
row.setOnClickFillInIntent(android.R.id.text1, i);
return(row);
}
#Override
public RemoteViews getLoadingView() {
return(null);
}
#Override
public int getViewTypeCount() {
return(1);
}
#Override
public long getItemId(int position) {
return(position);
}
#Override
public boolean hasStableIds() {
return(true);
}
#Override
public void onDataSetChanged() {
}
}
My Problem is:
Its not syncing side by by side when i browse some URL in my browser. i have used the below code sync when database is updated by new URL.
int[] ids = AppWidgetManager.getInstance(mActivity).getAppWidgetIds(new ComponentName(mActivity, WidgetProviderFavorite.class));
WidgetProviderFavorite myWidget = new WidgetProviderFavorite();
myWidget.onUpdate(mActivity, AppWidgetManager.getInstance(mActivity),ids);
its calling the onUpdate method(). but onUpdate doesn't call the service class which is going to call factory class and upadting the lisview with new database values. the flow i mentioned earlier was not happening when new values added to db.
why service method is not called?
or any other method refresh the list-view when database values changes
Answering my self:
We have to call notifyAppWidgetViewDataChanged() in onUpdateMethod().
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.listView);
Complete OnUpdate():
public class WidgetProviderFavorite extends AppWidgetProvider {
#SuppressWarnings("deprecation")
#Override
public void onUpdate(Context ctxt, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
for (int i=0; i<appWidgetIds.length; i++) {
Intent svcIntent=new Intent(ctxt, WidgetServiceFavorite.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews widget=new RemoteViews(ctxt.getPackageName(),R.layout.widget_favorite);
widget.setRemoteAdapter(appWidgetIds[i], R.id.listFavoriteLogin,svcIntent);
Intent clickIntent=new Intent(ctxt, WidgetActivityFavorite.class);
PendingIntent clickPI=PendingIntent.getActivity(ctxt, 0,clickIntent,PendingIntent.FLAG_UPDATE_CURRENT);
widget.setPendingIntentTemplate(R.id.listFavoriteLogin, clickPI);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.listView);
appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
}
super.onUpdate(ctxt, appWidgetManager, appWidgetIds);
}
I'm a newbie and i'm finding difficulty in getting texts from a string array. I tried creating a widget in my app and i wanted the widget to update it's text view from the string array i declared in the resources folder, but this does not seams to work out. Here is my code.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
public static TextView Quote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Quote = (TextView) findViewById(R.id.appwidget_text);
final String[] Quotes = getResources().getStringArray(R.array.Qoutes);
Random rand = new Random();
int randNum = rand.nextInt(Quotes.length);
Quote.setText(Quotes[randNum]);
}}
NewAppWidget.java
public class NewAppWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = MainActivity.Quote.getText().toString();
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0 , intent, 0);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
remoteViews.setOnClickPendingIntent(R.id.interfaceID,pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}}
Thank You
I have completed one task application in android.And now i create one widget for this application.In my widget i have display list of task for today,which is working correctly.My problem is when i go to my application and add some task in today and then back to the home screen the widget having only old data instead of new data and no modification...please any one help me....
My RemoteFactory class:
public class TaskItemStatus implements RemoteViewsService.RemoteViewsFactory {
Context context;
int appWidgetId;
String statusRemainingTask="false";
String[] items;
private final String TAG = "CalendarViewSample:"
+ this.getClass().getName();
public TaskItemStatus(Context context, Intent intent) {
this.context = context;
appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
getData();
}
#SuppressLint("SimpleDateFormat")
private void getData() {
List<String> listTask=new ArrayList<String>();
Taskdatabase objTaskDb = new Taskdatabase(this.context);
objTaskDb.Open();
Calendar calendarToday = Calendar.getInstance();
SimpleDateFormat simpledateFormat = new SimpleDateFormat("dd-MM-yyyy");
String dateToday = simpledateFormat.format(calendarToday.getTime());
listTask.addAll(objTaskDb.fetchTodayRemainTask(dateToday, statusRemainingTask));
Log.i(TAG,"ListTask:"+listTask.toString());
items=new String[listTask.size()];
items=listTask.toArray(items);
}
#Override
public int getCount() {
return (items.length);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public RemoteViews getViewAt(int position) {
RemoteViews row = new RemoteViews(context.getPackageName(),
R.layout.widgetrow);
row.setTextViewText(android.R.id.text1, items[position]);
Intent i = new Intent();
//Bundle extras = new Bundle();
//extras.putString(WidgetTaskSchedular.EXTRA_WORD, items[position]);
//i.putExtras(extras);
row.setOnClickFillInIntent(android.R.id.text1, i);
return (row);
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public boolean hasStableIds() {
return (true);
}
#Override
public void onCreate() {
}
#Override
public void onDataSetChanged() {
}
#Override
public void onDestroy() {
}
}
WidgetProvider:
public class WidgetTaskSchedular extends AppWidgetProvider {
static int ID;
static final int[] sameid=new int[1];
public static String EXTRA_WORD=
"com.capsone.testing.calendar.WORD";
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getAction().equals("update_widget"))
{
Log.i(TAG,"AppWidgetIds:"+ID);
for(int i=0;i<1;i++)
{
sameid[i]=ID;
Log.i(TAG,"SameId:"+sameid[i]);
onUpdate(context, AppWidgetManager.getInstance(context),sameid);
}
}
}
#SuppressWarnings("deprecation")
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
ID=appWidgetIds[i];
for (int i=0; i<appWidgetIds.length; i++) {
Log.i("Widget","WidgetId:"+appWidgetIds.length);
Intent intentWidgetService=new Intent(context, WidgetService.class);
intentWidgetService.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
intentWidgetService.setData(Uri.parse(intentWidgetService.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews remoteView=new RemoteViews(context.getPackageName(),
R.layout.widgetlayout);
remoteView.setRemoteAdapter(appWidgetIds[i], R.id.listWidget,
intentWidgetService);
Intent clickIntent=new Intent(context, ActionBarActivity.class);
PendingIntent clickPendingIntent=PendingIntent
.getActivity(context, 0,
clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteView.setPendingIntentTemplate(R.id.listWidget, clickPendingIntent);
ComponentName component=new ComponentName(context,WidgetTaskSchedular.class);
appWidgetManager.updateAppWidget(component, remoteView);
}
}
}
AppWidgetProvider class:
ComponentName component = new ComponentName(context, WidgetTaskSchedular.class);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.listWidget);
appWidgetManager.updateAppWidget(component, remoteView);
RemoteView class:
#Override
public void onDataSetChanged() {
// Just copy and paste you getdata() coding here
}
One way to achieve this is when you save the new task in your application just send a broadcast with a custom intent to indicate the change in the underlying database.
Add a receiver to this broadcast in your WidgetTaskSchedular class and in on receive method call the onUpdate method to re-populate data in the widget. Somewhat like this:
public void onReceive(Context context, Intent intent) {
System.out.println("On receive function");
if (intent.getAction().equals("com.android.myapp.myBroadcast")) {
System.out.println("There is an update from app ");
//re populate data or in onUpdate
onUpdate(context, AppWidgetManager.getInstance(context), IDs);
}
super.onReceive(context, intent);
}
PS:Save Ids as a static field or something.I took in the IDs in a static array of integers which I populatedin the onUpdate method,you can also try replacing that part with the following code:
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget);
// Update - here like for example as below
remoteViews.setTextViewText(R.id.yourTextID, "My updated text");
// Trigger widget layout update
AppWidgetManager.getInstance(context).updateAppWidget(
new ComponentName(context, Widget.class), remoteViews);