Reputation: 31
i have a main activity which is creating shared preference and assigning it to a value each hour. The shared preferences over there are getting created, and are passed to a listview which is using an adapter class to populate and pulls the values from the same shared preferences And in the second activity the code for retreiving is written in on resume so that it can show updated numbers when back is pressed. which looks something like this, onlisttem click listener forwards the control to this activity which is suppose to add or substract value and update the shared preferences, i am updating it in onpause and onBackPressed, coz i think its too much to put in an onClickListener, here's the code for Last counter activity. The problem is the shared preferences is not getting updated.
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();
};
Help anyone please.
Upvotes: 1
Views: 91
Reputation: 38098
Replace sp1.edit().commit();
with edit.commit();
You have the same issue twice.
Upvotes: 1