Android: SharedPreferences Boolean - java

does someone know where the mistake is? There is an error in Android Studio.
The following is the code for now.
final String keyFirstTime = "keyFirstTime";
prefsEditor.putBoolean(keyFirstTime, false);
if (keyFirstTime = false) {
Thanks in advance.

keyFirstTime is a string (see comment)
you are PUTTING a value not getting a value
You are using an assignment in an if statement
You are comparing a STRING to a BOOLEAN
In Activity 1 you should have:
final String keyFirstTime = "keyFirstTime";
prefsEditor.putBoolean(keyFirstTime, false);
In Activity 2 you should have:
boolean firstTime = prefs.getBoolean(keyFirstTime, false); //you don't need the editor
if (firstTime) {
...
}
Please go here for a tutorial: https://developer.android.com/training/basics/data-storage/shared-preferences.html
EDIT Try doing this (stolen from here)
private static final String FIRST_RUN = "FIRST_RUN";
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
prefs = getSharedPreferences(getApplicationContext().getPackageName(), MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean(FIRST_RUN, true)) {
prefs.edit().putBoolean(FIRST_RUN, false).commit();
//call relevant function for first run
} else {
//call relevant function for every other run
}
}

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); prefs.edit().putBoolean("keyFirstTime", true).commit();
Now to get Boolean value you have to use
Boolean check = prefs.getBoolean("keyFirstTime", false);
Now you can check this way
if(check){ your code here }

Related

save calculator result and show them as a list using SharedPreferences

i have successfully implemented a calculator with a history activity in which it will show old results in a list view
but i am facing a problem that the first line is always null
https://imgur.com/a/jvXms
i tried to make default string " Old Calculation "
> String w = "Old Calculation";
but this didn't work,
my app save the result in a multiline String in SharedPreferences and pass it to another activity through an intent
>SharedPreferences.Editor editor ; // saving shared preferences editor as MainAcitivty class attribute
under the onCreate i set the String value to sharedpref
> SharedPreferences prefs = getPreferences(MODE_PRIVATE);
w = prefs.getString("saved", null);
update method in which i update the result string value with the String s( String s is the calculated result)
> public void update(String s){
editor= getPreferences(MODE_PRIVATE).edit();
w = w
+ System.getProperty ("line.separator")
+ s
+ System.getProperty ("line.separator");
editor.putString("saved", w);
editor.apply();
}
Passing W value to the activity in which i will show the result in TextView list
> public void History(View v){
Intent myIntent = new Intent(MainActivity.this, History.class);
myIntent.putExtra("message", w);
startActivity(myIntent);
overridePendingTransition(R.anim.anim_slide_in_left,
R.anim.anim_slide_out_left);
}
History activity
public class History extends AppCompatActivity {
TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
String w ="Old calculation is showed here";
tv1 = (TextView) findViewById(R.id.tv1);
print(w);
}
public void print(String w) {
Bundle bundle = getIntent().getExtras();
w = bundle.getString("message");
tv1.setMovementMethod(new ScrollingMovementMethod());
tv1.setText(w);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
}
public void deleteAppData(View v) {
try {
// clearing app data
String packageName = getApplicationContext().getPackageName();
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
when you store data from activity A and you want retrieve it from another activity, You must use SharedPreferences as below:
SharedPreferences prefs = getSharedPreferences(String, int);
String is FileName like "result"
int is Mode like MODE_PRIVATE
for example see this link
in addition i wrote a simple code for help you

Shared preferences? (Extremely simple issue!?)

I am just trying to store the users input from an editText in a Shared Preference, but it is not working:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
}
return true;
});
When I first edit the text, I will first get a log of "mDefault" which is normal, since nothing is stored in the shared preference.
Then, I store something in the shared preference, and to make sure it stored, I log and I get a log of what I typed. Which means the shared preference data WAS stored.
Heres the problem: After I have stored something in the shared preference, I go to a different activity, and I come back, and all the data stored in the shared preference is GONE!
The very first log still says mDefault after navigating through activities.
What could the problem be?
EDIT:
Here is my instantiation:
onCreate:
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
Maybe you don't save on setOnEditorActionListener. Save when you go to a different activity. Because when it goes to different activity the setOnEditorActionListener editText.getText().toString() it returns null.
STORING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("username", "Rishabh");
edit.putString("password", "rishabh123");
// Commit the changes
edit.commit();
RETRIEVING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
String password= pref.getString("password", "");
Log.d(TAG, username);
Log.d(TAG, password);
Adding this as an example in case you missed a key components. This is currently working for me:
public class Main2Activity extends ActionBarActivity {
private SharedPreferences keyword;
private SharedPreferences.Editor keywordEditor;
private String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
final EditText editText = (EditText) findViewById(R.id.et_text);
findViewById(R.id.btn_launch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, Main22Activity.class);
startActivity(intent);
}
});
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, "Initial: " + keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, "Saving in prefs: " + keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
return true;
}
});
}
}
From a fresh install:
I typed in "test" and hit the send button on keyboard therefore invoked the onEditorAction
Then clicked on launch new activity -> hit back button and typed in "test2" and hit send button.
The following is the log out put:
02-29 23:26:42.068 18105-18105/com.example.naveed.myapplication V/TAG: Initial: mDefault
02-29 23:26:42.136 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test
02-29 23:26:53.281 18105-18105/com.example.naveed.myapplication V/TAG: Initial: test
02-29 23:26:53.338 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test2
As you can see initially it was "mDefault" then "test" was saved. I launched a new activity and came back. Next time the initial was "test" since it was saved last time and "test2" was the new value saved.
Create SharedPreferences class
public class SharedPreferenceClass
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "INTELLIJ_AMIYO";
public static final String KEY_SET_VALUE= "KEY_SET_VALUE";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setUserDATA(String data)
{
editor.remove(KEY_SET_VALUE);
editor.putString(KEY_SET_VALUE, data);
editor.commit();
}
public String getUserDATA()
{
String getData= pref.getString(KEY_SET_VALUE, null);
return getData;
}
}
Now call this in your Activity section globally
SharedPreferenceClass sharedPrefClassObj;
& call onCreate(Bundle savedInstanceState) section
sharedPrefClassObj = new SharedPreferenceClass(getApplicationContext());
Now add this
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
sharedPrefClassObj.setUserDATA(editText.getText().toString()); // Set data
// Get data sharedPrefClassObj.getUserDATA();
}
}
return true;
});
Very important: you need a Preference name (for example: "MY_PREFS_NAME") to set and retrieve the values:
SharedPreferences.Editor keywordEditor = context.getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
Use the same constant Preference name and it will give you the same preferences in any point of your app.

Load strings from sharedpreferences in EditText (two classes)

I have two different activity's. First one only showed to the user first time - to store phonenumber inside sharedprefs. I think the problem is my load from prefs method but just in case I will leave everything here to make it more relevant to future users. It looks like in both activitys the "mobilnummer" is saved - but I am having problem to display them.
The idea is it to be overwritten if user updates it - I think the method will do that?
OnStartUp.java
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
final Button button = (Button) findViewById(R.id.ntonboarding);}
public void SaveToMobile(View v) {
if (mobilnummer.getText().toString().length() >= 8) {
FragmentedUser.SaveMobile(mobilnummer.getText().toString()); // just saves to Parse.com (This works)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
}
}
Profile
EditText mobilnummer;
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
This is the issue/problem i think! (Code below)
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
String tempMobilnummer = mobilnummer.getText().toString();
mobilnummer.setText(tempMobilnummer);
// IF user wants to change mobilenumber
mobilnummer.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
if (mobilnummer.getText().toString().length() >= 8)
FragmentedUser.SaveMobile(mobilnummer.getText().toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
tlfstatus.setImageResource(R.drawable.ok);
handled = true;
}
return handled;
}
});
I think here is your error:
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
//here it should be MobileNumberSaved instead of mobilnummer, because tehre is no sense to set the same text to the textView again after you got it from there
String tempMobilnummer = MobileNumberSaved.getText().toString();
mobilnummer.setText(tempMobilnummer);
But the correct way to get a value from shared preferences is something like this:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String savedMobileNumber = prefs.getString("mobilnummer", "");
mobilnummer.setText(savedMobileNumber);
Update: when you save the value in the shared preferences, you save only the editText, not it's value, so do something like this when saving:
SharedPreferences.Editor editor = settings.edit();
//mobilnumber is your EditText, so get it's text like this
editor.putString("mobilnummer", mobilnummer.getText().toString());
editor.commit();
And everything else is still the same that I wrote above

Store Value in SharedPreference across Activities

I am new in Android, and got a task to develop a small project to submit in my college, i have tried my best but now i need some help
Let me tell you first, what i am trying to do ?
I have two Activities, MainActivity and AccountActivity
In MainActivity i am using button to switch to AccountActivity
In AccountActivity i am trying to store strBalance value in SharedPreference but whenever i do click on back button and then again come to AccountActivity always getting "1000" not that value which i have stored in SharedPreference.
Here is the complete code of AccountActivity.java:-
public class AccountActivity extends Activity {
EditText editAmount;
int strAmount;
Button btnPayment;
TextView textBalance;
int strBalance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
editAmount = (EditText) findViewById(R.id.editAmt);
btnPayment = (Button) findViewById(R.id.btnPay);
textBalance = (TextView) findViewById(R.id.textBalance);
strBalance = 1000;
textBalance.setText("Your current balance is: $ "+strBalance);
btnPayment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
strAmount = Integer.parseInt(editAmount.getText().toString().trim()); // user input
if(strAmount>strBalance) {
Toast.makeText(AccountActivity.this, "You don't have enough balance", Toast.LENGTH_SHORT).show();
}
else
{
strBalance = strBalance - strAmount; // 1000 - 500 = 500
textBalance.setText("Your current balance is: $ "+strBalance);
Log.v("strBalance", String.valueOf(strBalance)); // 500
editor.putInt("key_balance", strBalance);
editor.commit();
}
}
});
}
}
Do this,
SharedPreferences sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
int any_variable = sharedPreferences.getInt("key_balance", 0);
Remove initialisation and do this in your onCreate and then use the new variable as you strBalance.
-Check Both the preference and key name are same or not.
You did not retrieve data from SharedPreferences
Write your code in onResume() like this:
#Override
protected void onResume() {
super.onResume();
// SharedPreferences retrieval code
}
To know more about SharedPreferences check this link.
This should work fine:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
if (pref.getInt("key_balance", 1000) != null) {
strBalance = pref.getInt("key_balance",1000);
} else {
strBalance = 1000;
}
Instead of
strBalance = 1000;

Android - Change class variable before onCreate

I am new to Android development. I am trying to call a method of one of my classes when a button on my main activity is pressed.
On my Main Activity I have this button:
public void buttonTest(){
Button b = (Button) findViewById(R.id.test);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String s = "changeText:myText";
Intent in = new Intent(PlusActivity.this, Test.class);
in.putExtra("method",s);
startActivity(in);
}
});
}
And here is is the class (without imports) which that intent above is calling to.
public class Test extends Activity {
static String text = "test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
TextView mTextView = (TextView) findViewById(R.id.textView);
mTextView.setText(text);
}
public void changeText(String s){
this.text = s;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String[] array = intent.getStringExtra("method").split(":");
if(array[0].equals("changeText")){
changeText(array[1]);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
Basically I want to know if it is possible to change the value of that String text, before onCreate(). Basically each button will have a correspondent text, and I want to be able to modify that text based on which button.
If it is, what should I do/change?
Thanks in advance.
The right way to do it is to send the string you want it to be as an extra in the intent, and to read the extra from the intent and assign it to that variable in the onCreate function.
Use SharedPreference. Save in OnCLick of first class and retrieve in OnCreate of second class.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes
String text;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
text= null;
} else {
text= extras.getString("your default string message");
}
} else {
String s = "your default string message";
text= (String) savedInstanceState.getSerializable(s);
}

Categories

Resources