Android SharedPreferences没有保存

Hak*_*ton 2 android sharedpreferences android-appwidget

我正在访问AppWidgetProvider子类中的SharedPreferences,如下所示:

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.d( TAG, "WidgetProvider.onReceive " + intent.getAction() );
        Toast.makeText( context, "WidgetProvider.onReceive " + intent.getAction(), Toast.LENGTH_LONG ); // TOAST NOT WORKING

        Bundle pExtra = intent.getExtras();
        if ( pExtra != null ) {
            SharedPreferences pref = context.getApplicationContext().getSharedPreferences("widget_pref", Context.MODE_PRIVATE );
            int iWidgetId = intent.getExtras().getInt("widgetId");
            int iCount = pref.getInt("widgetCount", 0);
                    // HERE IS THE PROBLEM, iCount will always start from 0!
            for ( int i = 0; i < 10; i++ ) {
                iCount = pref.getInt("widgetCount", 0);
                iCount++;
                pref.edit().putInt("widgetCount", iCount);
                boolean bSaved = pref.edit().commit(); // return TRUE
                bSaved = pref.contains("widgetCount"); // return FALSE
                Log.w(TAG, "WidgetProvider.onReceive: " + iWidgetId + " > " + iCount + " result: " + bSaved);
            }

                    // non-relevant code
            RemoteViews remoteViews = new RemoteViews( context.getPackageName(), R.layout.widget_layout );
            remoteViews.setTextViewText( R.id.hellotextview, "ID: " + iWidgetId + " > " + iCount );
            Intent clickIntent = new Intent( context, WidgetProvider.class );
            clickIntent.setAction("WIDGET_PROVIDER_CLICKED");
            clickIntent.putExtra("widgetId", iWidgetId);
            PendingIntent clickPendingIntent = PendingIntent.getBroadcast( context, 0, clickIntent, 0 );
            remoteViews.setOnClickPendingIntent( R.id.hellolayout, clickPendingIntent );
//          AppWidgetManager.getInstance(context).updateAppWidget( iWidgetId, remoteViews );
//          ComponentName name = new ComponentName(context, WidgetProvider.class);
            ComponentName name = new ComponentName(context.getApplicationContext(), WidgetProvider.class);
            AppWidgetManager.getInstance(context).updateAppWidget(name, remoteViews);
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,正如您从评论中看到的那样,即使我正在循环并保存iCount,也将始终从默认值开始.即使我只是提交,contains()甚至返回false.我尝试了不同的获取SharedPreferences的方法(直接使用上下文,或context.getApplicationContext()以及不同的Context.MODE_XXX)

提前致谢!

Zen*_*aro 7

SharedPreferences.Editor每次通过在进入for循环之前调用pref.edit().Cache SharedPreferences.Editor对象并重新使用该实例来创建新对象.