Save state of Button in activity Android - java

I have two buttons(button1, button2) in my activty. botton1 is 'Enabled'(true) , while the other one isn't.
When I click on button1, button2 becomes 'Enabled'. I want to record this activity in this state for the next utilization of my application.

You can save state in sharedPrefrences, try this
SharedPreferences prefs = getSharedPreferences("Your preference name here", MODE_PRIVATE)
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
b2.setEnabled(true);
prefs.edit().putBoolean("b2enabled", true).commit();//saving State here
}
});
And now where you want to use this state simple get the state as.
Boolean b2state= prefs.getBoolean("b2enabled", false); //false is the default value
And if you want to enable or disable button on result do
if (b2state){
b2.enabled(true);
}
else{
b2.enabled(false);
}

Well, you can use the help of a data storage option. For a simple task like this,
shared preference is enough.
use something like this to store the state change.
function setState(boolean state){
SharedPreferences sharedPref =this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("state",state);
}
you can retrieve the data at anytime (usually in in the beginning) like this. Note that the second argument serves the default value.
int state=this.getPreferences(Context.MODE_PRIVATE).getBoolean("state",false);
Hope this helps.

Related

android app to - generate sqeuential number and save it

I want to make a simple android app to - generate sequential number every time a button is pressed and save it as it is when it is closed. So when I open it next time it starts from there.
In JAVA I got sequential number part figured. But don't know how to save that number upon closing the app.
Just a simple hint could help me find out the rest.
This is my first question here so ignore if you find it too childish.
Thanks!!
There are many ways to do it:
Using saveInstanceState() and onRestoreInstanceState() these are the two android activity life cycle methods to store data at the time of closing your app.
You can use SharedPreferences to save your data. It basically uses a small XML file for storing your data permanently.
You can also use SQLite database for storing data. [But for this purpose it is not preferable.]
Hope it will meet your question.
Use SharedPreference like -
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get your last saved sequential number
num = getMyNumber();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
++num;
saveMyNumber(num);
}
});
......
}
private void saveMyNumber(int num) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("sequencialnum", num);
editor.commit();
}
private int getMyNumber(){
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
return sharedPref.getInt("sequencialnum", 0);
}

Check activation code on first app run

I created an android app that when it runs for the first time an activation page loads with these codes .
Button btnInput = (Button) findViewById(R.id.send);
btnInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText m = (EditText) findViewById(R.id.editText);
String strInput = m.getText().toString();
if (strInput.equals("123") || strInput.equals("456"))
startActivity(new Intent(ActiveCode.this, MainActivity.class));
else
startActivity(new Intent(ActiveCode.this,ActiveCode.class));
finish();
}
});
}
And Main activity code like this :
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
startActivity(new Intent(MainActivity.this,ActiveCode.class));
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit();// Very important to save the preference
}
}
the problem is that when on first run user closes the app completely without entering code and open it again they don't need to enter code and it goes directly to main activity , so basically it's a bug of my app .
I want help to change codes in a way that activation page disappear only when user enters code.
Try to initialize preference like this,
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
instead of,
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Because your preference is not binding with your activity.

check if activity is the first since launch

I want my main activity to show a popup the on launch, this activity is the first activity that is created, but multiple instances of this activity could be created and I only want the first since launch to display this popup, so I would like to know if there how I can check this.
The most simplest way of doing it is use a static variable
How do you use it:
Define a static boolean flag and assign it false value, once the activity is created for the first time, make the flag true, and now you do your task with simple if/else condition
public static boolean flag=false;
then in onCreate
if(flag==true)
{
//Activity is not calling for first time now
}
if(flag==false)
{
//first time calling activity
flag=true;
}
Store flag in SharedPreferences which indicate is application is launched first time or not. Use Activity Oncreate method as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and check SharedPreferences if fist time launch
SharedPreferences settings = getSharedPreferences("showpopup", 0);
SharedPreferences.Editor editor = settings.edit();
if(settings.contains("firsttime")){
// means activity not launched first time
}else{
// means activity launched first time
//store value in SharedPreferences as true
editor.putBoolean("firsttime", true);
editor.commit();
//show popup
}
}
I would use selvins approach. Unless you have a backend to your application setup and user registration, there will be no way for you to get this type of information for a specific application instance unless you use SharedPreferences
int activityLaunchCount = 0;
SharedPreferences preferences = getBaseContext().getSharedPreferences("MyPreferences", SharedPreferences.MODE_PRIVATE);
activityLaunchCount = preferences.getInt("ActivityLaunchCount", 0);
if(activityLaunchCount < 1)
{
// ** This is where you would launch you popup **
// ......
// Then you will want to do this:
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Then I would Increment this counter by 1, so if will never popup again.
activityLaunchCount += 1;
// Store the New Value
editor.putInt("ActivityLaunchCount", activityLaunchCount);
// You Must call this to make the changes
editor.commit();
}else{
// If you application is run one time, this will continue to execute each subsequent time.
// TODO: Normal Behavior without showing a popup of some sort before proceeding.
}
Then when you want to Close the application
Override the Activity finish() method
#Override public void finish()
{
super.finish();
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Store the New Value
editor.putInt("ActivityLaunchCount", 0);
// You Must call this to make the changes
editor.commit();
}

boolean won't stay on the right input when i kill my app or reboot the device

im building a app, found a java part that lets me show an activity only at first start.
this works but when i kill the app or reboot my phone it goes back, can anyone help me out with this?
im using this in my main activity (Toolz.java)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Prefs.firststart == false) {
setContentView(R.layout.toolz);
} else {
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
and i added this to First.java
Prefs.firststart=false;
and i made the Prefs.java and added this
public class Prefs {
public static boolean firststart = true;
}
you will need to use SharedPreferences instead o static variable for saving data which also available when app killed or device reboot.
you can see following tutorial how we use SharedPreferences for saving and reading data from SharedPreferences
Shared Preferences
When the app restarts all your code will start from the starting point (i.e Prefs.firststart will be set to true). Instead, you need to make a persistent variable that is saved throughout sessions. If you're using a DB you could use that, or you could use the built-in SharedPreferences, as such:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = this.getPreferences(MODE_PRIVATE);
if (prefs.contains("started")) {
setContentView(R.layout.toolz);
} else {
//Add the preference:
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("started",true);
editor.apply();
Intent i = new Intent(this, First.class);
startActivity(i);
finish();
}
}
When you kill your app, the values are going to reset to their initial values. Your boolean will be equal to true. I suggest saving the state of the variable using SharedPreferences. Check out this other question someone asked about saving.
How to save a state of a variable in android app and use it
Try it like this
//**** First start *****
//you get the prefs for your app using a pref name
String PREFS_NAME = "myAppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//persist the boolean value in preferences using a key-value approach
editor.putBoolean("pref_app_started", true);
//commit the changes
editor.commit();
and when you start the app you check for that pref
//**** next start *****
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//now we get the saved boolean using the key we previously uesd when setting it
//the second parameter is the default value for the flag in case it was never set
boolean wasAppStarted = settings.getBoolean("pref_app_started", false);
//now you can use your wasAppStarted flag to decide what you do further

Adding dynamic checkbox preferences in Android, and display them in preference screen?

I want to implement functionality where user will be able to select which group of items to be displayed using checkbox shared preferences. To be precise I will read checked items from the preferences and display.
Here is my preferences class
public class Preferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//One way to add default preferences
//addPreferencesFromResource(R.xml.prefs);
//For now I prefer this
setPreferenceScreen(defaultPref());
}
// The first time application is launched this should be read
private PreferenceScreen defaultPref() {
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setKey("1");
checkboxPref.setTitle("SomeRandomStuff");
root.addPreference(checkboxPref);
return root;
}
public showAllPreferences () {
// TO SHOW ALL THE PREFERENCES BUT NOT SURE HOW TO DISPLAY THEM
}
}
Now I cannot understand how do I add more preferences dynamically and display them in preference screen.
Here is the main activity class
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
}catch (Exception e) {
e.printStackTrace();
}
exView = (ExpandableListView) findViewById(R.id.expandableListView1);
// STUFF TO ADD IN PREFERENCES
editText = (EditText) findViewById(R.id.editText1);
//BUTTON TO ADD PREFERENCES.(SEARCH TERM IS IDENTIFIED AND ADDED TO PREF)
addButton = (ImageButton) findViewById(R.id.imageButton1);
// BUTTON TO DISPLAY PREFERENCES
prefButton = (ImageButton) findViewById(R.id.imageButtonPref);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = settings.edit();
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
PrefObject obj = new PrefObject();
String key = Integer.toString(i);
String title = editText.getText().toString();
//prefArray.add(obj);
editor.putString(key, title);
editor.commit();
i++
}
});
prefButton.setOnClickListener(new OnClickListener() {
// This method should show the preferences activity with new data
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Main.this, Preferences.class);
startActivity(intent);
// I know how to call the intent but I am not sure if
// how to read the saved contents and display it
Preferences pref = new Preferences();
pref.showAllPreferences();
}
});
AFAIK, there is no "visibility" option for preferences, which kinda makes sense when you think it's all just a ListView.
See [1]. For what I see, you could do something like this:
PreferenceScreen screen = this.getPreferenceScreen();
// Use "1" since you're using "1" to create it.
CheckBoxPreference ckbox = (CheckBoxPreference) this.findPreference("1");
screen.removePreference(ckbox);
To recreate, you could do this [2]:
screen.addPreference(ckbox);
Additionally, remember to create your preference using the setOrder(int order) so that when you recreate, it will be recreated in the proper position.
As you can see, it could be worth to keep a global reference to the preference to make it easier and faster.
Of course, I don't need to tell that you should integrate that logic into your CheckboxPreference listener. See this answer by nobody else than Reto Meier himself to see a good way of doing it (it's a checkbox, too). There he registers a listener to the whole screen and checks which preference triggered the listener, but you can do it simpler (but more verbose later on) by just setting its setOnPreferenceChangeListener.
*edit: I see that you're also using a button to add the preference. You can also implement the same logic above into the button itself. It all depends if you want to do this using a checkbox or a button.
Finally, it could be worth to just set the enabled state, unless you are doing something like "see advanced preferences" or something worth to keep novice users away from doing dangerous stuff to your app. But generally the enable states work better for user experience, IMHO.
I hope this answers your question.

Categories

Resources