共享首选项未获得更新

时间:2014-04-13 17:02:59

标签: android performance android-layout android-intent android-listview

我有一个主要活动,即创建共享首选项并每小时将其分配给一个值。在那里创建共享首选项,并传递给listview,它使用适配器类来填充和从同一共享首选项中提取值。在第二个活动中,retreiving代码在恢复时写入,以便它可以按下后退时显示更新的数字。看起来像这样,onlisttem点击监听器将控件转发给这个活动,假设要添加或减去值并更新共享首选项,我在onpause和onBackPressed中更新它,因为我认为它太多了,无法放入onClickListener,这是Last counter活动的代码。问题是共享首选项没有得到更新。

ImageButton add,sub,push;
TextView countkeeper, countpusher;
String []hours={"8:30 - 9:30","9:30 - 10:30","10:30 - 11:30","11:30 - 12:30","12:30 - 1:30","1:30 - 2:30","2:30 - 3:30","3:30 - 4:30","4:30 - 5:30"};
int lip,c,target;
Intent i;
SharedPreferences sp,sp1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_counter);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    add=(ImageButton)findViewById(R.id.imageButton1);
    sub=(ImageButton)findViewById(R.id.imageButton2);
    push=(ImageButton)findViewById(R.id.imageButton3);
    countkeeper=(TextView)findViewById(R.id.countkeeper);
    countpusher=(TextView)findViewById(R.id.countpusher);

    sp= getSharedPreferences("Count", MODE_APPEND);
    Log.d("CurrentCountFor"+hours[lip],""+sp.getInt("CurrentCountFor"+hours[lip], 10));
    c=sp.getInt("CurrentCountFor"+hours[lip], 10);
    target=sp.getInt("TargetFor"+hours[lip], 10);



    i=getIntent();
    lip= i.getIntExtra("lip", 0);


    add.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            c = c+1;
            countkeeper.setText("Count for "+hours[lip]+" is "+c+"/"+target);



        }
    });

    sub.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            c=c-1;
            countkeeper.setText("Count for "+hours[lip]+" is "+c+"/"+target);


        }
    });
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    sp1= getSharedPreferences("Count", MODE_APPEND);
    SharedPreferences.Editor edit=sp1.edit();
    edit.putInt("CurrentCountFor"+hours[lip], c);
    sp1.edit().commit();

};

@Override
protected void onPause() {
    super.onPause();
    sp1= getSharedPreferences("Count", MODE_APPEND);
    SharedPreferences.Editor edit=sp1.edit();
    edit.putInt("CurrentCountFor"+hours[lip], c);
    sp1.edit().commit();


};

请帮助任何人。

1 个答案:

答案 0 :(得分:1)

sp1.edit().commit();替换为edit.commit();

你有两次同样的问题。