I'm new to java and android programming and I want to convert string array to json. Here's the format:
String[][] filters = new String[2][5];
for(int i=0; i<5; i++){
filters[0][i] = "text";
}
for(int i=0; i<5; i++){
filters[1][i] = "text";
}
I tried
JSONArray mJSONArray = new JSONArray(Arrays.asList(filters));
session.editor.putString("filters",mJSONArray.toString());
session.editor.commit();
then I checked it by printing it out like this
System.out.println(session.pref.getString("filters", null);)
but the output is like this
["[Ljava.lang.String;#41b91028","[Ljava.lang.String;#41b910a8"]
The reason why I want to convert it to json is because I want to pass it to a SharedPreferences, which requires a string to be passed. Also, I would also like to know how to decode it. Thanks.
It depends on the library where you have the JSONArray class. But general approach should be that you create an empty JSONArray (for example let's call it parentJsonArray) and then, while looping through your 2 dimensional array elements you put other child JSONArray's into parentJsonArray. Should be something like this:
JsonArray parentJsonArray = new JsonArray();
// loop through your elements
for (int i=0; i<2; i++){
JsonArray childJsonArray = new JsonArray();
for (int j =0; j<5; j++){
childJsonArray.add(filters[i][j]);
}
parentJsonArray.add(childJsonArray);
}
After that, you can pass your parentJsonArray as a String into SharedPreferences and get it in the usual way how you get the simple String.
Converting String Array to jsonArray is not proper way to store to the SharedPreference because reverse is not possible then.
So I Would like to suggest convert string[][] array to Base64 String and store that string to shared preference and you can easily convert That string to String [][] back.
Use below functions to
private String convertTwoDimensionalStringArrayToString(String[][] s){
ByteArrayOutputStream bo = null;
ObjectOutputStream so = null;
Base64OutputStream b64 = null;
try {
bo = new ByteArrayOutputStream();
b64 = new Base64OutputStream(bo, Base64.DEFAULT);
so = new ObjectOutputStream(b64);
so.writeObject(s);
return bo.toString("UTF-8");
} catch (Exception e){
e.printStackTrace();
}finally {
try{
if (bo != null) { bo.close(); }
if (b64 != null) { b64.close(); }
if (so != null) { so.close(); }
}catch (Exception ee){
ee.printStackTrace();
}
}
return null;
}
private String[][] convertStringToTwoDimensionalStringArray(String s) {
ByteArrayInputStream bi = null;
ObjectInputStream si = null;
Base64InputStream b64 = null;
try {
byte b[] = s.getBytes("UTF-8");
bi = new ByteArrayInputStream(b);
b64 = new Base64InputStream(bi, Base64.DEFAULT);
si = new ObjectInputStream(b64);
return (String[][]) si.readObject();
}catch (Exception e){
e.printStackTrace();
} finally {
try{
if (bi != null) { bi.close(); }
if (b64 != null) { b64.close(); }
if (si != null) { si.close(); }
}catch (Exception ee){
ee.printStackTrace();
}
}
return null;
}
How to Use?
session.editor.putString("filters",convertTwoDimensionalStringArrayToString(filters));
session.editor.commit();
get back to String [][] ?
System.out.println(convertStringToTwoDimensionalStringArray(session.pref.getString("filters", null)));
You can use ObjectSerializer class (I've found it somewhere, but don't remember where). You can serialize your object to String and then save it into SharedPreferences as String value. When you need it back, just deserialize it back into object and use it.
There is example:
private void serializeTest() {
final String[][] filters = new String[2][5];
for(int i=0; i<5; i++){
filters[0][i] = "text";
}
for(int i=0; i<5; i++){
filters[1][i] = "text";
}
try {
final String serialized = ObjectSerializer.serialize(filters);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("KEY", serialized).apply();
} catch (IOException e) {
e.printStackTrace();
}
}
private void deserializeTest() {
final String serialized = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("KEY", "");
try {
final String[][] filters = (String[][]) ObjectSerializer.deserialize(serialized);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
And here's ObjectSerializer class source code:
http://pastebin.com/MgJbwYeP
Related
I want to create a multidimensional array and pass it as a parameter in a method and then fill the arrayList with elements and return the new version of the arrayList to be able to use that array in different classes but I get java.lang.NoSuchMethodError: I think the problem is about the way i return the array. I searched but I could not find . How can I do it correctly?
here is my code;
public test{
public static List<List<String>> 2Darray=new ArrayList<List<String>>(); // TE ERROR IN THIS LINE
public List<List<String>> fillArray(List<List<String>> array){
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++){
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
}
return array;
}
A little tinkering (just getting it to compile) results in this which seems not to have a problem. Perhaps your issue is elsewhere.
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for (int i = 0; i < splited.length; i++) {
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return array;
}
BTW: You should really use try with resources - it is much clearer.
Modified your code a bit so that it compiled, and replaced the reading from a text file to reading a string. There were several issues, but it seems to work. Give it a try.
The main problems I noticed were mismatching curly braces, and starting a variable name with a number.
import java.util.*;
import java.io.*;
public class Main {
public static List<List<String>> array2D = new ArrayList<List<String>>();
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
String str = "Some test text";
InputStream is = new ByteArrayInputStream(str.getBytes());
//in = new BufferedReader(new FileReader("sampleFile.txt"));
in = new BufferedReader(new InputStreamReader(is));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++) {
row.add(splited[i]);
}
array.add(row);
}
}
catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
}
finally {
try {
in.close();
}
catch (IOException e) {
}
}
return array;
}
public static void main(String[] args) {
Main main = new Main();
List<List<String>> test = main.fillArray(array2D);
for(int i = 0; i < test.size(); i++) {
for(int j = 0; j < test.get(i).size(); j++) {
System.out.println(test.get(i).get(j));
}
}
}
}
I am trying to add content of a json file to an arraylist. I have done this a couple of times before but I cannot figure out what is wrong in this particular case that I cannot add anything to the arraylist.
So I have a :
private List<Person> persons = new ArrayList<Person>();
and this is how I load the json file from assets folder (from this answer):
public String loadJSONFromAsset() {
String json = null;
try {
// json file name
InputStream is = this.getAssets().open("file.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and to write:
public void writeJson(){
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray response = new JSONArray(loadJSONFromAsset());
for (int i = 0; i < response.length(); i++) {
Person person = new Person();
JSONObject jo_inside = response.getJSONObject(i);
Log.d(TAG, jo_inside.getString("firstName"));
//Add values in `ArrayList`
person.setName(obj.getString("firstName"));
person.setAge(obj.getString("age"));
person.setPhoto(obj.getInt("id"));
// Add to the array
persons.add(person);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
When I try to print the content of persons array for testing purposes, I get nothing using the above method. However, if I insert a person like this :
persons.add(new Person("John", "23 years old", 1));
then it will be added to the array.
I think there is a minor mistake somewhere but I can't find the solution.
There are few corrections needed in your code. Check the comments in the code block.
public void writeJson(){
try {
//this line is not needed, since you are reading array & not not json object
//JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray response = new JSONArray(loadJSONFromAsset());
for (int i = 0; i < response.length(); i++) {
JSONObject jo_inside = response.getJSONObject(i);
Log.d(TAG, jo_inside.getString("firstName"));
//Add values in `ArrayList`
//for setting the values use object read from response array
Person person = new Person();
person.setName(jo_inside.getString("firstName"));
person.setAge(jo_inside.getString("age"));
person.setPhoto(jo_inside.getInt("id"));
// Add to the array
persons.add(person);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This shall solve your issue.
Below is my code. I am converting images into bytearray values.
Here finalPathNames.size() == 4
So i want to save the byteArray values eachtime like byteArray1,byteArray2,byteArray3,byteArray4 which is inside for loop
Set<String> finalPathNames = sharedpre.getStringSet("prePathNames", null);
InputStream is = null;
for (String temp : finalPathNames) {
try {
is = new FileInputStream(temp);
try {
byteArray = streamToBytes(is);
} finally {
is.close();
}
} catch (Exception e) {
}
}
is there any optimized way to find result values
Send the bytes to the server, when you retrieve them or keep them in a list (in case you need them more than 1 time)
// as mentioned in the comments, user wants specifically 4 arrays
byte[][] byteArrays = byte[4][]; //
Set<String> finalPathNames = sharedpre.getStringSet("prePathNames", null);
InputStream is = null;
int index = 0;
for (String temp : finalPathNames) {
byteArrays[index] = new byte[0]; // in case of exception clear array. possibly set to null
try {
is = new FileInputStream(temp);
try {
byte[] byteArray = streamToBytes(is);
byteArrays[index] = byteArray;
} finally {
is.close();
}
} catch (Exception e) {
}
finally {
index++;
}
}
Then the resulting streams are available as:
byteArrays[0], byteArrays[1], byteArrays[2], byteArrays[3],
I have this method that takes a json file from storage and turns it into a bunch of java objects. How do I add bufferred output/input streams in order to speed it up? Or is there another way to optimize the speed?
EDIT: Im not only going to use this for reading from JSON files, so I dont need json to java parsers, I actually need to speed up file oprations using buffers :)
public static ArrayList<String> convertJSONtoArrayList(File jsonStrings) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(jsonStrings);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return convertJSONtoArrayList(fileInputStream);
}
public static ArrayList<String> convertJSONtoArrayList(InputStream fileInputStream) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ArrayList<String> arrayListString = new ArrayList<String>();
int ctr;
try {
if (fileInputStream != null) {
ctr = fileInputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = fileInputStream.read();
}
}
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Parse the data into jsonobject to get original data in form of
// json.
JSONArray jsonArray = new JSONArray(byteArrayOutputStream.toString());
int arrayLength = jsonArray.length();
for (int i = 0; i < arrayLength; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
arrayListString.add(jsonObject.getString(Tags.VALUE));
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayListString;
}
My idea for this being possible comes from here: How to speed up unzipping time in Java / Android? - in the answers becomes clear that if BufferedInputStream is added, the operation is sped up really good.
public static List<String> convertJSONtoArrayList(File f) {
final StringBuilder jsonString = new StringBuilder(500);
try {
final BufferedReader reader = new BufferedReader(new FileReader(f));
String s;
while ((s = reader.readLine()) != null) {
jsonString.append(s);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
return Collections.emptyList();
}
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
int arrayLength = jsonArray.length();
final List<String> result = new ArrayList<String>(arrayLength);
for (int i = 0; i < arrayLength; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
result.add(jsonObject.getString(Tags.VALUE));
}
return result;
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyList();
}
}
or try this (shoule be faster):
public static List<String> convertJSONtoArrayList(File f) {
ByteBuffer buffer = ByteBuffer.allocate(f.length());
try {
ReadableByteChannel channel = Channels.newChannel(new FileInputStream(f));
channel.read(buffer);
channel.close();
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyList();
}
final String jsonString = new String(buffer.array());
try {
JSONArray jsonArray = new JSONArray(jsonString);
int arrayLength = jsonArray.length();
final List<String> result = new ArrayList<String>(arrayLength);
for (int i = 0; i < arrayLength; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
result.add(jsonObject.getString(Tags.VALUE));
}
return result;
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyList();
}
}
Use the same code but wrap a BufferedInputStream around the FileInputStream.
I am making this J2ME application but I am having some problem when I am trying to save I thinks that it save properly but I am not sure....but when I retrieve it gives null
This is how I am storing them
PAR par = new PAR(oldMonPay, newMonPay, oldInterest);
par.setOldMPay(oldMonPay);
par.setNewMPay(newMonPay);
par.setOldInt(oldInterest);
And this is how I saving and retrieving
public static byte[] parseObjPAR(PAR p) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out;
try {
out = new DataOutputStream(baos);
out.writeUTF(p.getNewMPay());
out.writeUTF(p.getOldInt());
out.writeUTF(p.getOldMPay());
} catch (IOException e) {
}
return baos.toByteArray();
}
public static PAR parseByteArrPAR(byte[] b) {
PAR p = null;
ByteArrayInputStream bais;
DataInputStream in;
if (b != null) {
try {
bais = new ByteArrayInputStream(b);
in = new DataInputStream(bais);
p = new PAR(
in.readUTF(),
in.readUTF(),
in.readUTF());
} catch (IOException e) {
}
}
return p;
}
This is how I displaying the retrieved information, there is another problem this thing is not showing all the data but is only showing the 3 records. I think the first 3.
public void populatePAResult(PAR[] p) {
try {
for (int i = 0; i < p.length; i++) {
String oldMP = p[i].getOldMPay();
String newMP = p[i].getNewMPay();
String oldI = p[i].getOldInt();
result1.append("Day : " + oldMP, null);
result1.append("Time : " + oldI, null);
result1.append("Technology : " + newMP, null);
}
} catch (Exception e) {
}
}
In the parseObjPAR method that writes the data the order is:
out.writeUTF(p.getNewMPay());
out.writeUTF(p.getOldInt());
out.writeUTF(p.getOldMPay());
whereas when you read it back in and pass the order the constructor is expecting is different:
PAR par = new PAR(oldMonPay, newMonPay, oldInterest);
so even if it wasn't null the loaded data would be invalid.