How to save a result in android? - 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
}

Related

How to retain the task of the activity even when closing the app Android

I have a switch button in my android app I intend to switch it on but after I exit the app by removing it on my background task when I opened again the app it goes back to normal and switch goes back to off again. i=I want to retain or save the activity which I have been left. How am I going to retain the task of my activity basically the fragment itself? Am I going to use On pause?
#Override
public void onPause() {
super.onPause();
}
You can accomplish this using shared preferences. For example, in onCreate, load the switch state from shared preferences (with a default for the first time)
SharedPreferences prefs = getSharedPreferences("MyUniquePrefsName", Context.MODE_PRIVATE);
switchState = prefs.getBoolean("MyBoolean", false); // switchState being a boolean class member
// then set the switch to switchState
When the user updates the switch, change the stored value of switchState and in onPause save the updated state to the shared preferences
#Override
public void onPause() {
super.onPause();
SharedPreferences.Editor ed = getSharedPreferences("MyUniquePrefsName", Context.MODE_PRIVATE).edit();
ed.putBoolean("MyBoolean", switchState);
ed.apply();
}

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.

disable buttons permanently throughout the aplication in android

Actually i have 3 buttons.User should click on any one button then all the 3 buttons should disable permanently throughout the app(when we close and open the app, buttons should be in disable state).How can i achieve this?
Thanks in advance.
define the behavior in SharePreferences:
for example use this in onResume:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
boolean enabled = pref.getBoolean("isEnabled",true);
myButton.setEnabled(enabled);
in onClick event of the button do this:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
pref.edit().putBoolean("isEnabled",false).commit();
myButton.setEnabled(false);
Use shared preference to store the clicked state of button.And check the preference value each time in activity/ fragment and disable or enable as per preference value.
you need to save your button state in sharedpreferences and based on your condition you need to enable / disable it in your activity code.
if(stateofbuttonfromprefs) {
button.setEnabled(false);
} else {
button.setEnabled(true);
}
You can use SharedPreference for your purpose. For more information refer this
declare SharedPreference before onCreate method
SharedPreferences stateButton;
SharedPreferences.Editor bEditor;
initialize this on onCreate()
stateButton= getApplicationContext().getSharedPreferences("Button_State", 0);
bEditor = stateButton.edit();
add these two methods on your activity
public void setBState(boolean e) {
bEditor.putBoolean("btn_state", e);
bEditor.commit();
}
public boolean getButState(){
return stateButton.getBoolean("btn_state", true);
}
call this to know your button state call
but.setEnabled(getBState());
when you need to disable the button, use
setBState(false);
On Button click
button_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
prefs.edit().putBoolean("btn_click", true).commit();
}
});
In Activity OnCreate method
Boolean btnClick= prefs.getBoolean("btn_click", false);
if(btnClick){
//Disable Button
}else{
//Enable Button
}

Call an activity only once in the app and show it again when the app restart after being killed

I'm developing an application in which I have to show an activity only once in the app lifecycle.
What I'm doing is on my MainActivity.java I'm calling an Activity 1, so after when I move in my app and whenever I come back to MainActivity.java my Activity 1 is called. I just want to show it once.
And again Activity 1 should be displayed when user kills the app and restarts it.
Here is what I'm doing in my MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startActivity(new Intent(MainActivity.this,
Activity1.class));
}
I have tried using the following code but it only run once, when the app is installed for the first time.
private boolean isFirstTime() {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
How can I modify the above code, so that my requirement is satisfied.
Any kind of help will be appreciated.
You should set ranBefore to false in onDestroy
#Override
public void onDestroy()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", false);
editor.commit();
}
Change
return !ranBefore
to
return ranBefore
It looks to me that you are always returning the same thing instead of the variable you initialize. Also, you could put the code to start the Activity directly in that method. Then you don't have to even worry about a return statement. It will just never run it again after you change the value in SharedPreferences
Edit
you can set your SharedPreferences value to false in onCreate(). This will work if you don't finish your Activity when you go to another and if its your main Activity then you probably don't ever want to finish it until you exit the app
I have solved this problem using SharedPreferences. What I have done is on Splash I entered some values in SP, and on the MainActivity I checked that, if the value matches show the activity, otherwise don't open the dialog. And on keyCodeBack(), I have cleared SP, this helps me in meeting my requirement.
Use shared preferences..
and to kill the activity, use class.finish() at your onClick()..

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.

Categories

Resources