For storing the value in the counter app you have to click once otherwise it will reset your counter to default value.
I followed this answer Continuing integer counter from sharedpreferences
I have to ask that if I close the app and again re-open the app and don't click once and then again close as it was so how can I get my counter's last session value.
Here is the code :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String PREFS_NAME = "myPrefsFile";
TextView tv;
ImageButton btncount, btnreset;
int counter;
SharedPreferences myPrefs;
String stringCounter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvcounter);
btncount = (ImageButton) findViewById(R.id.btncount);
btnreset = (ImageButton) findViewById(R.id.btnreset);
btncount.setOnClickListener(this);
btnreset.setOnClickListener(this);
try {
myPrefs = getSharedPreferences(PREFS_NAME, counter);
String count = myPrefs.getString("Count", "Counter");
tv.setText(count);
counter = Integer.parseInt(count);
}catch (Exception ex){
ex.printStackTrace();
}
}
@Override
public void onClick(View v) {
if (v == btncount){
counter++;
stringCounter = Integer.toString(counter);
tv.setText(stringCounter);
}
if(v == btnreset){
counter = 0;
stringCounter = Integer.toString(counter);
tv.setText(stringCounter);
}
}
@Override
protected void onPause(){
super.onPause();
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("Count", stringCounter);
editor.commit();
}
}