Reputation: 37
i have a TextView which shows countdown timer in activity A. and the function for countdown timer is in class B. in activity A:
TextView tvTime = (TextView) findViewById(R.id.tv_time);
B a = new B(tvTime);
a.startTimer(20000);
and in Class B:
public B(TextView tvTime)
{
this.tvTime = tvTime;
}
//Countdown Timer
public void startTimer(int t) {
Log.d("Timer Value outside cdt", ""+t);
timer = new CountDownTimer(t, 1000) {
public void onTick(long millisUntilFinished) {
tvTime.setText(""+millisUntilFinished
/ 1000;);
Log.d("Timer Value outside cdt", ""+millisUntilFinished
/ 1000;);
}
public void onFinish() {
tvTime.setText("000");
}
};
timer.start();
}
and its working fine but when i try to get value of tvTime to save it inSharedPrefs by using following code its not working
public void saveGame(){
time = tvTime.getText().toString();
spEdit.putString(SAVED_TIME, time);
spEdit.commit();
}
Edited:
By adding 2 debug statements I figure it out that the problem is not in saving the value but the problem is there when i call startTimer() on getting stored value
public void getGame(){
startTimer(Integer.valueOf(sp.getString(SAVED_TIME, "0000")));
}
after calling this func i can see the result of
Log.d("Timer Value outside cdt", ""+t);
but 2nd statement show no result
Log.d("Timer Value outside cdt", ""+millisUntilFinished
/ 1000;);
Upvotes: 0
Views: 77
Reputation: 8843
make sure your textview's object is accessible in the particular method
, it might be out of scope for your method. if possible declare your textview object at class level
so all the class's method can use that
public class yourclass
{
TextView tvTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//--- text view---
TextView txtView = (TextView) findViewById(R.id.text_id);
}
public void saveGame(){
time = tvTime.getText().toString();//now you can use your textview here
spEdit.putString(SAVED_TIME, time);
spEdit.commit();
}
}
Upvotes: 0
Reputation: 1444
To store the value in SP:
time = tvTime.getText().toString();
Editor editor = sharedpreferences.edit();
editor.putString("NAME", time );
editor.commit();
To retrieve data from SP:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name= prefs.getString("NAME", null);
Upvotes: 1