Want to clear EditText content before activity goes in background - android

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.

Related

Android activity refreshes flow

I have an activity A, it has a button to open B, which inserts a record. A can then refresh the view inside onActivityResult. This is a normal flow.
However, B can accept share intent to insert a record also. How can A know when this action is done from B to refresh the view just like the normal flow? (of course, I assume act A already running on background task)
I can, of course, detect the change using onResume inside A, but i wish to know if it is a proper method.
thank you
You can use onResume to refresh the view for activity A. Because other method would be using broadcastReceiver and broadcastIntent and that would create unnecessary load.
You can use sharedPreference to store if data has been changed in Activity B and then in onResume of Activity A fetch that shared Preference and refresh the view
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean isChanged = sharedPreferences.getBoolean("isChanged",false);
if(isChanged){
//refresh your views
//clear the shared prefernce
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("isChanged",false);
editor.apply();
}
}
Remember you have set that shared preference in ActivityB while loading data
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("isChanged",true);
editor.apply();

How to save a result in android?

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
}

AlertDialog restarted each time I return to MainActivity

I created a MainActivity in which the user has a few app options, displayed in a grid menu, which access subsequent specific activities. However, when the application starts, I use an AlertDialog for the user to enter login details, inflated just after the grid layout definition.
The problem is, each time I select an item in the grid menu (and, consequently, a new activity), the AlertDialog pops-up again. How can I avoid this?
Moreover, I have an uploading service which should start with the beginning of the MainActivity (or after the login, perhaps), but should not be restarted each time a new activity is called. I assume this problem is related to the previous one, although I have managed to temporarily solve it by using a startService button via an OptionsMenu. This is no permanent solution.
Thank you in advance.
EDIT: I tried to use getSharedPreferences as follows:
private SharedPreferences prefs;
private String prefName = "MyPref";
int hasLoggedIn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mm_gridmenu);
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
hasLoggedIn = prefs.getInt("hasLoggedIn", 0);
if (hasLoggedIn == 0) {
showDialog(SHOW_DIALOG);
prefs = getSharedPreferences(prefName , MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("hasLoggedIn", 1);
editor.commit();
}
However, this way the hasLoggedIn value is saved as 1 and the dialog never pops-up again. I tried setting the back button to fix that, but this seems to prevent the app from being minimized. Is there a way to add that action to the button? (Which I would duplicate on the Home button as well)
#Override
public void onBackPressed() {
prefs = getSharedPreferences(prefName , MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("hasLoggedIn", 0);
editor.commit();
Log.i("hasLoggedIn", hasLoggedIn + "");
return;
}
Moreover, I believe this action will affect subsequent activities (setting the alertDialog back on). Which should be a valid alternative to this?
Basically you need to keep track of your applications states, you have a few options to do this. One simple way would be to use a SharedPreferences to store a boolean variable called something like hasLoggedIn after the user logs in you set this value to true. Each time your main activity launches simply check the value of hasLoggedIn if its is set to false require the user log in again. If it is already true don't show the log in dialog
You can try this:
Add a boolean flag in your MainActivity:
private boolean dialogFlag = true;
in the onCreate/onResume method:
if(dialogFlag) {
createDialog();
dialogFlag = false;
}
If you want to pop up just once the app is installed, you can save this flag into a property file. And read it first whenever the app is getting started.

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

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...

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