How to store ArrayList into sharedPreferences in Android - java

In my application I want store ArrayList into sharedPreferences and get this list in another page!
For store this List i used this library : https://github.com/MrNouri/GoodPrefs
I write below codes, but when get this data I don't know how can get data!
My codes for store list :
for (int i : intList) {
stringBuilder.append("ID : ").append(testPlans.get(i).getId())
.append("Type : ").append(testPlans.get(i).getItemType())
.append("Content").append(steps.get(i).getStepData().toString()).append("-");
App.stepsBodyList.add(new DataItem(testPlans.get(i).getId(),
testPlans.get(i).getItemType(),
steps.get(i).getStepData().toString()));
}
GoodPrefs.getInstance().saveObjectsList(TEST_STEPS_STORED_LIST, App.stepsBodyList);
My codes for get data :
private List<DataItem> storedStepsBodyList = new ArrayList<>();
Toast.makeText(context, ""+
GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,).size()
, Toast.LENGTH_SHORT).show();
This library for get list give me 2 constructor, one is tag name and second value is default! (TEST_STEPS_STORED_LIST,)
But I don't know can i set default value for second item of constructor!
I write this GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,storedStepsBodyList) but show me error for this storedStepsBodyList .
How can i fix it?

Simple way, you can use Gson library, add it to build.gradle, it will serialize your list to JSON and save it to SharePreference
implementation 'com.google.code.gson:gson:2.8.6'
public void saveItems(List<Item> items) {
if (items != null && !items.isEmpty()) {
String json = new Gson().toJson(items);
mSharedPreferences.edit().putString("items", json).apply();
}
}
public List<Item> getItems() {
String json = mSharedPreferences.getString("items", "");
if (TextUtils.isEmpty(json)) return Collections.emptyList();
Type type = new TypeToken<List<Item>>() {
}.getType();
List<Item> result = new Gson().fromJson(json, type);
return result;
}

Related

Reading data from Android App using bluetooth

I have Java code to receive data in Android App via Bluetooth like the attached code
Java Code
so readMessage will equal = {\"Pin\":\"A4\",\"Value\":\"20\"},{\"Pin\":\"A5\",\"Value\":\"925\"},{\"Pin\":\"A0\",\"Value\":\"30\"}
So I want to take only the values after string \"Value\" from received data so
Can anyone suggest how to make do that?
Thanks
you can parse the readMessage with JSON format
example:
String[] pinValueArr = readMessage.split(",")
for (String pinValue : pinValueArr) {
try {
JSONObject pinValueJSON = new JSONObject(pinValue);
String pin = pinValueJSON.optString("pin", ""); // opt means if parse failed, return default value what is ""
int pin = pinValueJSON.optInt("Value", 0); // opt means if parse failed, return default value what is "0"
} catch (JSONParsedException e) {
// catch exception when parse to JSONObject failed
}
}
And if you want to manage them, you can make a List and add them all.
List<JSONObject> pinValueList = new ArrayList<JSONObject>();
for (String pinValue : pinValueArr) {
JSONObject pinValueJSON = new JSONObject(pinValue);
// ..
pinValueList.add(pinValueJSON);
}
You can use Gson to convert Json to Object.
(https://github.com/google/gson)
Create Model Class
data class PinItem(
#SerializedName("Pin")
val pin: String? = null,
#SerializedName("Value")
val value: String? = null
)
Convert your json.
val json = "[{"Pin":"A4","Value":"20"},{"Pin":"A5","Value":"925"},{"Pin":"A0","Value":"30"}]"
val result = Gson().fromJson(this, object : TypeToken<List<PinItem>>() {}.type)
So now you having list PinItem and you can get all info off it.

Android-Java List to String and vice versa

I am new to Android programming and I wanted to create a function to take in a list and return a String. That's my code:
private String List_to_String(final ArrayList<String> list) {
String returnString = "{";
for (String _s : list) {
returnString = returnString + _s.replace(":","\\:") + ":";
}
if (returnString != null && returnString.length() > 0) {
returnString = returnString.substring(0,
returnString.length() - 1);
}
returnString = returnString.concat("}");
return returnString;
}
It works but now I want to make a function that returns a ArrayList when I give a String generated with the function above also I think you need to take extra care of the ":".
So if I have a String
HDJDJJDJ:JSJSJSJJSJS:SJJSHS\:\:JS
the function should return a list with these items
HDJDJJDJ
JSJSJSJJSJS
SJJSHS::JS
Can you understand me
Thanks for your help
Maybe you can try something like this.
In Android Studio
[File]->[Project Structure]->[Dependencies]->[Add Dependency]->[Library Dependency]-> choose 'app'(If you have multiple modules) -> search for 'GSON' -> choose implementation.
Initialize Gson in java class :
Private Gson gson = new Gson();
String to List :
List<T> myList = new ArrayList<T>();
String myString = gson.toJson(myList);
List to string :
Type myType = new TypeToken<List<T>>(){}.getType();
myList = gson.fromJson(myString, myType);

How to save JSONdata into a set?

I have a data set. It is of the form
{
"name1": 123
"name2": 234
"name3": 345
.
.
.
}
Now, I am using a #RestController to read this through PostMan. I have a class test.java.
I have a function,
public void testController(#RequestBody String request)
I'm running this through a local host with the help of #RequestMapping. I need to save the above data set one by one in an object. The object is as follows.
public class OperatorClass implements Comparable<OperatorClass>{
private String name;
private ArrayList<String> id = new ArrayList<>();
OperatorClass(String name, String id)
{
add_id(id);
add_name(name);
}
I am trying to save this data in the following way, which by the way I have figured out is wrong.
try {
JSONObject array = new JSONObject(request);
Iterator<String> stringIterator1 = array.keys();
stringIterator1.next();
ArrayList<String> arrayList = new ArrayList<>();
OperatorClass oco = new OperatorClass(array.keys().,array.get(array.keys().toString()).toString());
System.out.println(oco.get_Name());
System.out.println(oco.get_Id());
} catch (Exception e) {
e.printStackTrace();
}
I know it is wrong because array.keys() gives all the name1, name2, name3 data. What I want to know is how to get just name 1 for this. And how to get it's following ID, to insert into a particular object.I was trying to save the object into a set of operator class.
Ok. I have got an answer to this problem. We use
String temp = stringIterator1.next();
And instead of
OperatorClass oco = new OperatorClass(array.keys().,array.get(array.keys().toString()).toString());
We use,
OperatorClass oco = new OperatorClass(temp, array.get(temp).toString);
Just remember that using string iterator will probably not display the values in the order of the data set, due to hash mapping.

Wicket : pass json to ListView in java

List userList = Arrays.asList(
new User[] {
new User("FirstA", "LastA"),
new User("FirstB", "LastB"),
new User("FirstC", "LastC")
});
add(new ListView("listview", userList) {
protected void populateItem(ListItem item) {
User user = (User) item.getModelObject();
item.add(new Label("firstname", user.getFirstname()));
item.add(new Label("lastname", user.getLastname()));
}
});
The above code adds values from List userList and displays Firstname and LastName in Table.
I need to pass JSONObject to ListView.
Json schema -
{"schema":[{"name":"John","id":"01"},{"name":"Sam","id":"02"}]}
Json is passed from Database -
JSONObject json=widget.getJsonForTableContent(query); //QUERY from Database
json.toString();
System.out.println(json); //Prints json - {"schema":[{"name":"John","id":"01"},{"name":"Sam","id":"02"}]}
Iterator<String> iter=json.keys();
while(iter.hasNext())
{
String key = iter.next();
System.out.println(key); //prints only "schema" from json in console
}
The key value prints only "schema" in console.
How to parse and iterate json to print "name" and "id" also and pass these values to ListView to display in wicket Table
I am just a beginner.Any help would be appreciated.Thankyou
Here is standard API for a JSON parser / additional overview with examples
The overview provides an example of using the API to parse JSON from an InputStream:
URL url = new URL("https://graph.facebook.com/search?q=java&type=post");
try (InputStream is = url.openStream();
JsonParser parser = Json.createParser(is)) {
while (parser.hasNext()) {
Event e = parser.next();
if (e == Event.KEY_NAME) {
switch (parser.getString()) {
case "name":
parser.next();
System.out.print(parser.getString());
System.out.print(": ");
break;
case "message":
parser.next();
System.out.println(parser.getString());
System.out.println("---------");
break;
}
}
}
}
Not sure where you'll ultimately be deriving your JSON data from but if you wanted to test it with a static string you could convert the string to an input stream as follows:
InputStream stream = new ByteArrayInputStream(json.toString().getBytes(StandardCharsets.UTF_8));
As for the ListView part of your question - it wouldn't be very difficult once you have parsed out the tokens to add them to the ListView similarly to what you've done.

Android get data from json and sort

I'm trying to get data from json. I can get data at first state.
But how to get data "ascending" and "descending" and show it on another activity in listview ?
Here's My Json
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
And here's my Java code
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String table_name = c.getString(TAG_TABLE_NAME);
String item_list = c.getString(TAG_ITEM_LIST);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CATEGORY_NAME, category_name);
contact.put(TAG_TABLE_NAME, table_name);
contact.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodlistfilter.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm trying to follow this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/, but i still don't fully understand.
Let me explain this.
[ means its an array.
{ is an object.
In your case it's an array whcih contains an -JSONObject with name category_name, filter_type and field_name. type and table_name and a new jsonarray with object item_list.
How can you parse this string?
Here is an example:
String str = "[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}";
JSONArray jsonArray = new JSONArray(str);
//now it holds the JSONObject.
for (int i = 0; i<= jsonArray.length(); i++) {
//now we loop through and get the jsonObject
JSONObject jsonObj = new JSONObject(jsonArray.getJsonObject(i));
//now it contains your data.
Log.d("Category_nameValue=", jsonObj.getString("category_name"));
//now we want to get the array from the item_list.
JSONArray itemList = new JSONArray(jsonObj.getString("item_list"));
//now itemList.getString(1); === Ascending while itemList.getString(2) == Descending
//now itemList contains several new objects which can also be looped as the parent one.
}
Since you now know how to create an JSONArray, you can start sorting it.
This has been answered already at Android how to sort JSONArray of JSONObjects
If you want to send those data to another Activity you can use the JSONArray.toString() method and send it via Intents.
This is easy explained at Pass a String from one Activity to another Activity in Android
Hope this helps.
If you're new, I would recommend you think about using Gson to parse your Json response directly to a java entity class. So you will avoid to manually parse all your responses.
Your JSON response
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
The entity representing the response
public class MyEntity {
String category_name;
String filter_type;
String field_name;
String type;
String table_name;
String [] item_list;
// getters / setters ...
}
Parsing the response
Gson gson = new Gson();
MyEntity myEntity = gson.fromJson(response, MyEntity.class);
Finally, to send the data, start the new Activity with extras
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("EXTRA_DATA", myEntity.getCategoryName());
startActivity(intent);
Now you recover the extra data on your AnotherActivity
Intent intent = getIntent();
String categoryName = intent.getStringExtra("EXTRA_DATA");
And you can fill the ListView using an ArrayAdapter: Example
To get a JSONArray from your JSONObject c
simply write:
JSONArray itemList = c.getJSONArray(name);
then you can iterate through that data like any other array
for (int i = 0; i < itemList.length(); i++) {
// do something
}

Categories

Resources