I insert the values in sharedpreferences, now I do not know how to display these values in a TextView.
SharedPreferences prefs = getSharedPreferences(SharedPrefName, 0);
SharedPreferences.Editor prefsEditor = prefs.edit();
float importo = prefs.getFloat( "Importo", 0 );
float valore = Float.parseFloat( mImporto.getText().toString() );
prefsEditor.putFloat( "Importo", importo + valore );
prefsEditor.commit();
First thing lets try to save something in SharedPreferences, I'm using a method because is easy to understand this way, and it looks cool :P
TO ADD in class:
private SharedPreferences settings;
private static final String PREFS_NAME = "app_name";
private TextView usernameTextView;
private TextView passwordTextView;
init textviews...
usernameTextView = (TextView)...
passwordTextView= (TextView)...
in constructor add this:
settings = context.getSharedPreferences(
PREFS_NAME, 0);
--Save username and password
public static final String USERNAME = "username";
public static final String PASSWORD= "password";
private void savePreferences(String sharedUsername, String sharedPassword) {
SharedPreferences.Editor SharedEditor = settings.edit();
SharedEditor.putString(USERNAME,
sharedUsername);
SharedEditor.putString(PASSWORD,
sharedPassword);
SharedEditor.commit();
}
--Load and display username and password in a textview
private void loadSharedPreferences() {
if (settings != null) {
String loadUsername= settings.getString(
USERNAME , null);
if (loadUsername != null && !loadUsername.isEmpty()) {
usernameTextView.setText(loadUsername);
}
String loadPassword= settings.getString(
PASSWORD, null);
if (loadPassword!= null && !loadPassword.isEmpty()) {
passwordTextView.setText(loadPassword);
}
}
}
Hope you use it. Cheers
just find your textview in your layout:
TextView tv = (TextView)view.findViewById(R.id.yourtextview);
tv.setText("your value");
It depends where you want to set the value. If you just want to set the value after saving it in SharedPreference, then you can simple do:
TextView YourTextView = (TextView) findViewById(R.id.tv);
YourTextView.setText(String.valueOf(importo + valore) );
If you want to set it in some other class, then you can get the value from SharedPreferencce and set in in TextView. See How to use SharedPreferences in Android to store, fetch and edit values for how to get the values. Then after you extract the value, you can set it as I showed in the example above.
Assuming you mean you need to retrieve these values in a different Activity, you retrieve the values with something like
SharedPreferences values = getSharedPreferences(SharedPrefName, 0);
float valore = values .getFloat("Importo", 0);
Then get the String value and set your TextView or just do
textView.setText("" + valore);
The docs have a good example
SharedPreferences full docs
First getValue from Sharedprefrences :
float value = prefs.getFloat( "Importo", 0 );
set float value in your textview:
textview.setText(String.valueOf( value ));
Related
I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}
If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);
Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??
The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");
I made a chat room app which asks the user to enter its username every time i open it. How can i make it remember me? I am using fire-base for the back end.
See Code Here
Create Shared Preference class where first time when user enter his/her username store it.
You can read more about Shared Preference here
The for you as follows
public class SharePref {
public static final String PREF_NAME = "chatroom.shared.pref";
public static final String PREF_KEY = "chatroom.shared.username";
public SharePref() {
}
public void save(Context context, String text) {
SharedPreferences sharePref;
SharedPreferences.Editor editor;
sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
editor = sharePref.edit();
editor.putString(PREF_KEY,text);
editor.apply();
}
public String getData(Context context) {
SharedPreferences sharePref;
String text;
sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
text = sharePref.getString(PREF_KEY,null);
return text;
}
}
Now in your MainActivity you can check if you have already stored the username for user
inside your onCreate()
SharePref sharePref = new SharePref();
String UserName = sharePref.getData(mContext);
if(UserName == null) {
String value = //username value;
SharePref sharePref = new SharePref();
sharePref.save(context,value);
}
else {
// you already have username do your stuff
}
Hope this will help
You can use shared preference. Say you are saving username in String called User. To save username:
SharedPreferences shareit = getSharedPreferences("KEY",Context.MODE_PRIVATE);
SharedPreferences.Editor eddy = shareit.edit();
eddy.putString("AKEY", User);
eddy.commit();
And everytime user login:
SharedPreferences sharedPreferences = getContext().getSharedPreferences("KEY", Context.MODE_PRIVATE);
String getName = sharedPreferences.getString("AKEY", "");
String getName will have the value of your username. The "KEY" and "AKEY" used above are to give special id to different values saved via shared preference.
SharedPreferencec prefs = getSharedPreferences("username",Context.MODE_PRIVATE);
SharedPreference.Editor editor = prefs.edit();
if (!prefs.getString("username",null)
//do the chatting
else {
//show dialog to get username
//now save it in shared preferences
editor.putString("username",username);
editor.commit();
}
I am trying to save an integer value and retrieve the value using a same button using shared preferences.
To be more precise, when i click a button the value should be incremented(i++) and then it should be stored. When i close and open the application, it should retrieve the same value from where i left it. How do i do this?
I am using eclipse.
This works for me
public class OnPreferenceManager {
private SharedPreferences.Editor editor;
private SharedPreferences prefs;
private String startHour = "startHour";
private OnPreferenceManager() {}
private OnPreferenceManager(Context mContext) {
prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
editor = prefs.edit();
}
public static OnPreferenceManager getInstance(Context mContext)
{
OnPreferenceManager _app = null;
if (_app == null)
_app = new OnPreferenceManager(mContext);
return _app;
}
public void setStartHour(int hour){
editor.putInt(startHour, hour);
editor.apply();
}
public int getStartHour(){
int selectionStart = prefs.getInt(startHour, -1);
return selectionStart;
}
}
When you need to set integer just write as below
OnPreferenceManager.getInstance(this).setStartHour(theValueYouWantToStore);
And to retrieve write
OnPreferenceManager.getInstance(this).getStartHour()
You can use shared preferences as below.
//To save integer value
SharedPreferences preference = getSharedPreferences("YOUR_PREF_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YOU_KEY",you_int_value);
editor.commit();
//To retrieve integer value
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
int snowDensity = settings.getInt("YOU_KEY", 0); //0 is the default value
Check this gist https://gist.github.com/john1jan/b8cb536ca51a0b2aa1da4e81566869c4
I have created a Preference Utils class that will handle all the cases.
Its Easy to Use
Storing into preference
PrefUtils.saveToPrefs(getActivity(), PrefKeys.USER_INCOME, income);
Getting from preference
Double income = (Double) PrefUtils.getFromPrefs(getActivity(), PrefKeys.USER_INCOME, new Double(10));
In my application i have to save just an int variable like "score" or "level" so that the progress of the users doesn't go lost.
I tried to parse from a String but it doesn't work for me.
I also tried:
private int readFromFile() {
Scanner getScore= new Scanner(STORETEXT);
punteggio=getScore.nextInt();
return score;
}
where SCORETEXT has been defined:
private final static String STORETEXT = "score.txt";
If i put into the OnCreate:
int points= readfromFIle();
The app crashes.
1) Can you tell me what's the source code to read a Int?
2)I would like to know how to write it to .txt too, just to be sure the code i am using for writing is correct.
You are right in use SharedPreferences. Your app crashes because of empty string resource.
<string name="scoreNow">HERE MUST BE YOUR STRING VALUE</string>
Name attribute in tag is only an identifier, not a value.
But in fact, you shouldn't use strings in resources as key for some value. String resources are needed for localization. Keys for SharedPreferences and same classes better to be constant fields in class. For example, for your code:
public class Storage {
//...
private static final String SCORE_KEY = "score";
public void saveScore(int score) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(SCORE_KEY, scoreValue);
editor.apply(); //apply is better than commit in fact
}
public int readScore() {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int scoreValue = sharedPref.getInt(SCORE_KEY, 0);
return scoreValue;
}
}
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..