Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing JSON data to local database in android

Tags:

android

Okay so, I created an app that retrieves data from my server using JSON. Now I want to store the retrieved data on my phone's local storage/db. How do I do it? I am new in android programming.

This is the JSON that I receive from the server

{"messages":[{"id":"44","issender":0,"content":"CAT1DOG","date":"Jan 01, 1970 07:30 AM","sender":"Administrator","receiver":"User"},{"id":"57","issender":0,"content":"ttt","date":"Jun 30, 2016 03:43 PM","sender":"Administrator","receiver":"User"},{"id":"58","issender":0,"content":"s","date":"Jun 30, 2016 03:43 PM","sender":"Administrator","receiver":"User"},{"id":"82","issender":0,"content":"yeuwu","date":"Jun 30, 2016 04:59 PM","sender":"Administrator","receiver":"User"}],"success":1}

and this is my code to parse JSON

for(int i = 0; i < messages.length(); i++){
                        JSONObject o        = messages.getJSONObject(i);
                        String msgid        = o.getString("id");
                        String message      = o.getString("content");
                        String date         = o.getString("date");
                        String sender       = o.getString("sender");
                        String receiver     = o.getString("receiver");
                        String issender     = o.getString("issender");

                        // TEMP HASHMAP FOR USER
                        HashMap<String, String> msgList = new HashMap<String, String>();

                        // ADDING EACH CHILD NOTE TO HASHMAP => VALUE
                        msgList.put("id", uid);
                        msgList.put("message", message);
                        msgList.put("date", date);
                        msgList.put("name", sender);
                        msgList.put("receivername", receiver);

                        // ADDING USER TO MSGLIST
                        ListOfMsg.add(msgList);
                    }

Thanks in advance for those who will answers. will appreciate it.

like image 277
Akio Avatar asked Jun 30 '16 09:06

Akio


1 Answers

First I need to tell you that this is not the easy way out but for sure it is the correct one.

Next create a new class named Message

public class Message{
  public String issender;
}

When you receive the json :

List<Message> messages= new ArrayList<>();
Gson gson = new Gson();
Message m= gson.fromJson(json.toString(),Message.class);
messages.add(m);

Please be careful that the items in the class should have the name as the items in the json you are trying to receive

Now we are done with this part: Let us add the library for caching: Follow this tutorial and if you need help get back to me: https://guides.codepath.com/android/activeandroid-guide

or you could do the caching using sql old fashioned way

like image 164
Miriana Itani Avatar answered Oct 17 '22 01:10

Miriana Itani