如何传递数据并从Widget打开活动?

时间:2019-02-24 19:53:16

标签: android widget extra

我有一个只有一个textview的小部件,每24小时更改一次。 我想要的是,当我单击窗口小部件顶部时,使用textview中的文本打开一个活动。

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {

        TinyDB tinydb;
        Random r = new Random();
        int RandomNr;
        tinydb = new TinyDB(context);

            String[] list = tinydb.getListString(Constants.from_Quotes).toArray(new String[0]);
            RandomNr = r.nextInt(list.length - 1);
            String Quote = list[RandomNr];
            Intent intent = new Intent(context, QuoteActivity.class);
            intent.putExtra("StartedFrom", Constants.from_Widget );
            tinydb.putString(Constants.from_Widget,Quote);
            tinydb.putBoolean("WidgedAdded",true);
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.quote_widget);
            views.setTextViewText(R.id.appwidget_text, Quote);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
            views.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent);

            // Instruct the widget manager to update the widget
            appWidgetManager.updateAppWidget(appWidgetId, views);

    }

并且没有多余的内容通过。

在QuoteActivity.java上,我像这样检查:

 try {
           Bundle bundle = getIntent().getExtras();
           StartedFrom = bundle.getString("StartedFrom");
}catch (Exception e){
           e.printStackTrace();
 }

我得到空异常。

我不知道问题出在哪里,知道吗?

1 个答案:

答案 0 :(得分:1)

 void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {

    TinyDB tinydb;
    Random r = new Random();
    int RandomNr;
    tinydb = new TinyDB(context);

        String[] list = tinydb.getListString(Constants.from_Quotes).toArray(new String[0]);
        RandomNr = r.nextInt(list.length - 1);
        String Quote = list[RandomNr];
        Intent intent = new Intent(context, QuoteActivity.class);
        intent.putExtra("StartedFrom", Quote);
        tinydb.putString(Constants.from_Widget,Quote);
        tinydb.putBoolean("WidgedAdded",true);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.quote_widget);
        views.setTextViewText(R.id.appwidget_text, Quote);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);

}


 And in QuoteActivity

 try {
       Bundle bundle = getIntent().getExtras();
       String StartedFrom = bundle.getString("StartedFrom");
 }catch (Exception e){
       e.printStackTrace();
 }