I need to fill form and by pressing "Back" button save it , let's say, to preferences.
Or even show it to Log.
The problem is when I use onBackPressed() - Activity goes to onPause() and myEditText.getText().toString() returns result from XML and not the result that was actually in myEditText field. Same thing goes for onDestroy().
Of course, if I hang someButton.onClickListener() it saves my data well from myEditText because Activity doesn't go onPause() and doesn't take result from XML, but I need to save it exactly by pressing back button.
The code is basic:
EditText etCompetitionName;
Competition competition;
etCompetitionName=(EditText) findViewById(R.id.etCompetitionName);
Intent intent=getIntent();//I get number of object to work with
pos=intent.getIntExtra("pos", -1); // this is this number
competition=getObject(pos);// well, this is loading this object
olDetCompetitionName=competition.getName();//getting name from loaded object
etCompetitionName.setText(olDetCompetitionName);//set this text to EditText field
...
then :
protected void onDestroy() {
super.onDestroy();
//try to save
competition.setName(etCompetitionName.getText().toString());
saveObject(competition);
}
So, it saves old value, the one I set in the beggining. If I don't set it - it will be taken from layout xml. It is issue of onPause() I need to avoid it.
Your question is quite confusing but if you override onBackPressed() you can get the data.
#Override
public void onBackPressed()
{
String text = myEditText.getText().toString();
// save text
super.onBackPressed();
}
I know you said you did this but show how you are doing it if this doesn't work. This will put whatever the user has typed in the text variable then you can save it in SharedPreferences or wherever you want.
You can also do the same thing in onPause() if you want it to save if, say, something else comes in the foreground.
SecondActivity.Java -> I saved two edittext value in SharedPReference and called the MainActivity intent
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor editor = sharedPreferences.edit();
editor.putString("1", a.getText().toString());
editor.putString("2", b.getText().toString());
editor.commit();
Intent i = new Intent(SecondActivity.this,MainActivity.class);
SecondActivity.this.startActivity(i);
}
MainActivity.Java -> I have a button listener to show a Toast with values from the sharedpreference.
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String a = pref.getString("1", "") ;
String b = pref.getString("2", "");
Toast.makeText(getApplicationContext(),a+" "+b, Toast.LENGTH_LONG).show();
}
});
Related
So i need checkboxes to save state when i exit or switch activity. I need many checkboxes, so I need a function that works for all the checkboxes.
please help.
the simple solution is to use SharedPreferences,
you can read about it here
Code
create these 2 methods in your activity :
private void saveCheckboxesStates(){
SharedPreferences sharedPref =getActivity().getSharedPreferences("fileName",Context.MODE_PRIVATE);//replace fileName with any name you like
SharedPreferences.Editor editor = sharedPref.edit();
//suppose we have 3 checkboxes that we want to save their states
editor.putBoolean("checkbox1_state", checkBox1.isChecked()));
editor.putBoolean("checkbox2_state", checkBox2.isChecked()));
editor.putBoolean("checkbox3_state", checkBox3.isChecked()));
editor.apply();
}
private void loadCheckboxesStates(){
SharedPreferences sharedPref = getActivity().getSharedPreferences("fileName",Context.MODE_PRIVATE);
boolean checkbox1State= sharedPref.getBoolean("checkbox1_state", false);
boolean checkbox2State= sharedPref.getBoolean("checkbox2_state", false);
boolean checkbox3State= sharedPref.getBoolean("checkbox3_state", false);
checkBox1.setChecked(checkbox1State);
checkBox2.setChecked(checkbox2State);
checkBox3.setChecked(checkbox3State);
}
now override onBackPressed and onDestroy methods and call saveCheckboxesStates like that:
#Override
public void onBackPressed() {
super.onBackPressed();
saveCheckboxesStates();
}//this handle the case when the user clicks back the activity
#Override
public void onDestroy () {
super.onDestroy();
saveCheckboxesStates();
}//this handle the case when your app gets killed
then call the method loadCheckboxesStates in your onCreate method and you are done.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am just learning to build some applications in Android. Out of curiosity, I have a small and weird problem using Shared Preferences. If someone can help me addressing this issue , I would be most thankful to them. Anyways,here goes the problem. I have 2 Activities. 1. Activity 1 : Consists of just one button that will get you to the next activity. 2. Activity 2 : Consists of a listview with checkbox (simple_list_item_checked or simple_list_multi_choice_item).
My question is: I open my application, hit the button on my first activity screen, this moves me to the second activity. I check an item in the listview. I hit the back button on my phone, go to the first activity, again press the button on my activity 1 screen, this takes me to the list again. Now I just leave my list item checked(I don't change anything that is already checked previously). Now again, I hit back button on my phone, get back to activity one. Now again when I press the button on my activity one screen. It takes me back to the listview but SURPRISINGLY nothing is checked. To note a point here, I had also set and retrieved my shared preference.
MY QUESTION IN A SINGLE LINE IS : If I don't change a value in the check list while I'm in that Activity and then go back to the Main Activity, and get back to the same check list activity, my shared preference does not load what has been saved earlier. Is this the normal behavior of Shared Preference or is it a problem in the coding.
I would just like to know how preference values are saved and retrieved and how long does a preference save a value ? I mean the lifecycle of the saved value in preference.
MY SECOND QUESTION : Also, I would like to know one more thing in activity life cycle. When I am in the second activity as explained in the above example. Now I press the home button , now I go to the background tasks and clear all the tasks(Apps) that are running . Now, my question is which state of activity life cycle is followed or what will be the final activity lifecycle before i clear all my apps from the background ? Please someone help me out on this. Thanks to all those creative developers out there in advance. Hope someone can solve my issue.
public class Secondact extends ListActivity {
ListView list;
SharedPreferences pref;
int pos,itemposition,positionvalue;
boolean boolval,checkvalue;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.secondact);
Toast.makeText(getApplicationContext(), "ONCREATE", 50).show();
list=getListView();
String[] family_array=this.getResources().getStringArray(R.array.family);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,family_array);
list.setAdapter(adapter);
list.setChoiceMode(1);
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
Toast.makeText(getApplicationContext(), "DATA LOADED ITEM NO:"+pos, 50).show();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
pos=position;
list.setItemChecked(pos, true);
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
// Toast.makeText(getApplicationContext(), "PAUSE", 50).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
//Toast.makeText(getApplicationContext(), "RESUME", 50).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
Toast.makeText(getApplicationContext(), "DESTROY", 50).show();
Toast.makeText(getApplicationContext(), "DATA SAVED ITEM NO:"+pos, 50).show();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
//Toast.makeText(getApplicationContext(), "RESTART", 50).show();
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
savedInstanceState.putInt("itempositionno", positionvalue);
savedInstanceState.putBoolean("checkvalue", true);
Toast.makeText(getApplicationContext(), "ONSAVEINSTANCE", 50).show();
list.setItemChecked(pos, checkvalue);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
pos=savedInstanceState.getInt("itempositionno", pos);
checkvalue=savedInstanceState.getBoolean("checkvalue", true);
list.setItemChecked(pos, checkvalue);
Toast.makeText(getApplicationContext(), "ONRESTOREINSTANCE", 50).show();
super.onRestoreInstanceState(savedInstanceState);
}
}
I would just like to know how preference values are saved and
retrieved and how long does a preference save a value ? I mean the
lifecycle of the saved value in preference.
A single line reply to your single line question -
It is saved throughout the life-cycle of the application unless you yourself clear it.
To obtain shared preferences:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
In order to edit(clear) -
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
In order to save -
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();
Read - how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values.
Which state of activity life cycle is followed or what will be the
final activity life-cycle before I clear all my apps from the
background ?
Depends on your requirement. No need to follow final activity life-cycle to do this. For example - When the user logs out from the application, preferences related to the user are of no use and can be cleared independent of the life-cycle just after the log out button press.
Alright, for those who are suffering from the same problem of the shared preference not maintaining the value on activity switch. This piece of logic does the trick:
Set your default value of your row in the listview like this
sp.getInt("CheckedValue",
pass the position of the ealier checked row as the default one
viz.Listitem.getCheckedItemPosition());
This will save the checked value throughout your application's life cycle and/or activity life cycle.
NOTE:
Make sure to clear your sharedpreference before commit() so as to avoid the hectic memory usage of your app.
i'm saving the users login information to SharedPreferences, so he only has to configure his login data once.
This is my onBackPressed method in my Preferences.class (extends PreferenceActivity):
#Override
public void onBackPressed() {
//Login again
Intent intent = new Intent(Preferences.this, LoginActivity.class);
startActivity(intent);
}
What I need is a if-condition which checks, if the preferences changed or not.:
If the user opens the Preferences Activity (edit: from any View(!)), and does not change anything and clicks the backbutton -> just go back to last state.
If the preferences changed: call LoginActivity.
Couldnt find a solution yet and the LoginActivity gets called whenever i hit the backbutton.
Thanks in advance,
Marley
To determine if there was a change in SharedPreferences you have to assign a OnSharedPreferenceChangeListener to your SharedPreferences object like this:
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
in this case I'm doing it in my Application class that's implementing:
public class YambaAppObj extends Application implements OnSharedPreferenceChangeListener
Then you will have to override:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
//this method will be called when preferences are changed.
//do here what you want to record the change
Log.d(TAG , "onSharedPreferenceChanged for:" + key);
}
and then you could check this record in your onBackPressed() method of your Preferences Activity and act accordingly.
You can use OnSharedPreferenceChangeListener or (depending on what you really meany by changed) you can try utilising onSharedPreferenceChanged() like:
protected Boolean mPrefsChanged = false;
#Override
public void onSharedPreferenceChanged( SharedPreferences sharedPreferences,
String key ) {
mPrefsChanged = true;
}
of course it's far from perfect, but at least you got more options
I'm a rookie in android programming. I have a small problem. When I click a ImageView, I make that ImageView invisible and set a Button to visible. My problem is that how do you save this? For eg, I click the ImageView, Button shows up and ImageView disappears. And I exit the app and enter back into that same activity and I want that Button to remain there. How do I go about doing that?
Thanks!
Use SharedPreferences. here is a good tutorial on how to use them. example
But basically you are good to go by adding this code to your Activity
private boolean isVisible;
#Override
public void onCreate(Bundle myBundle){
super.onCreate(myBundle);
isVisible = getPreferences(MODE_PRIVATE).getBoolean("visible", true);
.... your code
if (isVisible){
// show ImageView
} else {
//don't
}
}
}
public void onPause(){
if(isFinishing()){
getPreferences(MODE_PRIVATE)
.edit().
putBoolean("visible", isVisible).commit();
}
}
Use a shared preference to save the state, i.e. say in your case a boolean value to indicate whether imageview was visible or not when you exit the app.
When you launch the app, use this value and accordingly perform the action.
For usage of shared preference,
How to use SharedPreferences in Android to store, fetch and edit values
you can store the state in shared preference when you leave your app onPause() or on the click event and can get result back on onCreate() method from that preferences
To store data in shared preference(in OnPause() or on the click event):
SharedPreferences prefs = getSharedPreferences("yourPrefName", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
// save values
editor.putBoolean("isButtonVisible", true);
editor.commit();
To get data from sharedPrefs(in onCreate()):
SharedPreferences prefs = getSharedPreferences("yourPrefName", MODE_PRIVATE);
boolean btnstatus = prefs.getBoolean(Constants.IS_LOGIN, false);
if (btnstatus) {
//put the code to show button and hide imageview
}
I have 2 views in my app. A form input and a screen to review the form data and confirm. The user inputs the data on the form submission screen in edittext fields. When the user clicks submit, they are presented with the data they input and a 'back' and 'confirm' button. I want it so that if the user presses back, they are returned to the form input screen and the data they input should still be in the editText fields.
At the moment, I am using an onClickListener to point to the form submission screen but the forms are all blank. How do I keep the data in them?
This is the onClickListener:
bBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent j = new Intent(FormConfirm.this, FormCreate.class);
startActivity(j);
}
});
i don't know how to write code on android apps, but i think, why you not to store them into variable flag and call them on edit text field?
for example, if you already fill the form and click submit, you can make a function for store data first on variable flag and show the data in form submission, so when you click back button, you can call the value that you store on variable flag into edittext.
i hope my answer can give you some inspiration
As stated you should save the values somehow, for example by using SharedPreferences.
As an example, when you go from the Input-form Activity to the Submit-form Activity:
bSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent j = new Intent(FormCreate.this, FormSubmit.class);
saveInput();
startActivity(j);
}
});
Where the method saveInput() could look something like:
private void saveInput() {
EditText input = (EditText) findViewById(R.id.someId);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().putString("input",input.getText().toString()).commit();
}
And then, when you press back, the back action could simply be something like:
bBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FormConfirm.this.finish();
}
});
That will cause the current activity to exit and your previous activity will be visible. If you want to display the last saved input when the Input-form Activity starts, you can simply do something like this:
private void loadInput(){
EditText input = (EditText) findViewById(R.id.someId);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String savedText = getString("input", "default input text");
input.setText(savedText);
}
and call that method in the onCreate-method in your Input-form Activity.
Had an inspiration and found a workaround that might not necessarily be correct but it works :) just changed the Java code for the activity to the following:
bBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});