noooobies123
noooobies123

Reputation: 23

How to save a custom Java Object in Android?

Can you help me out. I am trying to save my Java Objects(Customer) in android currently I am following a book in my studies.

This is what I got, I have Customer Object that has a String and UUID. With these I am able to save them successfully through converting it with JSON. My problem is I want to add an ArrayList of Objects which contains(Double, and two strings) for each Customer. How can I save this ArrayList and retrieve it inside that JSON Object when I convert my Customer Object to json.

I researched but can't really understand it well. I found GSON but I am not sure whether this is the one I needed and don't know how to add this library to my project. Another is can I be able to put JSONArray into a JSON object? These are the two potential solutions that I found but not that sure. I'm trying to save this through file not SQLite. Is there anyway?

Here is the code for the Customer class

    public class Customer {

//Constants for JSON
private static final String JSON_ID = "id";
private static final String JSON_NAME = "name";

private String mName;
private UUID mID;
private ArrayList<Item> mItems;

public Customer(){
    mID = UUID.randomUUID();
    mItems = new ArrayList<Item>();
}

//Loading Customer from JSON
public Customer(JSONObject jsonObject) throws JSONException{
    mID = UUID.fromString(jsonObject.getString(JSON_ID));
    if(jsonObject.has(JSON_NAME)){
        mName = jsonObject.getString(JSON_NAME);
    }
}


//JSON converter
public JSONObject toJSON() throws JSONException{
    JSONObject json = new JSONObject();
    json.put(JSON_ID, mID.toString());
    json.put(JSON_NAME,mName);
    if (!mItems.isEmpty()){

    }
    return json;
}


public UUID getmID() {
    return mID;
}

public String getmName() {
    return mName;
}

public void setmName(String mName) {
    this.mName = mName;
}

//Add item debt
public void addDebt(Item i){
    mItems.add(i);
}

//Get List Debt
public ArrayList<Item> getmItems(){
    return mItems;
}

public Item getItem(UUID id){
    for (Item item : mItems){
        if (item.getmItemID().equals(id)){
            return item;
        }
    }
    return null;
}

}

This is for the Item

   public class Item {

private String mItemName;
private Date mDate;
private UUID mItemID;
private double mPrice;


public Item(){
    mDate = new Date();
    mItemID = UUID.randomUUID();
}

public UUID getmItemID() {
    return mItemID;
}

public void setmItemID(UUID mItemID) {
    this.mItemID = mItemID;
}

public String getmItemName() {
    return mItemName;
}

public void setmItemName(String mItemName) {
    this.mItemName = mItemName;
}

public String toString(){
    return mItemName;
}

public Date getmDate() {
    return mDate;
}

public void setmDate(Date mDate) {
    this.mDate = mDate;
}

public double getmPrice() {
    return mPrice;
}

public void setmPrice(double mPrice) {
    this.mPrice = mPrice;
}

}

Upvotes: 0

Views: 4689

Answers (2)

NoSixties
NoSixties

Reputation: 2533

You could do the following to convert your entire object including the ArrayList into json and you can then save this into your SharedPreferences

To do this you need to import the GSON library. Here's how you do that.

if you're using Android Studio

  • Go to your build.gradle file and open it
  • Scroll down until you see dependencies
  • add the following line and synchronize the project(option will apear on top of the screen compile 'com.google.code.gson:gson:2.3.1'

if you're using Eclipse

  • Download the gson jar
  • Right click your project and select properties
  • Select "Java Build Path" on the left, and then the "Libraries" tab. Now, click the "Add External JARS..." button
  • Locate and select the jar file you just downloaded, and then click "Open"
  • Finally click "ok" and you should be able to see it under referenced libraries

Now for the code it would look something like this

SharedPreferences mSettings = getSharedPreferences("YourPreferenceName", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSettings.edit();

GsonBuilder gsonb = new GsonBuilder();
Gson mGson = gsonb.create();

let's say you have 2 methods one for saving your object and one for reading it.

public boolean writeJSON(Customer c, String yourSettingName)
{
   try {
       String writeValue = mGson.toJson(c);
       mEditor.putString(yourSettingName, writeValue);
       mEditor.commit();
       return true;
   }
   catch(Exception e)
   {
       return false;
   }
}

public Customer readJSON(String yourSettingName)
{
   String loadValue = mSettings.getString(yourSettingName, "");
   Customer c = mGson.fromJson(loadValue, Customer.class);
   return c;
}

You then can just call those methods and it will let you know if the writing was successfull and when you call the read it'll return your customer object you saved previously.

hope this helps you out

Upvotes: 3

rymate1234
rymate1234

Reputation: 448

The idea of GSON is that it can convert a JSON string directly into a Java Object. Here's an example of using GSON to parse a JSON string:

Gson gson = new Gson();
Notes notes = gson.fromJson(json.toString(), Notes.class);

This will parse the JSON and convert it into a Notes object.

Converting it back should be as simple as the following, however in my code base I don't use it, so it's untested:

Gson gson = new Gson();
String json = gson.toJson(notes, Notes.class);

Upvotes: 0

Related Questions