Continue from the last counter when reopen the android application - android

I am new in Android programing. I want to make an application. The button text increase whenever the user click on it. My counter is reseted when the application is closed. How can I store the last counter value and call it again when the application is reopened?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
}
EDIT:
I try to use this Shared Preferences but I got eror about "setSilent" and "mSilentMode". Help please
My new code
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
#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();
}
}

It depends, are you asking how to preserve a variable across an app's lifespan or between different lifespans?
If it's across different lifespans, you can write it to disk and then read it onCreate.
If you need to do it across one lifespan, it depends on your use case, but generally putting it in a global, static variable would do the trick!
If this is unclear and you'd like some sample code, please, don't be afraid to ask! : )

You can save your c value in the Preference when your activity is going to be closed, and when you rise up your activity you set your c variabile to the previous value

Use this snippet out of your onClickListener: To get the int if there is any
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
int ca = hhii.getInt("c_value2", 0);
button.setText(ca+"");
Use this in your onClickListener: To save the int as the user clicks the button-much better than saving it in onBackPressed or OnDestroy or whatever
c++;
button.setText(Integer.toString(c));
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
hhii.edit().putInt("c_value2",c).commit();
Regards from Iran,
Gabriel

Related

How do I create a button dynamically based on user input?

I am trying to make an app where the user types in text and presses enter and a button is dynamically placed on a different activity with its text set as what the user inputs. I am not sure how to do this, I was thinking of saving the user input in a sharedPreference but I am not sure where to go from there.
package com.example.opisa;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AddGoalsActivity extends AppCompatActivity {
// Create object of SharedPreferences.
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor= sharedPref.edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_goals);
}
public void addGoalText(View view) {
EditText name = (EditText) findViewById(R.id.editText1);
TextView mText = (TextView) findViewById(R.id.textView);
if (name.getText().toString().isEmpty()) {
mText.setText("Didnt type anything");
} else {
mText.setText(name.getText().toString());
}
}
//put your value
editor.putString("goals", name);
//commits your edits
editor.commit();
}
After the user types in what he wants,I would like the mText to be the value of text on a button that dynamically appears on a different activity.
In Your First Activity Write
public class AddGoalsActivity extends AppCompatActivity {
// Create object of SharedPreferences.
SharedPreferences setValue ;
//now get Editor
SharedPreferences.Editor valueEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_goals);
setValue = getSharedPreferences("key",Context.MODE_PRIVATE);
}
public void addGoalText() {
valueEditor = setValue.edit();
EditText name = (EditText) findViewById(R.id.editText1);
TextView mText = (TextView) findViewById(R.id.textView);
if (name.getText().toString().isEmpty()) {
mText.setText("Didnt type anything");
valueEditor.putString("key","Didn't type");
} else {
mText.setText(name.getText().toString());
valueEditor.putString("key", String.valueOf(name.getText()));
}
valueEditor.apply();
}
}
If you are calling addGoalText somewhere , if not use onchangelistener
In Your Second Activity in which you have button
public class SecondActivity extends AppCompatActivity {
SharedPreferences setValue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);// your layout
setValue = getSharedPreferences("key",Context.MODE_PRIVATE);
Button your_button =findViewById(R.id.buttonId);//write your own ID
String S = setValue.getString("key","defaultValue");
your_button.setText(S);
}
}

Sharedprefrences not saving?

When i try to save a variable to shared preferences then call it in an editext it is not being saved? I've been looking around for hours but i cannot find anything on it. I know that sharedPrefrences acts like a dictionary in a way but other than that i don't understand why this is not working :(
package com.example.gatorblocks;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class block1Settings extends WearableActivity{
private TextView mTextView;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block1_settings);
configureBackButton();
configureColor();
Button addTextButton = (Button) findViewById(R.id.Apply);
TextView simpleEditText = findViewById(R.id.simpleEditText);
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("classes1","1-1")); //set textbox to equal current class
final EditText vEditText = (EditText) findViewById(R.id.simpleEditText);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
addTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String enteredText = vEditText.getText().toString(); //sets the array value of block to the editText
test(enteredText);
}
});
}
private void configureColor() {
Button Block1 = (Button) findViewById(R.id.colorButton);
Block1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, colorBlock1.class));
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
private void configureBackButton(){
Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, classes.class));
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
finish();
}
});
}
public void test(String enteredText){
SharedPreferences pref = getSharedPreferences("classes.txt", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("class1", enteredText);
editor.apply();
}
}
How did you get data from SharedPreferences which is not saved? You saved data using key class1 and want to get it by classes1 which is not correct way. You have to use same key. Try using
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("class1","1-1"));

Android Using SharedPreferences to save and retrieve values - Counter

Hello I am new to android and actually i am developing a application whereby the user would be clicking on a button and the button should record the click event - the counter should be incremented at each time the button is clicked. The button would be displayed in one activity and once the user has clicked the button, another activity would be displayed whereby the results would be shown.
Actually i am having problems in assigning the sharedPreferences to the button and then displaying it into the next activity hence having the number of clicks.
The code i am using is as follows:
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
/** Declare the variables being used */
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_SCORE = "Score"; // Integer
int counter;
Button add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
Intent openClickActivity2 = new Intent("com.android.jay.Results");
startActivity(openClickActivity2);
}
});
}
}
Results.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Results extends MainActivity{
public void onCreate(Bundle savedInstanceState) {
SharedPreferences mGameSettings;
super.onCreate(savedInstanceState);
mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
if (mGameSettings.contains(GAME_PREFERENCES_SCORE)) {
DisplayResults.setText(mGameSettings.getString(GAME_PREFERENCES_SCORE, “counter”));
}
}
}
Any help to guide me would be much appreciated.Thank you
You will have to set GAME_PREFERENCES_SCORE in MainActivity. Do something like this after counter++:
getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE).edit().setInt(GAME_PREFERENCES_SCORE, counter). commit();
Simply make a Preferences class
public class Preferences {
String MASTER_NAME = "mysticmatrix_master";
SharedPreferences mysticMatrixPref;
Preferences(Context context) {
mysticMatrixPref = context.getSharedPreferences(MASTER_NAME, 0);
}
public void setAddCount(int count) {
SharedPreferences.Editor prefEditor = mysticMatrixPref.edit();
prefEditor.putInt("count", count);
prefEditor.commit();
}
public int getAddCount() {
return mysticMatrixPref.getInt("count", 0);
}
}
and in your MainActivity.java put this code
public class MainActivity extends Activity implements OnClickListener {
ImageButton add;
Preferences cpObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = new Preferences(getApplicationContext());
/*
* getting the count variable and adding 1 in that to check the condition of showing rate activity and adds
*/
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cpObj = new Preferences(getApplicationContext());
cpObj.setAddCount(cpObj.getAddCount() + 1);
}
});
}
}
And in your result activity just get the count's value
import android.content.Context;
public class Results extends MainActivity{
Preferences cpObj;
public void onCreate(Bundle savedInstanceState) {
preferences = new Preferences(getApplicationContext());
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
DisplayResults.setText(cpObj.getAddCount());
}
} }
By this you will get the default value of result as '0' and you can set that in your Preferences class
Use a method like this:
public static void SavePreference(Context context, String key, Integer value) {
SharedPreferences.Editor editor = PreferenceManager
.getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE)
.edit();
editor.putInt(key, value);
editor.commit();
}
and in you onclick after counter++ add this:
SavePereference(context, "GAME_PREFERENCES_SCORE", counter);

Values in sharedpreferences are not cleared

I am developing an app in which I need to manage users session i.e when user logs in for the first time he must see the login page and once he is authenticated he is redirected to the home screen and tht time a value is set in sharedpreferences. Now on the home screen when the user clicks on logout button the values in shsredpreferences must be cleared and the next time the user opens the app he must be directed to login page.Unless and until user clicks logout he must not be shown the login page.
I am able to store values in sharedpreferences but not able to delete them.
here is my code for loginpage.java
package com.sess.eg;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class loginpage extends Activity {
/** Called when the activity is first created. */
EditText acc,user,pin;
Button login;
StringBuilder builder = new StringBuilder();
String UserName;
SharedPreferences.Editor prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
// UserName= prefs1.getString("User", "Abcdef");
//
// System.out.println(UserName);
//
// if(UserName.equals("Ad"))
//
// {
// System.out.println(UserName);
// Intent i=new Intent(loginpage.this,homepage.class);
// startActivity(i);
// }
setContentView(R.layout.main);
acc = (EditText) findViewById(R.id.ed_login_acc);
user = (EditText) findViewById(R.id.ed_user_acc);
pin = (EditText) findViewById(R.id.ed_pin_acc);
login = (Button) findViewById(R.id.login_button);
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
login.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
prefs.putString("User", "Ad");
prefs.commit();
//System.out.println(sendJson1());
//startService(new Intent(Login.this, MyService.class));
Intent i = new Intent(loginpage.this, homepage.class);
startActivity(i);
finish();
//System.out.println(UserName);
}
});
}
#Override
protected void onStart() {
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
UserName= prefs1.getString("User", "Abcdef");
System.out.println(UserName);
if(UserName.equals("Ad"))
{
System.out.println(UserName);
Intent i=new Intent(loginpage.this,homepage.class);
startActivity(i);
finish();
}
super.onStart();
}
}
here is my code for homepage.java
package com.sess.eg;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class homepage extends Activity{
Button logout;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home3);
logout = (Button) findViewById(R.id.logout);
logout.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
SharedPreferences.Editor prefs = getPreferences(MODE_WORLD_WRITEABLE).edit();
prefs.clear();
// prefs.commit();
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
String UserName= prefs1.getString("User", "Abcdef");
System.out.println(UserName);
finish();
}
});
}
}
In your code:
//prefs.commit();
Change this. Remove it from the comments.
prefs.commit();
commit() is called to save your preferences changes.
"Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.
Note that when two editors are modifying preferences at the same time, the last one to call commit wins. "
Read here.
You have commented out the calls to prefs.commit(). Uncomment them.

Cannot access SharedPreferences in constructor

I use SharedPreferences for storing data. When I try to call the data-storing function from the constructor of my class, it shows a Runtime error. However, when I call the function from onCreate() it works fine.
Is there any way I can call my data-storing function from the constructor?
package com.examples.storedata;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Activity1 extends Activity
{
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
editText1 = (EditText)findViewById(R.id.edittext1);
editText2 = (EditText)findViewById(R.id.edittext2);
buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);
}
public Activity1()
{
LoadPreferences(); //show error while calling from here
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
SavePreferences("MEM1", editText1.getText().toString());
LoadPreferences();
}
};
Button.OnClickListener buttonSaveMem2OnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
SavePreferences("MEM2", editText2.getText().toString());
LoadPreferences();
}
};
private void SavePreferences(String key, String value)
{
SharedPreferences sharedPreferences = getPreferences(MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.putInt("1",5);
editor.commit();
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}
You are attempting to access your text views before you have initialised the view or the variables:
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
When you call LoadPreferences from the Activity constructor, onCreate hasn't yet been called, which means textSavedMem1 and textSavedMem2 have not been initialised and are null.
When you call it from onCreate, so long as it is after the following, then these variable are initialised and everything works as expected.
setContentView(R.layout.main);
textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
This is normal. By the time your activity is created e.g when the constructor is called SharePreferences object is not yet accessible. It's not good practice to use/override activity's constructor. Read about activity lifecycle to get the idea how to use activity.
Its not possible since u can get SharedPreference in activity which has already been created.. here u r trying to get SharedPreference even before activity is under construction (Constructor).. for getting shared preference u need activity..
U can store the values in some Instance variables inside constructor then put them in SharedPreference...

Categories

Resources