caly__pso
caly__pso

Reputation: 168

Output JSON to file, then input it back in

I'm writing an app for Android where I need to output some objects' info to a file so that it's still there when the user closes the app, etc. For now, I'm only outputting these objects as strings "name", each with their own "value". And just to preface, I am very new to Java and Android development, so I apologize for any silly mistakes.

Here's the code to output the JSON:

public static String outputFile(FileOutputStream out, String name, List<String> values)
{
    String outputString = "";
    outputString += "\"meals\":[\n";

    for (int i = 0; i < values.size(); i++)
    {
        outputString += "{\"" + name + "\": \"" + values.get(i) + "\"},\n"; //output: {"name":"value"}, for every element
    }
    outputString = outputString.substring(0, outputString.length()-2); //this takes off the newline char, and the last comma.
    outputString += "\n"; //add the newline character back on.
    outputString += "]";

    Gson g = new Gson();
    String s = g.toJson(outputString);

    try
    {
        out.write(s.getBytes());
        out.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return outputString; //debug only
}

Then later, I'm using this to input the JSON and parse each object in with its respective value:

public static List<String> inputFile(Context context, FileInputStream in, List<String> names)
{
    InputStreamReader inReader = new InputStreamReader(in);
    BufferedReader bufferedReader = new BufferedReader(inReader);
    StringBuilder builder = new StringBuilder();
    String line;
    String tempJson = "";

    List<String> tempList = new ArrayList<>();

    try
    {
        while ((line = bufferedReader.readLine()) != null)
        {
            builder.append(line);
            String readJson = builder.toString();
            Gson readGson = new Gson();
            tempJson = readGson.fromJson(readJson, String.class);
        }
        in.close(); //close the file here?


        JSONObject jobj = new JSONObject(tempJson);

        for (int i = 0; i < names.size(); i++)
        {
            tempList.add(jobj.getString(names.get(i))); //this should add the JSON string stored at every index i in names.
        }

        //debug:
        Toast.makeText(context, tempList.toString(), Toast.LENGTH_LONG).show();

        return tempList;
    }
    catch (Exception e)
    {
        e.printStackTrace();

        //debug:
        Toast.makeText(context, tempList.toString(), Toast.LENGTH_LONG).show();

        return new ArrayList<>(Arrays.asList("File Input Error!")); //return a blank-ish list?
    }
}
}

So I'm sure there's an easier way to do this. Maybe I'm not using gson like I should be? Any help is greatly appreciated.

Upvotes: 0

Views: 541

Answers (2)

NoChinDeluxe
NoChinDeluxe

Reputation: 3444

If you just need to store a list to disk for later use, here is a pretty simple way of doing it.

Let's say you have an ArrayList of Strings you want to store:

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("one");
arrayList.add("two");
arrayList.add("three");

You can easily store these in the SharedPreferences for the app, which are not really user preferences but just key/value slots that are made easily accessible for your use of persistent data. You can't store an ArrayList directly, but you CAN store a Set, so we'll first need to convert our ArrayList to a Serializable Set:

HashSet<String> hashSet = new HashSet<>(arrayList);

Then we get an instance of the app's SharedPreferences and save our new HashSet to disk:

SharedPreferences sharedPreferences = getSharedPreferences("whatever_you_want_to_name_this", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("name_of_the_preference_to_modify", hashSet);
editor.apply(); 

And that's it! When you're ready to retrieve your data, you'll need to first get the HashSet that you saved:

SharedPreferences sharedPreferences = getSharedPreferences("whatever_you_want_to_name_this", MODE_PRIVATE);
HashSet<String> hashSet = (HashSet<String>) sharedPreferences.getStringSet("name_of_the_preference_to_modify", new HashSet<String>());

And simply convert it back to an ArrayList:

ArrayList<String> arrayList = new ArrayList<>(hashSet);

I think it's a pretty simple and clean way to save a List. And you won't have to mess with all the JSON. Hope it helps!

Upvotes: 1

meda
meda

Reputation: 45490

Try this approach:

public void saveObject(Object object) {
    String key = object.getClass().getSimpleName();
    Gson gson = new Gson() ;
    String objectJSON = gson.toJson(object);
    SharedPreferences sharedPreferences = context.getSharedPreferences("Pref name here", context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
    prefsEditor.putString(key, objectJSON);
}

public Object retrieveObject(Class objectClass){
    String key = objectClass.getSimpleName();
    Gson gson = new Gson();
    SharedPreferences sharedPreferences = context.getSharedPreferences("Pref name here", context.MODE_PRIVATE);
    String objectJSON = sharedPreferences.getString(key, "");
    Object object  = gson.fromJson(objectJSON, objectClass);
    return object;
}

The first one converts the object to a json string and save it to shared preferences.

The second one get the string convert it to a json and then return the object

Upvotes: 0

Related Questions