Widget not updating on creation? - Android - android

I've got a widget that shows weather when a button is clicked on it. The widget is supposed to do this update when it's first created, however that's not the case. I have to manually click-update it once I put it on homescreen.
Q. How to I update the widget automatically once it's created?
Things I've tried:
Use onEnabled inside Widget Provider
Use onRecieve inside Widget Provider
My WidgetProvider:
public class Widget extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.rButton, buildButtonPendingIntent(context));
pushWidgetUpdate(context, views);
}
public static PendingIntent buildButtonPendingIntent(Context context) {
Intent intent = new Intent();
intent.setAction("update");
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static void pushWidgetUpdate(Context context, RemoteViews views) {
ComponentName myWidget = new ComponentName(context, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(myWidget, views);
}
}
My BroadcastReceiver:
public class WidgetReceiver extends BroadcastReceiver {
double lat, lon;
String xtemp, xmaxtemp, xmintemp, xcity, xweather, provider, weatherpic;
Location loc;
LocationManager mlocManager;
//======================================= OnReceive Method
#Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals("update")) {
new MyAsyncTask2().execute(context);
}
} catch (Exception e){
e.printStackTrace();
}
}
public class MyAsyncTask2 extends AsyncTask<Context, Void, String> {
//Does all the update for the weather and shows it on the textViews
}
}
I'm new to Widget programming, let me know if I can make any optimizations! :)

Related

notifyappwidgetviewdatachanged not working on a listview on my widget

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.

OnUpdate() not calling the widget service

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

Automatically update widget in the home screen when i make modification in my application

How can we updating the View of a Home Screen Widget on the onReceive method of AppWidgetProvider?.I am trying to update the listview of my Home screen widget but it seems that I cant access the listview of my AppWidgetProvider on onReceive method.My problem is when i changes in my application and come back to the home screen that the widget has no modification.Here is a sample code of my onReceive
public class WidgetTaskSchedular extends AppWidgetProvider {
private final String TAG = "CalendarViewSample:"
+ this.getClass().getName();
static int ID;
int[] sameid=new int[1];
#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);
}
}
}
public static String EXTRA_WORD=
"com.capsone.testing.calendar.WORD";
#SuppressWarnings("deprecation")
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i=0; i<appWidgetIds.length; i++) {
ID=appWidgetIds[i];
Log.i(TAG,"LengthofWidget:"+appWidgetIds.length);
Log.i(TAG,"TestAppWidget:"+appWidgetIds[i]);
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);
}
}
}
MainActivity class:
In this main class i change some modification and broadcast this to widget class using on pause method:
#Override
public void onPause() {
super.onPause();
Intent updateWidget = new Intent(getActivity(), WidgetTaskSchedular.class);
updateWidget.setAction("update_widget");
PendingIntent pending = PendingIntent.getBroadcast(getActivity(), 0, updateWidget, PendingIntent.FLAG_CANCEL_CURRENT);
try {
pending.send();
} catch (CanceledException e) {
e.printStackTrace();
}
}

Cant change ImageView resource on RemoteView Android

I'm trying yo make a simple widget with clickable image that will change when its clicked.
I don't understand why it doesn't work
public class AppWidget extends AppWidgetProvider {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction()==null) {
context.startService(new Intent(context,
ToggleService.class));
} else {
super.onReceive(context, intent);
}
}
#Override
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
context.startService(new Intent(context,
ToggleService.class));
}
public static class ToggleService extends IntentService {
public ToggleService() {
super("AppWidget$ToggleService");
}
#Override
protected void onHandleIntent(Intent intent) {
ComponentName me=new ComponentName(this, AppWidget.class);
AppWidgetManager mgr=AppWidgetManager.getInstance(this);
mgr.updateAppWidget(me, buildUpdate(this));
}
private RemoteViews buildUpdate(Context context) {
RemoteViews updateViews=new
RemoteViews(context.getPackageName(),R.layout.widget);
int a = 1;
if(a ==
1) {
updateViews.setImageViewResource(R.id.phoneState,
R.drawable.dual_off);
} else {
updateViews.setImageViewResource(R.id.phoneState,
R.drawable.dual_on);
}
Intent i=new Intent(this, AppWidget.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i,0);
updateViews.setOnClickPendingIntent(R.id.phoneState,pi);
return updateViews;
}
}
}
I have tried all sort of things in for loop but it just won't change image.
I have done this from a book about android development, am new to java and android.
You would to update your widget by AppWidgetManager, after changing remoteview's source.In this snippet code I try to change layout of widget that it's AppWidgetProvider name is DictionWidgetProvider :
private void hideWidgetInstances() {
hideViews = new RemoteViews(App.getContext().getPackageName(),
R.layout.hide);
AppWidgetManager mManager = AppWidgetManager.getInstance(App
.getContext());
ComponentName cn = new ComponentName(App.getContext(),
DictionWidgetProvider.class);
mManager.updateAppWidget(cn, hideViews);
}
Here App is a class that extends Application.You can use Application Context to reach ComponentName.

How to stop service when removing widget from homescreen

I have a problem with service. I'm trying to do a simple battery level widget but the problem is that I don't know how to stop service when the widget is removed from homescreen.
Here is my service class
public class batteryService extends Service{
AppWidgetManager widgetManager;
private RemoteViews remoteViews;
private ComponentName thisWidget;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
widgetManager = AppWidgetManager.getInstance(context);
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
thisWidget = new ComponentName(context, Widget.class);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)*100;
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float value = (float)level/scale;
remoteViews.setTextViewText(R.id.widget_textview, String.valueOf(value));
widgetManager.updateAppWidget(thisWidget, remoteViews);
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
this.registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
super.onCreate();
}
#Override
public void onDestroy() {
this.unregisterReceiver(mBatInfoReceiver);
super.onDestroy();
}
}
and here widget class
public class Widget extends AppWidgetProvider{
private AppWidgetManager widget_manager;
private RemoteViews remoteViews;
private ComponentName thisWidget;
private Intent intent;
#Override
public void onEnabled(Context context) {
if(intent == null)
{
intent = new Intent(context, batteryService.class);
context.startService(intent);
}
super.onEnabled(context);
}
#Override
public void onDisabled(Context context) {
if(intent != null)
{
context.stopService(intent);
intent = null;
}
super.onDisabled(context);
}
}
When I remove widget from screen the service is still a live. I was trying to change onDisable to onDeleted method but it didn't change anything.
Have you any tips for me ?
Make sure you have the appropriate action in your manifest for the disabled event:
<action android:name="android.appwidget.action.APPWIDGET_DISABLED" />
This would be alongside your existing APPWIDGET_ENABLED and perhaps the classic APPWIDGET_UPDATE actions, for the <receiver> element for your AppWidgetProvider.
Also, please consider not having your service run constantly, but rather updating the battery information once every few minutes using AlarmManager. The battery level simply does not change that often to make it necessary to attempt to keep a service in memory all of the time.
Try by using onDeleted(Context, int[])

Categories

Resources