androidwidgettextview

Android get textView value inside widget


Is there a way to get value from textView item inside widget ? I have a 2 textViews in my widget layout and on my widget update I want to set new value to one of them and I don't want to change value of the second one. For now when I set value like this

   remoteViews.setTextViewText(R.id.text1, newValue");
   widgetManager.updateAppWidget(thisWidget, remoteViews);

this is setting value of the second textView to default value defined in layout. How to get it to not change the value of the second textView, or how to get value to the second textView to be able to adjust to the same ?


Solution

  • It is my understanding that whenever onUpdate is called, it updates all of the widgets, so what I do is use SharedPreferences, so when I set the TextView initially I save the textView text to sharedprefs and then I get the preference when I update. And I do this all within a for loop.

    Here is my onUpdate:

    @Override
    public void onUpdate(Context context, AppWidgetManager awm, int[] appWidgetIds){
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        int appWidgetId;
        for (int i=0;i<appWidgetIds.length;i++){
                appWidgetId = appWidgetIds[i];
    
                String widgetLabel = pref.getString("label"+appWidgetId, "");
                // I previously saved "widgetLabel" when I created the widget in my 
                // ConfigurationActivity
                M.updateWidget(context, appWidgetId, widgetLabel);
                    // I put this in another class so it's more manageable.
            }
    
    
    
    }
    

    in my Class M:

    public static void updateWidget(Context context, int appWidgetId, String widgetLabel){
    
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
    
            RemoteViews updateViews;
            int layoutId = R.layout.layout;
            int viewId = R.id.layout;
    
            updateViews = new RemoteViews(context.getPackageName(),
                    layoutId);
            updateViews.setTextViewText(R.id.widgetlabel, widgetLabel);
            editor.putString("label"+appWidgetId, widgetLabel);
            editor.commit();
    
            Intent intent = new Intent(context, ClickAction.class); 
            PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            updateViews.setOnClickPendingIntent(viewId, pendingIntent);
    
            AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, updateViews);
        }
    

    I hope that makes sense. Let me know if I need to elaborate on anything.