Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to add a dynamic textview to the page when I click OK in the dialog box. My problem is that I want that textview to be visible even when the app is opened again.
P.S. I can add multiple textviews(1 at a time) and all should be visible on opening app again. Example : Creating a new Playlist and the new playlist name appears always . Can anyone guide me how to do this?
You can store info about added TextView-s in SharedPreferences and when app is opened again get this info from SharedPreferences by getStringSet for example (to get added TextView's key names) and by other methods and create new TextView-s and add them to an activity layout.
ADDITION:
The most universal approach to this task is to save JSONArray which contains TextView-s data in SharedPreferences as a string by using toString() method and when app is opened again read JSONArray from SharedPreferences as a string and fill data of newly created TextView-s.
EXAMPLE:
private JSONArray data;
...
SharedPreferences pref = getSharedPreferences("application", 0);
data = new JSONArray( pref.getString("text_views_data", null) );
List<TextView> tvList = new ArrayList<TextView>();
for (int i = 0; i < data.length(); i++){
JSONObject ob = data.get(i);
TextView tv = new TextView(this);
tv.setText( ob.getString("text") );
tvList.add(tv);
}
...
private saveTextViewData(TextView tv){
JSONObject ob = new JSONObject();
ob.put("text", tv.getText());
data.put(ob);
SharedPreferences preferences = getSharedPreferences("application", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("text_views_data", data.toString() );
editor.commit();
}
You should call saveTextViewData method when you add new TextView.
you can store each the TextView as an object in an array of objects. Then you can save this array in a SharedPreferences then when you open the application get the array from SharedPreferences and add the TextViews to the application dynamically.
This is a simple solution!
Related
i create app where when user added new data , there is new label
I have tried and it worked, but I wonder how can I make the json that I store in SharedPreferences
do not over write
so I can add 2 or more user json to adapter
Here is my put string file the json variable contain user that added
SharedPreferences sharedPreferences = getSharedPreferences("newUser", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("listNewUser",json)
editor.apply();
Here is how I can get json from shared preference
try{
String listNewUserAdd = sh.getString("listNewUser","");
JSONObject object = new JSONObject(listNewUserAdd);
for (int i=0; i<object.length(); i++) {
CustomerNew customer = new CustomerNew();
customer.setCustomerName(object.getString("receiverName"));
customer.setAccountId(object.getString("customerReference"));
customer.setId(object.getLong("customerId"));
System.out.println("### GET CUSTOMER NAME "+customer.getCustomerName());
listSortNew.add(customer);
if (listSortNew == null) {
// if the array list is empty
// creating a new array list.
listSortNew = new ArrayList<>();
}
}
I think there are two ways to realize it. One way is when you put data you have to check if it exists.
SharedPreferences sharedPreferences = getSharedPreferences("newUser", MODE_PRIVATE);
String listNewUser = sharedPreferences.getString("listNewUser","");
if(!TextUtils.isEmpty(listNewUser)){
//covert it the list object
//then add the all new item to it
//finally convert it to json string
}
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("listNewUser",json)
editor.apply();
the other way is to change the SharedPreferences MODE_APPEND
but you must know, it doesn't mean that you add multiple values for each key. It means that if the file already exists it is appended to and not erased. We usually used MODE_PRIVATE
In the end I suggest you firstly get the data from it, then check if you need change, you can change the data, then save it again.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Welcome everyone!
I'm programming a mobile game on Anroid.
I really want to know how to save Player Data.
It will be a game that can be run on different devices without loss of data.
Using SharedPreferences
Using JSONObject, JSONArray and save it into file in Internal Storage and upload it to the external server
SQLite, MySQL
What would you choose? What are the pros and cons of each option?
I would like to save data for example:
Highscore
Life
Mana
Count of steps
Level of character
Amount of money
and more...
SharedPreferences should be the way to go for such a small amount of data. There are many benefits to using them over SQLite in this example.
I would discourage using external server because I personally would not like my game to require internet for playing.
It depends on how much player data there will be. But unless there is a lot of player data, I would suggest using shared preferences, especially if there is something simple like a Player object, or a list of Player objects. that will cover it.
You could use something like the following for a list of Players, and change any reference to that list to just a Player object if you only want to save 1. If you have a lot of data, players, or would need extra security you may want to go with SQLLite.
public class PlayerPrefs {
private static final String PLAYERS_PREF_FILE = "PLAYERS_PREF_FILE";
private static final String PLAYERS = "PLAYERS";
private static SharedPreferences getPrefs(){
final Context context = ApplicationData.getAppContext();
return context.getSharedPreferences(PLAYERS_PREF_FILE, Context.MODE_PRIVATE);
}
public static List<Player> getPlayers() {
final Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Player>>() {}.getType();
SharedPreferences prefs = getPrefs();
String players = prefs.getString(PLAYERS, null);
if (players == null){
return new ArrayList<Player>();
}
return gson.fromJson(players, listType);
}
public static void setPlayers(List<Player> players) {
final Gson gson = new Gson();
if (players != null) {
final SharedPreferences prefs = getPrefs();
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PLAYERS, gson.toJson(players));
editor.apply();
}
}
}
Also, you'll need to include the following in your Gradle file:
compile 'com.google.code.gson:gson:2.5'
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am developing an android application were I want to parse data through an array to URL API.
Taking an example, there are 5 TextBox and I enter some information in it. Then all the values entered in textView should parse in an array format to That API URL.
Please help!!
This is what i did, note that this is just an example.
final Map<String,String> postParam = new HashMap<String, String>();
for(int i = 0; i < 5; i++)
postParam.put("child_id[" + i + "]", i+"");
You will get :
child_id[0] with value 0
child_id[1] with value i
And goes on.
UPDATE
In your case, you might want to do something like :
postParam.put("child_id[" + i + "]", myEditText.getText.toString());
for each of your edittext.
Feel free to comment if you dont understand my answer or if i miss-understood you.
I hope i am understanding you correctly, you want to put 5 TextBox's entered text into one Array and then send this Array to API.
Try this:
ArrayList<String> textViewTexts = new ArrayList<String>();
// Put all EditText's text to array
// Do this for each EditText
textViewTexts.add(someEditText.getText());
You can then use textViewTexts.toString() and send this to API.
EDIT:
you can parse textViewTexts like this:
for (int i = 0; i < textViewTexts.size(); i++) {
String text = textViewTexts.get(i);
// Do something with text..
}
EDIT2:
you can parse textViewTexts like this:
JSONArray jArray=new JSONArray();
for (int i = 0; i < textViewTexts.size(); i++) {
String text = textViewTexts.get(i);
jArray.put(text);
}
// Send JSONArray to API
jArray.toString();
If you want to send that array to server via an api, then you should send data in JSONArray like this
JSONArray jArray=new JSONArray();
jArray.put(yourTextViewText1);
jArray.put(yourTextViewText2);
jArray.put(yourTextViewText3);
jArray.put(yourTextViewText4);
jArray.put(yourTextViewText5);
and you can send that to server like that
params.put("key",jArray.toString());
Moreover, It is easy for you web developer to parse this JSONArray.
My application is basically a quiz that presents people with world flags. I want to add a save function that adds the current flag to a separate list. Right now, this is what I do when they click the "save" button:
saveListGC.add(playList.get(1));
(playList.get(1) is the current flag). The problem is, I have to re-define the saveListGC every time the script starts, and that empties the contents:
public static ArrayList<String> saveListGC = new ArrayList<String>();
So what I'm wondering is how can I save this data, and re-load it later? I've seen things about using SharedPrefernces, but I don't really understand it. If someone could please explain it as easily as possible, I would really appreciate it. Thank you!
This a simple example of how you can use SharedPreferences:
//intiat your shared pref
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
//store data to pref
editor.putString("myString", "value 1");
editor.commit();
//retrieve data from pref
String myString = pref.getString("myString", null);
But the real problem here is that SharedPreferences can not store an Object of type List (ArrayList), but you can store an Object of type Set (like Hashset) using this method
Set<String> mySet = new HashSet<String>();
mySet.add("value1");
mySet.add("value2");
mySet.add("value3");
editor.putStringSet("MySet", mySet);
So to answer your second question, this what i propose for you to do:
//This is your List
ArrayList<String> saveListGC = new ArrayList<String>();
//Convert your List to a Set
Set<String> saveSetGC = new HashSet<String>(saveListGC);
//Now Store Data to the SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
editor.putStringSet("MySet", saveSetGC);
editor.commit();
//After that in another place or in another Activity , Or every where in your app you can Retreive your List back
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Set<String> mySetBack = pref.getStringSet("MySet", null);
//Convert Your Set to List again
ArrayList<String> myListBack = new ArrayList<String>(mySetBack);
//Here you can se the List as you like...............
Log.i("MyTag", myListBack.get(0));
Log.i("MyTag", myListBack.get(1));
Good Luck :)
I created a simple game. At the end the user's name and score is supposed to get into a highscore list. For this i would like to store these data in sharedpreferences. I saw a post and i am trying to apply it to my app but it force closes. I don't even know if this is the right thing i am doing. So i put these keypairs (player, score) into an arraylist. From there i can get the values out into a listview.
This is just an example.
SharedPreferences.Editor scoreEditor = myScores.edit();
scoreEditor.putString("PLAYER", "Thomas");
scoreEditor.putString("SCORE", "5");
scoreEditor.commit();
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
Map<String, ?> items = myScores.getAll();
for(String s : items.keySet()){
HashMap<String,String> hmap = new HashMap<String,String>();
hmap.put("PLAYER", s);
hmap.put("SCORE", items.get(s).toString());
LIST.add(hmap);
}
Toast.makeText(Start.this, "LIST size: "+LIST.size(), Toast.LENGTH_LONG).show();
For me it would also be okay if i store these data like this:
scoreEditor.putString("DATA", "Thomas" + "-" + "5");
and put that into ArrayList<String> LIST = new ArrayList<String>();
but i don't know how to do it.
Could you guys help me with this?
Edit: So i could go another way as Haphazard suggested. I put together this code, but i don't know if this is the way to do it. I haven't tested it yet, as sg is wrong with the sharedpreferences and i am still trying to figure it out.
SharedPreferences.Editor scoreEditor = myScores.edit();
scoreEditor.putString("DATA", "Thomas" + "-" + "5");
scoreEditor.commit();
HashSet<String> hset=new HashSet<String>();
hset.addAll((Collection<? extends String>) myScores.getAll());
ArrayList<String> LIST = new ArrayList<String>(hset);
The SharedPreferences Editor does not accept Lists but it does accept Sets. You could convert your List into a HashSet or something similar and store it like that. When your read it back, convert it into an ArrayList, sort it if needed and you're good to go.
Please note that the Set has to be a set of Strings so you will have to stick with your "Thomas" + "-" + "5" setup.
Edit: To your new update, I was thinking more of something like
//Retrieve the values
Set<String> set = new HashSet<String>();
set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
That code is untested, but it should work
EDIT: If your API level is below the get/setStringSet() level then you can try this:
1) Turn your list of high scores into a delimited string. That means if you had ["Tom, 1", "Ed, 5"] you could loop through it and turn it into a String like "Tom, 1|Ed, 5". You can easily store that using setString(..).
2) When you want to read the values back, perform a getString(..) and then String.split("|") to get the original list back. Well, it returns an array but that can be converted to a list easily enough.