How to update android Widget with a string array

286 views Asked by At

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

0

There are 0 answers