Converting ArrayList to String to store in Shared Preferences - java

i have ArrayList with multiple value. i want to convert this ArrayList into String to save in sharedPreferences, then I want to retrieve the String and convert it back to ArrayList
Please tell how to do that? (or any other idea to store and retrieve ArrayList)

Convert arraylist to string:
String str = "";
for (String s : arraylist)
{
str += s + ",";
}
Save string into sharedpreference:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("mystr", str).commit();
get string from sharedpreference:
String str = PreferenceManager.getDefaultSharedPreferences(context).getString("mystr", "defaultStringIfNothingFound");
Convert string to arraylist:
List<String> arraylist = new ArrayList<String>(Arrays.asList(str.split(",")));

You can use Google's GSON.
Gson is a Java library that can be used to convert Java Objects into
their JSON representation. It can also be used to convert a JSON
string to an equivalent Java object. Gson can work with arbitrary Java
objects including pre-existing objects that you do not have
source-code of.
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html
https://code.google.com/p/google-gson/
You get the idea:
Store: Convert Object to JSON String -> Save string
Retrieve: Get string -> Convert from JSON to Object

Related

Write Java string array to JSON array using Jackson JSON Generator

I want to write java string array into JSON array.
Array : ["abc","def","ghi","jkl","mno"]
One way is to loop over the array and add the elements one by one as below
JsonGenerator jsonGen = factory.createGenerator(output, JsonEncoding.UTF8);
jsonGen.writeArrayFieldStart("args");
for (String val : arr) {
jsonGen.writeString(val);
}
jsonGen.writeEndArray();
Is there any way to convert a string array into JSON array directly (i.e. without iterating over it)?

How to extract data from Json array?

Using Jsonobject I extracted data from RawmatrixData and stored it in Object:
org.json.JSONObject item = Fir.getJSONObject(i); Object value1 = item.get("RawMatrixData")`
Now i want to replace data 342771123181 with some string value, how to achieve this?
I tried with ArrayList<String> and ArrayList<ArrayList<String>>.
"LstMatrixFirmInfo": [
{
"RawMatrixData": "[[342771123181,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[3427714486446,1,2,null,null,null,null,null,null,null,null,null,null,null,28.99,28.99,28.99,25,4.81,4.81,4.81,null,null,null,null,null,null,null,null,null]]]}
Is RawMatrixData supposed be a string like in the image or JSON Array.
If RawMatrixData is supposed to be string then maybe converted to JSONArray
I would just use string replace.
String replacedText = Fir.getString('RawMatrixData').replace('342771123181', 'foobar')
Fir.push('RawMatrixData', replacedText);
The above can be done in one line but for ease of understanding it hasn't. First line gets your string from the Json object then replace the number with foobar.
Then text is pushed back on to the json object overwriting the old value.
The above code i believe sorts out your problem based on the picture you provided.
If the RawMatrixData was supposed to be a JSON array and not a string then in that case you would have to traverse the whole array replace as you go.

String.split for JSON array

I have the following string and I need to split it to get the two objects inside:
[Object{value1="1", value2="2"}, Object{Value1="1", value2="2"}]
You could try:
String[] splitTextObject = YOUR_STRING.split(", ");
String object1 = splitTextObject[0];
String object2 = splitTextObject[1];
...
But I don't think you actually need to split the string this way in order to achieve getting each object, and instead you should consider parsing your JSON. Perhaps utilise GSON.

passing JSON array from JavaScript to java and convert JSON array to java array

In my application, I need to pass JSON array to java then convert that array to java array using java as a language. Here is the code.
JavaScript
function arraytofile(rans)
{
myData.push(rans); // rans is the random number
var arr = JSON.stringify(myData);// converting to json array
android.arraytofile(arr); // passing to java
}
Java
public void arraytofile(String newData) throws JSONException {
Log.d(TAG, "MainActivity.setData()");
System.out.println(newData);
}
newData is printing data as [[2],[3],[4]]... I want in regular java array. How I can achieve this?
You can use Google gson . An excellent Java library to work with JSON.
Find it here: https://code.google.com/p/google-gson/
Using gson library classes you can do something like this:
// I took a small sample of your sample json
String json = "[[2],[3],[4]]";
JsonElement je = new JsonParser().parse(json);
JsonArray jsonArray = je.getAsJsonArray();
// I'm assuming your values are in String, you can change this if not
List<String> javaArray = new ArrayList<String>();
for(JsonElement jsonElement : jsonArray) {
JsonArray individualArray = jsonElement.getAsJsonArray();
JsonElement value = individualArray.get(0);
// Again, I'm assuming your values are in String
javaArray.add(value.getAsString());
}
Now you have your json as Java List<String>. That's basically as array.
If you know exact number of results, you can surely define an array of fix size and then assign values to it.
If you know Java, than you already know how to go from here.
I hope this helps.

Multidimensional Arrays to store multiple data types

I know php a little. and java much little.
I am creating a small application to search a text in a text area and store the result in a array.
The array in PHP will look like this.
array(
"searchedText" => "The text that is searched",
"positionsFound" => array(12,25,26,......),
"frequencies" => 23 //This is total words found divided by total words
);
But, java does not support array with multiple data types. In the above array, only the second element "positionFound" is of variable length.
Later on I need to iterate through this array and create a file including all above mentioned elements.
Please guide me
Java does support Objects. You have to define a Class like
class MyData {
String searchedText;
Set<Integer> positionsFound;
int frequencies;
}
List<MyData> myDataList = new ArrayList<MyData>();
// OR
MyData[] myDataArray = new MyData[number];
And you can use this structure to hold your data. There are other methods which are helpful such as constructors and toString() and I suggest you use your IDE to generate those.
When writing this data to a file, you might find JSon a natural format to use.
I suggest you look at GSon which is a nice JSon library.
From the GSon documentation, here is an example
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj

Categories

Resources