I have an app where the user can enter an amount into an EditText but then I want to be able to add or subtract this to/from a double then be able to display this double with a TextView within another activity.
I'm not sure how to go about this and would appreciate some help.
Thanks in advance!
Edit: I forgot to mention that I also want this data to be kept between app launches/closes.
In your activity that accepts the input from the EditText:
double value = Double.parseDouble(yourEditText.getText().toString());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (adding) {
value = prefs.getFloat("your.float.key", 0f) + value;
} else {
value = prefs.getFloat("your.float.key", 0f) - value;
}
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("your.float.key", value);
editor.apply();
In your activity that shows the value:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Double value = prefs.getFloat("your.float.key", 0f);
yourTextView.setText(value.toString());
Firstly you will need to parse the data from your EditText, you can get a String from an EditText using
EditText.getText().toString()
and then use some form of
Double.parseDouble(String)
Integer.parseInt(String)
to get a numeric value from the string, with which you can then use for whatever math you need. After you calculate this value you will want to send it to another Activity via intent
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("KEY", myDouble);
startActivity(i);
to receive the intent in your next activity use
Bundle extras = getIntent().getExtras();
if (extras != null) {
Double myDouble = extras.getDouble("KEY");
}
and then if you want to save the value you will want to look into SharedPreferences
to save
SharedPreferences prefs = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("KEY", myFloat);
editor.commit();
to get
SharedPreferences prefs = getSharedPreferences("KEY", Context.MODE_PRIVATE);
myFloat = prefs.getFloat("KEY", myFloat);
Related
I would like to display the name and user type after registration and login. For this app, after a person registers, one is taken back to the log in screen. If the login is successful, the homepage activity will open.
I'm trying to send the name and user type value from registration to homepage but sharePreferences kept on returning the null value.
(Registration)
//grab the user type to homepage
Spinner spinner = (Spinner)findViewById(R.id.user_type_spinner);
String userType = spinner.getSelectedItem().toString();
EditText name=(EditText) findViewById(R.id.name);
preferences = this.getSharedPreferences(PREFS_NAME,
Registration.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("NAME", name.getText().toString());
editor.putString("USER_TYPE", userType);
editor.commit();
(Homepage)
//Grab name and user type to show in homepage
preferences = this.getSharedPreferences(PREFS_NAME,
Registration.MODE_PRIVATE);
textUserType = (TextView) findViewById(R.id.textView3);
textName = (TextView) findViewById(R.id.textView1);
textWelcome = (TextView) findViewById(R.id.textView2);
//Get name and user type
String prefName=preferences.getString("NAME", "");
String prefUserName=preferences.getString("USER_TYPE", "");
//display the view
textName.setText("Hello " + prefName + "!");
textWelcome.setText("Welcome");
textUserType.setText("User type:" +prefUserName);
You can follow the answer given by Haj Ali, it works....But I think that keeping an user and his password inside the sharedpreferences XML file is a REALLY bad practice since anyone can steal the file and obtain the credentials.
-> If your passing parameters from one activity to another, add the parameters to your intent.
-> If you're passing parameters from an activity to a fragment, add the parameters to a bundle, and then add the bundle to the fragment.
Follow such a model:
Activity A:
//inputs
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
//SharedPreferences
SharedPreferences prefs = PreferenceManager.
getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("email",email);
editor.putString("password",password);
editor.commit();
Activity B:
SharedPreferences sharedPreferences = PreferenceManager.
getDefaultSharedPreferences(getApplicationContext());
email= sharedPreferences.getString("email", "");
password = sharedPreferences.getString("password", "");
In my MainActivity, I have written some code which I assume creates a file and saves a value in that file.
public static final String WHAT_I_WROTE = null;
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//creates new SharedPreference?
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
//writes to the preferences file called saved_text?
SharedPreferences.Editor writer = saver.edit();
writer.putString(WHAT_I_WROTE, message);
writer.commit();
}
In another activity, I want to be able to read the message and display it but when I try this, it cannot resolve the symbol "saver".
String text_for_display = saver.getString(WHAT_I_WROTE);
What is the mistake I have made here and how do I correct it to read the saved string?
Thanks.
In another activity you have to again initalize the Shared preference.
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
String text_for_display = saver.getString(WHAT_I_WROTE),"any_default_value";
WHAT_WROTE = "anyText"
Add this to the other activity you have:
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
then read it like this
String myValue = saver.getString("saved_text", "default_value");
Setting values in preference is like,
SharedPreferences.Editor editor = getSharedPreferences("saved_text", MODE_PRIVATE).edit();
editor.putString("WHAT_I_WROTE", message);
editor.commit();
Retrieve the data like,
SharedPreferences prefs = getSharedPreferences("saved_text", MODE_PRIVATE);
String text_for_display = prefs.getString("WHAT_I_WROTE", null);
Don't forget to put "context" before "getSharedPreferences" if necessary.
I'm newbie for Android Studio & Java, i'm PHP user.
Just want to know how to do like PHP session in Android Studio.
No matter which Activity i go to, i can easily get the session value example like the User ID. (session["USERID"])
now the method i using is putting extra everytime i call for another activity.
i'm sure there will be a better way to do this.
anyone have any good suggestion?
PS: I google around and it keep return me PHP session tutorial/example/etc but not for Android Studio....(may be i enter work #keyword or sentence)
Thank You Very Much
Thanks to fillobotto & Arshid KV
here is my code
first_main activity
sharedpreference = getSharedPreferences(BIZInfo, Context.MODE_PRIVATE);
sharedpreference.edit().putString(userid, "12345");
sharedpreference.edit().commit();
second_main activity
sharedpreference = PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = sharedpreference.getString("text", null);
if (restoredText != null) {
sp_name = sharedpreference.getString("userid", "No name defined");
}
Log.i("TAG", "onCreate: [" + sp_name + "]");
log show empty value/nothing...
what went wrong!?
You can use SharedPreferences as session in php
Demo code :-
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Arshid");
editor.putInt("Age", 22);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int Age = prefs.getInt("Age", 0); //0 is the default value.
}
You were really near to the solution. This is what I use:
public static String getSession(Activity context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString("session", null);
}
public static void setSession(Activity context, String session) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("session", session);
editor.apply();
}
I'm actually passing the Activityto get SharedPreferences, but in this way you will obtain an instance of the object which is not activity-related.
Hell I am trying to make highscore for my project but my code is only saving last value not highest value
How can I store only highest value? here is my code .
This is saving process ->
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
TextView outputView = (TextView)findViewById(R.id.textscore);
CharSequence textData = outputView.getText();
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
This is Reading process
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
String textData = prefs.getString(TEXT_DATA_KEY, "No Preferences!");
TextView outputView = (TextView) findViewById(R.id.textread);
You need to check the previously saved value to see which is highest else it you will just save the latest value, not the highest
E.g.
if (textData != null) {
int score = Integer.parseInt(textData.toString());
if(score > prefs.getInt(TEXT_DATA_KEY, 0)) // Or get String, with parse Int.
{
//editor.putString(TEXT_DATA_KEY, textData.toString()); // Should be saved as int
editor.putInt(TEXT_DATA_KEY, score);
editor.commit();
}
}
You need to store a new value only if the existing value in shared preferences is lesser than the new value.
You don't seem to be having this value check in your code
Replace
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
with
if (textData != null) {
if(Integer.parseInt(prefs.getString(TEXT_DATA_KEY, "0")) < Integer.parseInt(outputView.getText())) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
}
First of all why are you saving high scrore as string, use int or float (if you must).
The simplest way is to read high score before saving it and compare to the one you try to save.
You'll want to keep track of your in-game high score. That's easiest done using a number rather than using a text view's string:
int hiScore = 0;
In your startup, perhaps in onCreate(), you'll want to obtain the previous high score:
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
try {
hiScore = prefs.getInt(HI_SCORE, 0);
} catch (NumberFormatException e) {
hiScore = 0;
}
When a new score is obtained, you'll want to record it if it's higher than the previous high score:
if (newScore > hiScore) {
hiScore = newScore;
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HI_SCORE, hiScore);
editor.commit();
}
I want to save totalBalance in this activity to SharedPreferances and the retrive it in another class.
so i want totalbalance to be displayed in another activities in same application...
if possible also edit it in other activites...
please help... thanks
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
// Genrating random number Random number
Random rn = new Random();
randomNumber = (int) rn.nextInt(9) + 1;
// changes textView1 equals to random number
textView1.setText("Random Number is "
+ Integer.toString(randomNumber));
button1.setText("Play Again");
// Matching random number to ArrayList
if (positive_IDs.contains(randomNumber)) {
// if matched then changes textView2 to Matched Number
textView2.setText("Number: "
+ Integer.toString(randomNumber) + " Matched");
totalBalance = totalBalance + winingPrize;
textView5.setText("Total Balance = Rs: "
+ String.format("%.2f", totalBalance));
}
}
try this,
public void saveValue(String lock, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("Value", lock);
editor.commit();
}
public String getValue(Context context) {
SharedPreferences savedvalue = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedvalue.getString("Value", "");
}
Save Value as Following
int Value;
private void saveValues(){
SharedPreferences readSP = getSharedPreferences("String", MODE_PRIVATE);
SharedPreferences.Editor editor = readSP.edit();
editor.putString("String", Value);
editor.commit();
}
Retrive value in any of your Class As following
int value;
private void getSavedValue()
{
SharedPreferences settings = getSharedPreferences("String", MODE_PRIVATE);
value=settings.getString("String", "");
}
// try this
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("balance", String.format("%.2f", totalBalance));
editor.commit();
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
String total = sharedPreferences.getString("balance");
Use following code to retrive your value from SharedPreference,write this in other class where you want to retrive value of total balance
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
Editor edit1 = remembermepref.edit();
edit1.putInt("totalbalance_key",totalBalance);
edit1.commit();
and to store total balance into ShardPreference use in your activity:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
int totalbalance = pref.getInt("totalbalance_key");
Now use totalbalance way you want.
Most important thing is to check whether you have used same key to restore as well as tostore the value in SharedPreference
Hope this helps..