Saving State Of Activity Android - android

How can I save state of activity that setBackgroundResource and setTextColor I have set up in if sentence remains changed when I start activity again?
if (cases == 1) {
TextView layout = (TextView) findViewById(R.id.textView1);
layout.setBackgroundResource(R.drawable.izbrano);
layout.setTextColor(Color.parseColor("#d7a308"));
ImageView image = (ImageView) findViewById(R.id.imageOdprto);
image.setImageResource(R.drawable.o1);
String strIi = formatter.format(cases);
text.setText(strIi + "€");
}

It seems that you need to store settings instead of the Activity's state. In this case I would suggest using SharedPreferences.

Maybe it is more easy just to remember your cases value (assumed it is global):
#Override
public void onPause(){
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("cases", cases);
editor.commit();
super.onPause();
}
#Override
public void onResume(){
super.onResume();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
cases = sharedPref.getInt("cases", 0);
if ( cases == 0 ){
// do stuff
} else {
// do more stuff
}
}

Using preferences is not much more preferred.
Here is a nice tutorial for how to save activity states. Check this Link
it suggests,
int someVar;
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("someVar", someVar);
outState.putString(“text”, tv1.getText().toString());
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
someVar = savedInstanceState.getInt("someVar", 0);
tv1.setText(savedInstanceState.getString(“text”));
}

Related

How to handle ToggleButton state in OnPause and OnResume state

I am facing problem with toggle button state on onResume() and onPause() state.
Activity - A (first user toggle ON the button) then go back to Activity - B, then it will comeback to Activity - A then I want toggle Button is ON not OFF, how to handle this state in android.
By default Activity handles its components state which has an id attribute.
If it's not acting like that, you can use onSaveInstanceState and onRestoreInstanceState to handle components state manually:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("Toggle1", toggle.isChecked());
// etc.
}
And to restore the state:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
boolean toggle1State = savedInstanceState.getBoolean("Toggle1");
toggle1.setCheched(toggle1State);
}
toggle_relative.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
#Override
public void onToggle(boolean on) {
if (on == true){
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("toggle_relative", true); // value to store
editor.commit();
Toast.makeText(getContext(),"Relatives will be notified in case of accidental situation",Toast.LENGTH_LONG).show();
}else {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("toggle_relative", false); // value to store
editor.commit();
}
}
});
#Override
public void onResume() {
super.onResume();
boolean boll_toggle_relative = preferences.getBoolean("toggle_relative", false); //default is true
if (boll_toggle_relative == true)
{
toggle_relative.setToggleOn();
}
else
{
toggle_relative.setToggleOff();
}
}

Load preferences in another activity?

I stored a value in my MainActivity called "tgpref".
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); //value to save
editor.commit();"
In my onCreate i have
public SharedPreferences preferences;
---
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = getPreferences(MODE_PRIVATE);
I want to display the value in my widget so i try to write in the onUpdate in widget provider class this
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean tgpref = preferences.getBoolean("tgpref", false)
if (tgpref == true) {
remoteViews.setTextViewText(R.id.battery, "Risp on");
} else {
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
If the toggle button in the MainActivty is clicked i want that in my widget appears "Risp on" else "Risp off". Right now displays only "Risp off" so i don't know how i can do. Any helps? Nothing happen i can't load the value
it looks good, so i guess your button doesn`t trigger the value change?!
MainActiviy
private Boolean mTgpref;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
//get value from shared preferences and update ui
prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
mTgpref = prefs.getBoolean("tgpref", false);
setYourText();
}
private void setYourTextAndStoreToSharedPref(){
Log.i("TEST","mTgpref -> " + mTgpref); //check value
if(mTgpref){
remoteViews.setTextViewText(R.id.battery, "Risp on");
}
else
{
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
prefs.edit().putBoolean("tgpref", mTgpref).commit();
//UPDATE YOUR WIDGET HERE
}
//function called on switch button click
private void onSwitchClickButtonClick(){
mTgpref = !mTgpref; //toggle Boolean
setYourText();
}
EDIT
Sorry, I misunderstood your main problem. After updating SharedPreferences, you should follow the steps described here: http://developer.android.com/guide/topics/appwidgets/index.html#UpdatingFromTheConfiguration

SharedPreferences Android - Saving and editing one string only using two activities

I have a single string which the user will edit and will be displayed back to him when he uses the app. He can edit the string at any time. I am familiar with SQLite databases, but because for this purpose I am using only one string/one record, I felt SharedPreferences would be better. However, after following two different tutorials, I am unable to get it so save the data. In both cases I have needed to amend the tutorial code because I will be using two activities, one to view the code, the other to edit it. I was unable to find a tutorial for using sharedpreferences for two activities. Below is the code.
Class to view the code:
public class MissionOverviewActivity extends Activity {
TextView textSavedMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_view);
textSavedMem1 = (TextView)findViewById(R.id.textSavedMem1);
LoadPreferences();
textSavedMem1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
return;
}});
};
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
textSavedMem1.setText(strSavedMem1);
}
}
Class to edit the code and return to the view page
public class MissionDetailActivity extends Activity {
EditText editText1;
Button buttonSaveMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_edit);
editText1 = (EditText)findViewById(R.id.editText1);
buttonSaveMem1 = (Button)findViewById(R.id.buttonSaveMem1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
viewStatement();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
protected void viewStatement() {
Intent i = new Intent(this, MissionOverviewActivity.class);
startActivity(i);
}
}
If any body could answer this question, or point me in the direction of a sharedpreferences tutorial that uses two classes (for edit and displaying), It would be greatly appreciated!
Thanks
getPreferences(int) is private for Activity, you want to share the same SharedPreference between activities you should use this way:
SharedPreferences prefs = this.getSharedPreferences(
"yourfilename", Context.MODE_PRIVATE);
and use the same method when you want to reload it. here the doc for getPrerences(int)

how to save some value in sharedpreferences and get that in next activity

I'm creating a Quiz App, I ask some questions and give options in the form of radio buttons, now I want to store value of of answer (plus on right answer and minus on wrong one) in SharedPreferences and show that result in other activity. I have searched and found this answer here
I used that but still I'm unable to get my desired results
My code Looks Like :
Main Activity which saves some value in SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences saveScore;
private SharedPreferences.Editor editor;
RadioGroup group;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
saveScore = getPreferences(MODE_PRIVATE);
}
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
editor = saveScore.edit();
editor.putInt("score", -1);
editor.commit();
}else{
editor = saveScore.edit();
editor.putInt("score", 1);
editor.commit();
}
Intent intent = new Intent (MainActivity.this, NextActivity.class);
startActivity(intent);
}}
this is the Next Activity which tries to get values from SharedPreferences:
public class NextActivity extends Activity{
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);
int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );
}}
does any one know how to that?
You should change the line
saveScore = getPreferences(MODE_PRIVATE);
To
saveScore = getSharedPreferences("score",Context.MODE_PRIVATE);
Store the value when navigating to nextActivity during onPause() as below:
#Override
protected void onPause()
{
super.onPause();
// Store values between instances here
SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourStringKeyValue", "StringValue"); // value to store
// Commit to storage
editor.commit();
}
and get the data with that key in next Activity's onCreate as below:
SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0);
String name= preferences.getString("YourStringKeyValue","");
try this,
public class DataStorage {
private static String KEY;
public static SharedPreferences savedSession;
public void saveID(Context context, String msessionid) {
// TODO Auto-generated method stub
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("SESSION_UID", msessionid);
editor.commit();
}
public String getID(Context context) {
savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
return savedSession.getString("SESSION_UID", "");
}
}
Edit:
DataStorage mdata = new DataStorage();
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
mdata.saveId(Mainactivity.this,1);
}else{
mdata.saveId(Mainactivity.this,-1);
}
And then get value from NextActivity.
DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);
You're using the wrong preference file, the getPreference function on Activity returns a file private to that Activity. You need to use the named file version- getSharedPreferences(name, mode)

save the state when back button is pressed

I am developing an android app. If I press a back button the state of my application should be saved .What should i use to save the state ..am confused with all of these onPause(),onResume(), or onRestoresavedInstance() ??? which of these should i use to save the state of my application?? For eg when i press exit button my entire app should exit i have used finish() ?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s1=(Button)findViewById(R.id.sn1);
s1.setOnClickListener(this);
LoadPreferences();
s1.setEnabled(false);
}
public void SavePreferences()
{
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", s1.isEnabled());
}
public void LoadPreferences()
{
System.out.println("LoadPrefe");
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
s1.setEnabled(state);
}
#Override
public void onBackPressed()
{
System.out.println("backbutton");
SavePreferences();
super.onBackPressed();
}
What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,
#Override
public void onBackPressed() {
super.onBackPressed();
}
And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}
you can use this way
public void onBackPressed() {
// Save settings here
};
Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
save your application state in this method.

Categories

Resources