0

我正在尝试制作一个小部件,用户必须为其提供名称。根据该名称,收集并显示数据。小部件中有一个刷新按钮,用于刷新此数据。

问题是在配置类和 AppWidgetProvider 类之间共享这个名称。我试过的:

  • 只需在小部件中使用 EditText。在 config 类中,在 EditText 中设置名称,并在 AppWidgetProvider 类中检索它。这不起作用,因为我找不到在 AWP 中检索文本的方法。
  • 使用 SharedPreferences:

在配置类中:

c = SelectWidgetStationActivity.this;

// Getting info about the widget that launched this Activity.
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null)
    awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
prefs.edit().putString("widgetname" + awID, name);
prefs.edit().commit();

在 AWP 类中:

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) { //ACTION_WIDGET_RECEIVER is the action fired by the refresh button
        this.onUpdate(context, AppWidgetManager.getInstance(context), AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName("com.app.myapp", "com.app.myapp.MyWidgetProvider")));
    }
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

for (int widgetId : appWidgetIds) {
        name = prefs.getString("widgetname" + widgetId, "N/A"));
    //more code

name一直给我“N/A”。我已经检查过了awID并且widgetId是平等的。这可能是因为我使用了不同的上下文?(这里只是猜测)

那么有什么办法可以解决这个问题呢?

编辑 当我在屏幕上打印上下文时,我得到以下信息:

  • 配置类:com.app.myapp.WidgetConfigActivity@40774d18

  • AWP类:android.app.ReceiverRestrictedContext@406ad290

4

4 回答 4

3

只是出于好奇再次经历了这一点,并注意到了这一点:

prefs.edit().putString("widgetname" + awID, name);
prefs.edit().commit();

这为您提供了 2 个不同的Editor实例。您在这里所做的是获得一位编辑器,输入首选项并不管它。然后你得到一个新的(未更改的)编辑器并提交它(= 没有写入更改)。刚刚在一个小项目上测试过,没有按预期正确提交。

所以尝试用这样的代码替换代码:

Editor e = prefs.edit();
e.putString("widgetname" + awID, name);
e.commit();

或将提交链接到

prefs.edit().putString("widgetname" + awID, name).commit();
于 2011-11-08T14:07:23.347 回答
0
prefs.edit().putString("widgetname" + awID, name);

确保在编写首选项时name不是这样。null否则你会null在再次阅读时得到它,这将返回默认值“N/A”(就像找不到密钥一样)。

于 2011-11-08T13:04:38.620 回答
0

你可以试试

SharedPreferences prefs = context.getSharedPreferences("someName", Context.MODE_PRIVATE);
于 2011-11-08T12:54:00.877 回答
-1
public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";


SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
 //to access data from preference 

uid.setText(pref.getString(PREF_USERNAME, null));

//to set value in preference
   getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
                    .putString(PREF_USERNAME, uid.getText().toString()).commit();
于 2011-11-08T13:11:03.170 回答