Storing JSON data to local database in android - 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.

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

You can do this in two ways:
Use the new extension for json in sqite. The information you might need is available on this page https://www.sqlite.org/json1.html . Still I would suggest to do a little bit more of research on this, as it is new and I have not used it yet.
You can convert your json to string and insert it to the database.
String jsontostring = jsonObject.toString();

Related

create two tables using the same class in room database

I'm using Room as the database for the app. I`m fetching data from the server using Retrofit. the scenario is i have a class called Photo and annotated with Entity to be used by room, and im using this class to map the response of the API using retroft. i need to create two tables using the same class for example: latest_photos table and popular_photos table. How can i achieve this.
I don`t want to create a new class and make it extends from the other
I have an idea of using a single table through inserting a new column
that indicates weather the photo is popular or latest but i dont know
how to implement it efficientlly.
public void insertPhotos(final List photos) {
ioExecutor.execute(new Runnable() {
#Override
public void run() {
photoDao.bulkInsert(updateList(photos));
}
});
}
here im inserting list of photos (consists of 20 photo object). how can i add a new field to every photo object.
i`ve tried to use for loop but it takes noticeable time as i dont receive only 20 items but im paginating through the web server.
is there any way to add a new value to retrofit response and mapping
it to the Photo class
Ive solved the problem,now im dealing with only one table. i`ve inserted a new column that indicates weather the photo is popular or latest but the problem is the server is not returning any useful data to fill this column. so the only solution is to modify the json response before mapping to to my entity. so making retrofit call returning type to be ResponseBody to return json string itself and not to map it, so i can add a property to json response then i map it with the newly add property.
private void processData(Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray hits = jsonObject.getJSONArray("hits");
List<Photo> photos = new ArrayList<>();
for (int i = 0; i < hits.length(); i++) {
JSONObject photoJSONObject = hits.getJSONObject(i);
photoJSONObject.put("order", order); // add new property
String json = photoJSONObject.toString();
Gson gson = new Gson();
Photo photo = gson.fromJson(json, Photo.class);
photos.add(photo);
}

Json - how to parse a url in Android

I want to parse json from a url and use the json data with a listview.
I also want to only list the score and the name, but I have no idea how. Thanks.
{
"level":[
{
"id":1,
"server":[
{"score":33,"name":"Car"},
{"score":72,"name":"Bus"},
]
}
]
}
Do you know how to retrieve the data?
After you retrieve the data, parsing it is very simple. To get each individual item with its attributes I would use the following code:
String responseFromUrl;
JSONObject JSONResponse = new JSONObject(responseFromURL);
JSONArray level = JSONResponse.getJSONArray("level");
//The following loop goes through each object in "level". This is nessecary if there are multiple objects in "level".
for(int i=0; i<level.length(); i++){
JSONObject object = level.get(i);
int id = object.getInteger("id");
JSONArray server = object.getJSONArray("server");
//This second loop gets the score and name for each object in "server"
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.get(i);
int score = serverObject.getInteger("score");
String name = serverObject.getString("name");
}
}
Obviously replace "responseFromUrl" with the JSON response from the url in string format. If you don't know why I used JSONObject, JSONArray, String, Integer, etc., or are just confused about this, Udacity has a good course for making http connections and parsing JSON responses from APIs.
Link to Udacity Course
You can use the gson library to convert json to an java object
Download the latest jar and import into your project, currently you can download the latest at this link:
https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.1/gson-2.8.1.jar
After, this will help you:
https://stackoverflow.com/a/23071080/4508758
Hugs!

Android mapping does not work

Hi I have to send map to server and the server will get information from that. I'm having two piece of code for mapping first is(name and key are variables)
String user = "{ 'id':" + userId +","+"'response':{'id':"+userId+",'access':"+"'"+name+":"+key+"'"+"}}";
Map<String, Object> userMap = new Gson().fromJson(user, new TypeToken<HashMap<String, Object>>() {}.getType());
Set<String> keys = userMap.keySet();
for (String i:keys){
Log.d("user",i+" "+userMap.get(i));
}
here I concat required string and parse it and then convert it into map . This piece of code had worked. And my second set of code is
String user1 = "{id="+userId+", access="+""+name+":"+key+""+"}";
Map<String,Object> tuc = new HashMap<>();
tuc.put("id",userId);
tuc.put("access","");
Set<String> key = tuc.keySet();
for (String i:key){
Log.d("user",i+" "+tuc.get(i));
}
this code is not working,that mean server is not accepting this code. But when I print key value pairs the results are same for both codes. My lead doesn't like to use first piece of code. Can any one explain why,I'm struck in this for past two days. Thank you.Sorry for my poor English.
In Java, HashMap can only accept <key, value> pairs. It is not like Json, which in your case is in {key1:value1, key2:value2, ...} format.
Therefore, if you are intended to convert its format from {key1:value1, key2:value2, ...} into <key, value>. My suggestion is combining value2, value3, ... into an object (like String) as the value and value1 as the key.
See https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html for more details.

Iterate through MySql to ListView in Android

I wrote an Android App that pulls data from a MySql Database on a remote web server. The information is parsed and displayed in a listview. The listview also displays images which could slow down the activity. I was wondering how I could only display items 0-9, then when you click a button it will display 10-19, and so on. I can do it in VB using "do until" but as far as android/java, I am kind of lost. Any help would be appreciated.
Below is the class where I need to implement it. I believe I would need to add an Integer to keep count and implement a form of "DO UNTIL" before I loop through the array and add a count to the "Integer" but I am not sure how to go about it here.
class ProductQuery extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... file_url) {
// TODO Auto-generated method stub
try{
//Settings to send to PHP
List<NameValuePair> settings = new ArrayList<NameValuePair>();
//Adding Search Criteria(Keyword) to settings
settings.add(new BasicNameValuePair("product", product));
//Getting JSON result from request
JSONObject jObject = jParser.makeHttpRequest(url_to_php, "GET", settings);
//Display JSON in LogCat
Log.d("Product Search", jObject.toString());
//Get Result
int result = jObject.getInt(KEY_RESULT);
//If Result Equals 1 then
if(result==1){
//Getting the KEY_PRODUCTS
products = jObject.getJSONArray(KEY_PRODUCTS);
//Loop through Array
for(int i = 0; i < products.length();i++){
JSONObject x = products.getJSONObject(i);
String proPid = x.getString(KEY_PRODID);
String name = x.getString(KEY_NAME);
String price = x.getString(KEY_PRICE);
String desc = x.getString(KEY_DESCRIPTION);
String img = x.getString(KEY_IMAGE);
// creating new HashMap
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put(KEY_PRODID, proPid);
hmap.put(KEY_NAME, name);
hmap.put(KEY_PRICE, price);
hmap.put(KEY_DESCRIPTION, desc);
hmap.put(KEY_IMAGE, img);
//Hash to ArrayList
myproducts.add(hmap);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Instead of making pagination in the app, you should leave this to the server.
On your server, you should change the way you receive requests, so that when you call your server, you post a start index to fetch rows from and how many rows you want fetched for each request.
So the url to the server could look like this:
http://example.com/myjsonrequest.php?startindex=10&numofrows=10
In your PHP select statement on your server, you change it so it selects only the rows you need, like so:
SELECT * FROM my_table LIMIT $startindex, $numofrows;
Remember to check for SQL injections of course.
This way, you only fetch the data you actually want instead of fetching all the data in one go. Remember, your app is on a mobile OS, with a somewhat volatile internet connection sometimes, so if the data you're returning is growing, it wouldn't be nice from a user-perspective to sit and wait for all the data to load, especially when some of it, isn't needed yet.
For instance if you get let's say 1000 rows of data returned, that would take a while to fetch over a mobile internet connection.
After you receive the JSonObject with only a limited amount of entries, you can now parse it without keeping track of how many entries are returned.
Inside your Android app, all you need to keep track of is what index in the database, the user has seen so far and then increment this counter every time the user fetches a new page.

How is this JSON string supposed to be parsed to get the different fields

I have this JSON string that I am recieving after I make a purchase from the playstore and I am apparently missing something in my code when I am trying to parse it.
PurchaseInfo:{"orderId":"12999763165555505758.1317333586444405",
"packageName":"com.mypkgname.myapp",
"productId":"monthly_purchase_01",
"purchaseTime":1357456489000,
"purchaseState":0,
"purchaseToken":"yrynypfkdncvhlxdbypysvwz.AO-J1OxFkndfqkClAqbbYAOApkMgTG4VX9Ef0uNP0FIs9-xGrXivkbx3FNMA2yNU12K_sbvRGFcknVBTfisI-uZawCXLGlMX4v4Zw8GFOmS0Q6PIbiITTGqn5h1QbEB4Rv84sXdUJHP3B_UQfujZN7ADi9bm_N4_iA"}
Here is the snippet of code I am using it to attempt the parsing
try {
JSONObject j1 = new JSONObject(tester1);
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
int count = mPurchInfo.length();
final String[] purchInfo = new String[count];
JSONObject q1 = mPurchInfo.getJSONObject(0);
purchInfo[0] = q1.getString("orderId");
purchInfo[1] = q1.getString("packageName");
purchInfo[2] = q1.getString("productId");
purchInfo[3] = q1.getString("purchaseTime");
purchInfo[4] = q1.getString("purchaseState");
purchInfo[5] = q1.getString("purchaseToken");
orderID=purchInfo[0];
} catch (JSONException e) {
Log.e("Error","Yes");
}
I am catching the an error as I see this last log statement in my log but I am still trying to learn the parsing JSON Strings
I hope I am at least close
Ideally I would like to have Strings set to all the values in the JSON String
orderID = ??
packageName = ??
etc.
Thanks
I have this JSON string that I am recieving after I make a purchase from the playstore
If that's really what you get back, you need to contact them and tell them to fix their API; that string is not valid JSON. There are two problems with it:
A JSON document must have an object or array as the top-level item. The string as quoted is missing a { at the beginning and a } at the end.
All keys in JSON must be in double quotes. The first one, PurchaseInfo, is not.
Also, your code is doing this:
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
...but if it were valid JSON, PurchaseInfo wouldn't be an array, it'd be an object.
Looking at it, if you remove the PurchaseInfo: at the beginning, it's valid. Once you've removed that, this line:
JSONObject j1 = new JSONObject(tester1);
...will give you an object from which you can query information:
String orderId = j1.getString("orderId");

Categories

Resources