How can i stop to be refreshed my values in android activity - android

I am working in android. I am designing a file upload functionality.
This is my layout:
If I fill my entries like as title,price,category and then I press browse button for browse option then I go to BrowseActivity using startActivity(). But when I come back to this activity then all entries which were filled by me disappear. please suggest me what should I do for this so my entered entries save. If I do browse first then fill entries then it works properly.
What should I do for the case in which user first fill entries and then click on the browse button?

Use the SharedPreferences options to save all the Strings in onPause(). You can get them back in onResume() and fill out your text boxes. This is also nice since you can save the values that were entered and restore them each time the user leaves the app for any other reason.
EDIT:
Quick example:
Save your strings like so:
#Override
public void onPause(){
super.onPause();
// Save the user preferences during runtime for later use.
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("title", "Value of title");
editor.commit();
}
Then you get get the value back like this.
#Override
public void onResume(){
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
String title = settings.getString("title");
}

Here is what you need to do.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("title", title.getText.toString());
//Do the same for the other 2 boxes.
super.onSaveInstanceState(savedInstanceState);
}
and in onRestoreInstanceState() pull the items out.
Like..
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
String Title = savedInstanceState.getString("title");
//Do the same for other String items you put into the bundle using the savedInstanceState() above. And then use EditText.setText(title); to set the text
}
The bundle is used exactly for this purpose. You Can get more info here

Check out android's shared preferences, they should give you an easy way to store data.
Android Shared Preferences
http://developer.android.com/guide/topics/data/data-storage.html
http://developer.android.com/reference/android/content/SharedPreferences.html
Another way is to create an object which holds the data you need, and don't new it in the onResume method...

Related

Want to clear EditText content before activity goes in background

Use case is when user enters it's info in edittext and intentionally or unintentionally user sends the application in background. In such case I don't want to display edittext info in recent apps list screenshot and when user again resume the app I want to populate same info in edittext.
Another option is:
FLAG_SECURE - treat the content of the window as secure, preventing it from appearing in screenshots or from being viewed on non-secure displays.
More details here
But this also dissallows screenshots (not sure if u want that)
to use this add the following line to your onCreate() :
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
------------------------EDIT-------------------------
If u want to show the application in the "recent apps" list, but without the editText, than u might want to do something like this:
private string mySecretText;
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
//Now we remember the text
mySecretText = myEditText.getText().toString();
//Optional save it in your Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("secretText", mySecretText);
editor.apply();
//Remove the text from the editText
myEditText.setText("");
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//Optional load it from your Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
mySecretText = preferences.getString("secretText", "Default"); //U can remove default if u want
myEditText.setText(mySecretText);
}
------------------------EDIT-------------------------
Or u can change the complete thumbnail:
onCreateThumbnail - Generate a new thumbnail for this activity. This method is called before pausing the activity, and should draw into outBitmap the imagery for the desired thumbnail in the dimensions of that bitmap. It can use the given canvas, which is configured to draw into the bitmap, for rendering if desired.
Important!: The default implementation returns fails and does not draw a thumbnail; this will result in the platform creating its own thumbnail if needed.
So create ur own thumbnail
#Override
public boolean onCreateThumbnail (Bitmap outBitmap, Canvas canvas) {
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.myBitmap);
canvas.drawBitmap(myBitmap, 0, 0, null);
return true;
}
Good luck!
in the async task on execute add these lines
1. If u want to hide edittext box theneditext.setVisibility(View.INVISIBLE);
or
2.if u want to clear the content theneditext.clear();
You can use the activity lifecycle callback methods to clear (.clear()) or populate (.setText("some text")) the EditText.
onResume : the user sees and can interact with the activity.
onPause : the activity is partially or totally in background.
You could save the info as a shared preferences in MODE_PRIVATE for the current activity.
SharedPreferences sharedPreferences;
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
write a shared pref
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("INFO", "some text");
editor.commit();
read a shared pref
String info = sharedPreferences.getString("INFO", "default value");
So you can read the SP in onResume and write it in onPause, just before you clear the EditText content.
You can try the attribute, android:noHistory="true" for the activity tag in the manifest file.
It will destroy the trace.
OR if you want to show blank view in the recent list then:
Override onStop() method and just try resetting the content view of your activity to some blank xml file before you call super.onStop().
Probably, Android framework will make a screenshot of your app for showing in the recent apps when activity.onStop() is called.
Hope it will solve your problem.

variables need to be saved

I am making an application that contains a form and whenever a data clicks a button loads from a BD in a EditText, but every time I press a different button, the other EditText are cleared, I tried with:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("data", myVariable);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
other = savedInstanceState.getString("data");
name.setText(other);
}
Sorry if I have not explained well, I need that every time they change Activity variables and I have not deleted. Any suggestions? Thank you!
Try using Android SharedPreferences instead. This is a persistent key-value storage that Android offers for its apps and was designed to covers issues like this. Here's the easy way to use it:
SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);
// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();
...
// ..and to retrieve it..
prefs.getString("data", null);
// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't
// yet exist.
Hope this helps.

Handling runtime changes in Android for a simple app - do I need to use a Bundle?

I am making my first Android app, which consists of just editText's and Spinner's. Reading up on the activity cycle, I am wondering if it is even necessary to use the Bundle mechanism in my situation.
Since the state of the widgets are automatically persisted -
could I just call the getSelectedItem() method on the spinners and getText() on the EditText's within the onCreate() method for the Activity and pass that on to my newly re-created model object rather than using the Bundle mechanism? What are the advantages and disadvatanges of this approach?
The state of widgets it not automatically persisted. When you activity is destroyed it loses all the information about state. I recommend you saving you application state using shared preferences. Here is an example from google developers site. it allows you to save your application state by storing key-value pairs and it should suffice for your app.
Save the text and spinner item position in shared preferences when your activity is stopped - onStop() and restore the state in onCreate().
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
Although you can save your application state by onSaveInstanceState(Bundle) method, usually the better way will be to do that in onPause() or onStop() methods(the data will be saved for sure). Documentation says:
Note that it is important to save persistent data in onPause() instead
of onSaveInstanceState(Bundle) because the latter is not part of the
lifecycle callbacks, so will not be called in every situation as
described in its documentation.

Whether my private date could be saved when process killed my activity in android?

I have to give a dialog when my activity is launched at first time.
So I do that in my
public void onCreate(Bundle savedInstanceState)
and use
protected void onSaveInstanceState (Bundle outState)
to save the time of my launch. I notice that OS create a new "Bundle outState" instead of using the old one. And I can not debug the the date when re Oncreate.
My question:
The date I saved in onSaveInstanceState , could be really read by Oncreate? And how to debug?
Could I just use a private member vary to save the state and without being deleted by OS when the process is killed by OS.
Thank you for your help.
Bundle cannot be used to carry the data across application restarts.
You'd better save your data to the more permanent storage, like SharedPreferences, put this code in onCreate():
SharedPreferences prefs;
prefs = getSharedPreferences( "preferences", Context.MODE_PRIVATE);
long last_run_time = prefs.getLong( 'last_run', 0 );
if( last_run_time == 0 ) { // zero means your app has never been run
// display dialog, this is the first time!
....
// this saves current system time to prevent your dialog being seen again
prefs.edit().putLong( 'last_run', system.currentTimeMillis() ).commit();
}

How to update internal values of a PreferenceActivity when SharedPreferences change

I use a Preference in a PreferenceActivity to load default values: when this specific Preference is clicked, something like this happens:
private String mResetKeys = "key1,key2,key3";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor prefs_editor = prefs.edit();
for (String current_pref : mResetKeys.split(",")) {
prefs_editor.remove(current_pref);
}
prefs_editor.commit();
But afterwards, the Preferences whose corresponding SharedPreference was reset still show the old value - it seems to be cached in the Preference. Only when I leave the PreferenceActivity and reopen it, the Preferences show the new values.
How can I update the PreferenceActivity programmatically?
I had a similar problem. This probably isn't the most correct fix but it worked for my purposes. Right after I did the commits, I called the Activity.recreate(); method.
The activity will restart (onDestroy()/onCreate()/etc) but for my purposes all I needed was a special handling on one preference. I listened for a certain preference with an OnPreferenceClickListener and made an alert dialog box with a kind of warning message and an option to change their mind. If they did want to change their mind, I did my commit of the new value to the preference activity and then called recreate() so that the checkbox preference would be updated.
However, I am also interested in a way to do this without recreating the activity...
Update preference value without reloading PreferenceActivity
from http://liquidlabs.ca/2011/08/25/update-preference-value-without-reloading-preferenceactivity/
Here is how to update default shared preference value of target element (in this case EditTextPreference)
public class YourCustomPreference extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
// some logic goes above, when you want to reset value and update EditTextPreference value
// For convenience, I am going to wrap two different task in different methods
private void resetPreferenceValue() {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefEditor = sharedPref.edit(); // Get preference in editor mode
prefEditor.putString("your_edit_text_pref_key", "DEFAULT-VALUE"); // set your default value here (could be empty as well)
prefEditor.commit(); // finally save changes
// Now we have updated shared preference value, but in activity it still hold the old value
this.resetElementValue();
}
private void resetElementValue() {
// First get reference to edit-text view elements
EditTextPreference myPrefText = (EditTextPreference) super.findPreference("your_edit_text_pref_key");
// Now, manually update it's value to default/empty
myPrefText.setText("DEFAULT-VALUE"); // Now, if you click on the item, you'll see the value you've just set here
}
}

Categories

Resources