I am writing an application widget that takes data from the server and displays it in the widget on the Android user’s working screen. The problem is that when the Internet connection is not available and at this point the system updates the widget, the text you set to TextView elements is reset to the default text set in the Android Studio visual editor.

Those. it happens like this:

  1. Install the widget
  2. Internet connection is
  3. Widget successfully updated
  4. Text from server response is set to TextView
  5. No internet connection
  6. The system updates the widget
  7. The previous text in the TextView reset to the value set in android:text=""

I know that somewhere I am doing something wrong, because other widgets do not reset anything when there is no connection to the Internet.

WidgetProvider.java file

 public class WidgetProvider extends AppWidgetProvider { public static String LOG_TAG = "MYAPPLOG"; @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); Log.d(LOG_TAG, "onReceive"); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); Log.d(LOG_TAG, "onUpdate"); for (int widgetID : appWidgetIds) { updateWidget(context, widgetID); } } @Override public void onDeleted(Context context, int[] appWidgetIds) { super.onDeleted(context, appWidgetIds); Log.d(LOG_TAG, "onDeleted"); } public void updateWidget(Context context, int widgetID) { context.startService(new Intent(context, UpdatingService.class).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID)); } } 

File UpdatingService.java

 public class UpdatingService extends IntentService { public static String LOG_TAG = "MYAPPLOG"; public UpdatingService() { super("UpdatingService"); } @Override protected void onHandleIntent(Intent intent) { // здесь получаем widgetID из intent и др. переменные RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.initial_layout); if(isConnected(getApplicationContext())) { String response = getServerResponse(); if(response != null) { try { JSONObject JSON = new JSONObject(response); // берем данные из ответа сервера // устанавливаем во вьюхи remoteViews.setTextViewText(R.id.textView, someText); } catch (JSONException e) { e.printStackTrace(); Log.d(LOG_TAG, "JSONObject failed"); } } else { // LOG: Ошибка соединения с сервером } } else { // LOG: Нет соединения с интернет } // обновляем виджет (устанавливаем клик по виджету) // если не обновить, то кнопка на виджете не будет работать Intent someIntent = new Intent(getApplicationContext(), WidgetProvider.class); someIntent.setAction(WidgetProvider.ACTION_GOTO); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), widgetID, someIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.goToLayout, pendingIntent); AppWidgetManager.getInstance(getApplicationContext().getApplicationContext()) .updateAppWidget(widgetID, remoteViews); } public boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.isConnected()) { return true; } return false; } public String getServerResponse() { // используем HttpURLConnection } } 

I really hope for your help or a little hint. I have already written several widgets and all with this sore. Thank you very much for your attention.

  • So if there is no Internet, do not send a request + do not update the widget. Or is there another problem? - Android Android
  • So I do not send a request if there is no connection. In the above code it can be seen. In the widget there is a button (in the service code above this is shown), which performs some action. If you do not update the widget, then the button will not work. A vicious circle of some kind. - Aleksandr Ostaf
  • So what do you want ? You have no RemoteViews configured and it defaults the values. Implement the logic in the else set, set the text in the widget there is no network etc. Or just update the widget when it received Json, if not, then do not update, then you will always see the latest loaded data in the widget. In my opinion everything is very transparent. - Shwarz Andrei
  • The fact is that if you do not update the widget, the buttons in the widget will stop working (PendingIntent will not be installed). I was told that in ELSE (the case of inactive Internet) I need to get the saved values ​​and set them. But why do the views of the view are reset, if the text from the previous successful update should be installed in it or if the text (values) of the View is set from the previously saved. So one person suggested that you MUST set all the views of the values ​​(color, text, etc.) otherwise it will be taken from XML. It's true? - Aleksandr Ostaf
  • So I am writing the same thing to you, this is a feature of the widget and remoteViews, when updating you need to update everything. You can create a separate class that stores current information and when there is no network loading your view for the widget, everything will work too. - Shwarz Andrei

0