I'm trying to save a string in preference by adding it to the editor when a user press a button. Then i'm trying to retreieve the strings from the preference and turn it into an arrayList.
in onCreate
this.context = getApplicationContext();
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
int size = updatableList.size();
editor.putInt("list_size", size);
for (int i = 0; i < size; i++) {
((SharedPreferences) editor).getString("list_"+i, updatableList.get(i));
}
editor.commit();
Later in the application
updatableList.add(picturePath);
i=i++;
//saving path to preference********
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
((Editor) editor).putString("list_"+i, picturePath);
editor.commit();
It says the prefs later in the application is unused which i think is odd because i thought it told it to putString. The application crashes when it gets to there. Why does my prefs later in the application get used?
I see a main problem here and it's the following line:
i=i++;
This will not change i at all. You're telling it to increment i but at the same time setting i to the value prior to incrementing it. i++; is what you want.
Also I'd suggest using SharedPreferences.Editor.putStringSet() instead of putString() - that way you don't need to care about size and so on.
Are you trying to getString or putString here
for (int i = 0; i < size; i++) {
((SharedPreferences) editor).getString("list_"+i, updatableList.get(i));
}
Cos the code before this, does a putInt.
SharedPreference works like a key value pair. If the key is not found, it returns the default value.
From the above code, you are first trying to getString and later trying to putString. So the initial get will return default value.
Also, you have mentioned that the code crashes. Do you mind pasting the crash log.
In saving pref try it like this snippet
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString("KEY", "value");
edit.commit();
And to fetch it
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.getString("KEY", "defaultValue");
Related
I am making a game and I'm trying to display the highscore. honestly I don't know what I am doing. I could really use some help.
I want to display the highscore in two digits (e.g. 01, 02, 03 ... 09, 10, 11).
private class MainActivity extends Activity {
private TextView highscore;
private int hs=00;
private TextView mtvscore;
private int Score = 00;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mtvscore = (TextView) findViewById(R.id.score);
mtvscore.setText("" + Score);
highscore = (TextView) findViewById(R.id.highscorelabel);
highscore.setText("" + hs);
SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int hs = settings.getInt("HIGH_SCORE", 0);
if (Score > hs) {
highscore.setText(Score);
SharedPreferences.Editor editor = settings.edit();
editor.commit();
} else {
highscore.setText(score);
}
}
}
Use String format
String twoDigitsHighscore = String.format("%02d", Score);
highscore.setText(twoDigitsHighscore);
See the javadocs
Remember, this is Java, not Android related only. String.format is a Java method, nothing to do with Android.
Android is built using Java.
Try to learn more about what is Java, where does it ends and where Android starts to make your learning process better, as you shouldn't search for "Android two digits integer". You should search for "Java two digits integer".
So you need to take your number and format it to a string. It is done automatically for you when you use highScore.setText. Instead you need to use String.format()
highscore.setText(String.format("%02d", score));
For shared preferences you need.
SharedPreferences preferences = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("HIGH_SOCRE", score);
editor.apply();
I have 10 frameLayouts in LinearLayout. In my app I can move these frames, but if I close it, position of my frames didn't save. And if I open app again I see default position of my frames?
How can I save position? Help!!
P.S. In my app I use sharedPreferences.
You can use Shared Preferences to store stuff in memory and restore them at later time:
Android docs for SharedPreferences
Example - Storing and restoring an integer called position:
int position = 0;
//get the SharedPreferences for "yourContextName", which you need to replace it with you context name
SharedPreferences pref = getSharedPreferences("yourContextName", Context.MODE_PRIVATE);
/* --------------- Storing data -------------------- */
//Get editor for writing data to memory
SharedPreferences.Editor editor = pref.edit();
//Add an integer to editor
editor.putInt("position", position);
//Must commit or else the data will NOT be stored
editor.commit();
/* ---------------- Retrievig data ------------------ */
//Retrievig an integer from pref with tag "position" (-1 is the default value)
int retInt = pref.getInt("position", -1);
I have a main activity which has two fragments and I am trying to pass some data which I want to append on above whatever texts is already on a edittext on the next fragment.
Activity with two separate Tabs:
The following works fine:
Fragment #1:
String y = "TEST 1";
SharedPreferences prefs; // shared preferences
prefs = getActivity().getSharedPreferences("spa", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("someId", y);
editor.commit();
Fragment #2:
SharedPreferences prefs; // shared preferences
prefs = getActivity().getSharedPreferences("spa", Context.MODE_PRIVATE);
String someId=prefs.getString("someId","");
showLog.setText(someId + "\n HERE"); //this overwrites the text and is multiline
What I am looking to do is I want the showLog to append above what's already there.
My showLog is the following:
<EditText
android:id="#+id/showLog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Nothing to display"
android:inputType="textMultiLine"
android:lines="12"
android:paddingLeft="2dip"
android:singleLine="false"
android:textColor="#999999"
android:textSize="14dip"
android:textStyle="normal"
android:gravity="top" />
For example:
showLog already starts out with having "THIS IS A TEST" in the textbox
When the SharedPreference is called, the showLog should display the following:
TEST 1
HERE
THIS IS A TEST
But that's not happening. I tried using .append() which didn't have any affect.
I think I understand what you're trying to do now, you might want to try:
int start = showLog.getSelectionStart();
int end = showLog.getSelectionEnd();
String toIns = someId + "\n HERE";
showLog.getText().replace(Math.min(start, end), Math.max(start, end), toIns, 0, toIns.length());
Technically it's not appending, rather replacing the end of the string with new text.
EDIT: in light of the new issue arising, here are my edits to your project, let me know if there's anything wrong still.
My edited version is on the right, original on the left
CurrentTrip.java
DisplayTrip.java
What I'm doing with the text might not be exactly what you want, so make sure to let me know if it's not.
EDIT 2: And to delete the stored values:
final SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
EDIT 3: Having understood exactly what it is you want to do, here's one way to do it by storing the last trip added, and keeping track of the text you need in your TextView.
prefs = getActivity().getSharedPreferences("spa", Context.MODE_PRIVATE);
// Find the string we want
String someId = prefs.getString("someId","");
final Editor editor = prefs.edit();
// To stop a trip being added in onResume etc.
if(someId != prefs.getString("previous-trip", "")){
showLog.setText(someId + prefs.getString("previous", ""));
} else {
// Without this else, we'd have a blank box again
showLog.setText(prefs.getString("previous", ""));
}
// Store the latest trip that was added
editor.putString("previous-trip", someId);
// Store everything that's in the box so far for next time
editor.putString("previous", showLog.getText().toString());
// Commit to the prefs
editor.commit();
If I understand what you are trying to get then you should be able to do
String text = showLog.getText().toString();
showLog.setText(someId + "\n HERE" + text);
If you already have text in it then you just get that text and after opening up your SharedPreference put it all in with the original text last.
Intent extras
In first Activity
String someText = someTextString;
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("key", someText); // add some extra to the Intent to pass to next Activity
startActivity(i);
In SecondActivity
Intent intent = getIntent();
String myText = intent.getStringExtra("key"); // use same key value used in first Activity
About the part where you need to display the String:
// From what you have given, the TextView `showLog` is already displaying some text
// and you want to place another another String in front of it(prepend)
showLog.setText(stringToAdd + showLog.getText());
// "stringToAdd" is the string you trying to pass between activities(or fragments)
I am working on this app where I have one EditText field where you can write something and then it get saved and added to a list(TextView). I save the content of the EditText in this way:
saved += "*" + editTextFelt.getText().toString() + ". \n";
saved is a String.
Everything works fine, I can even reload the app and it's still displayed in the TextView, but if I try to write something and save it everything that was there, now disappears. Why?
CODE:
init Method()
sp = getSharedPreferences(fileName, 0);
betaView = (TextView)findViewById(R.id.betaTextView);
I've got a button to send the text, and this is like:
public void onClick(View v) {
switch(v.getId()){
case R.id.btnSend:
saved += "*" + editTextFelt.getText().toString() + ". \n";
SharedPreferences.Editor editor = sp.edit();
editor.putString("SAVED", saved);
editor.commit();
betaView.setText(sp.getString("SAVED", "Empty"));
How are you saving it? because when you save a text against a variable it replaces the previous one.
So you need to get the previous one and then append the new one and then again save it to SharedPreferences, something like this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String saved = sp.getString("YourVariable", "");
saved += "*" + editTextFelt.getText().toString() + ". \n"; //appending previous
//Editor to edit
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourVariable",saved);
editor.commit(); //don't forget to commit.
now set this appended text to your TextView like this:
betaView.setText(saved);
I have some code that collects a number, I am able to prove that I am genuating a number will im doing this but when I go to save the number using this code
public void SaveScore()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Score", (StringScore));
}
Then I call it back later in another page with this code
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
ScoreString = (settings.getString("Score", "0"));
Score.setText(ScoreString + "%");
It comes up as 0 I know that it is the default number so why am I not saving the number?
You've forgotten to do an editor.commit() to commit your changes.