Creating a while loop which insert json data into sqlite (Android) - android

Basically I am trying to insert the JSON objects the app received into the SQLite database. As I named my JSON object in a continuous ID, I want to create a do while loop to count how many objects it received and stop when the maximum object is received.
My codes is following:
mydb.StoreMemberInfo(Integer.valueOf(json.getString(TAG_MEMBER_ID).toString()), json.getString(TAG_MEMBER_NAME), Integer.valueOf(json.getString(TAG_MEMBER_POINT).toString()));
do {
mydb.StoreShopInfo(Integer.valueOf(json.getString(TAG_SHOP_ID + ++shop_ID_counter).toString()), json.getString(TAG_SHOP_NAME + ++shop_name_counter));
}
while(TAG_SHOP_ID + shop_ID_counter != null);
The JSON objects my app is supposed to receive is as following:
{"success":1,"message":"Login successful","member_id":"1","member_name":"Peter","member_point":"1000","shop_ID_1":"1","shop_name_1":"Chatime","shop_ID_2":"2","shop_name_2":"Beard Papa","shop_ID_3":"3","shop_name_3":"CoolBlog","friend_ID_1":"2","friend_name_1":"James","friend_ID_2":"3","friend_name_2":"Mary"}
The loop is supposed to stop once it reached shop_ID_4 but because it does not exist but the code is in a waiting state and does not process the other codes instead. What should I do?

Can be worked on to do what you need I believe. Just copy and pasted from something I did a few months ago.
public List<LocationData> parseLocatonData(String response)
{
String result = response;
mLocationData = new ArrayList<LocationData>();
try {
JSONObject jsonObject = new JSONObject(result);
Boolean status = jsonObject.getBoolean("status");
if (status) {
JSONObject jObject = new JSONObject();
jObject = jsonObject.getJSONObject("results");
Iterator<String> keys = jObject.keys();
while (keys.hasNext()) {
LocationData locationData = new LocationData();
String key = keys.next();
JSONObject innerJObject = jObject.getJSONObject(key);
locationData.setLocationName(innerJObject.getString("cName"));
locationData.setCity(innerJObject.getString("cCity"));
locationData.setAddress(innerJObject.getString("cAddress"));
locationData.setFieldName(innerJObject.getString("cField"));
locationData.setState(innerJObject.getString("cState"));
locationData.setFieldUrl(innerJObject.getString("cWebsite"));
locationData.setZip(innerJObject.getString("cZip"));
mLocationData.add(locationData);
}
return mLocationData;
}
} catch (JSONException e) {
Toast.makeText(mContext, "Error getting Location Info", Toast.LENGTH_SHORT).show();
LogUtils.LOGI(TAG, e.toString());
}
return null;
}
The main thing is the key iterator, lets you walk down the list

Related

Troubles with parsing JSON for android

I'm working on parsing some JSON in my android application, this is the code I started off with:
JSONObject jsonObject = **new JSONObject(result);**
int receivedCount = **jsonObject.getInt("CurrentCount");**
However this is causing it to error (The code that would error is surrounded with asterisks) in Android Studio, I tried using the suggestion feature which asked me if I want "Surround with try/catch" which would cause the app to crash when it launched.
This is the suggested code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
int receivedCount = 0;
try {
receivedCount = jsonObject.getInt("CurrentCount");
} catch (JSONException e) {
e.printStackTrace();
}
This is the JSON I'm trying to pass:
[{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
Thanks in advance!
J_Dadh I think first of all you should look through the documentation on how to use Json Parser which you can find in the following Link https://www.tutorialspoint.com/android/android_json_parser.htm
EXAMPLE JSON
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String YourJsonObject = "JsonString"
JSONObject jsonObj = new JSONObject(YourJsonObject);
JSONArray weather = jsonObj.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject c = weather.getJSONObject(i);
String id = c.getString("id");
String main= c.getString("main");
String description= c.getString("description");
}
as you pasted your JSON you are using [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
-If we analyze this JSON,This JSON contains a JSON ARRAY [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
having 3 JSON Objects{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}
-But when you are going to parse this JSON, you are accepting it as jsonObject = new JSONObject(result),but you should accept it asJSONArray jsonArray=new JSONArray(result);
and then you iterate a loop(e.g,for loop) on this jsonArray,accepting JSONObjects 1 by 1,then getting the values from the each JSONObject 1 by 1.
-1 more mistake in your JSON is that you are sending the strings as "5" but accepting it as getInt() that's not fair,you should send int to accept it as intas 5 (without double qoutes)
So you final JSON and code like this(as below)
JSON
[{"CurrentCount":5},{"CurrentCount":0},{"CurrentCount":1002}]
Code to Use this JSON
JSONOArray jsonArray = null;
try{
jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray[i];
receivedCount=jsonObject.getInt("CurrentCount");
}
}catch(JSONException e) {
e.printStackTrace();
}

How to process Json array in android without square bracket

Raw Json Data
[
{
"worker.1":{
"last_share":1443639029,
"score":"3722204.62578",
"alive":true,
"shares":1124332,
"hashrate":1047253
},
"worker.2":{
"last_share":1443639029,
"score":"3794755.69049",
"alive":true,
"shares":1069332,
"hashrate":1012070
},
"worker.3":{
"last_share":1440778690,
"score":"0.0",
"alive":false,
"shares":0,
"hashrate":0
},
"worker.4":{
"last_share":1443638222,
"score":"940190.67723",
"alive":true,
"shares":449932,
"hashrate":404772
}
"worker.nth":{
"last_share":1443638222,
"score":"940190.67723",
"alive":true,
"shares":449932,
"hashrate":404772
}
}
]
From the main question I have been able to narrow down the results and managed to add the Square bracket as well. Now i have a Json Array above so could someone advise me how can i process this Json array. Also note that it can end up being 1000 workers.
Please please help I have been breaking my head for 2 days on this,
Also note that the actual Json data is complex and 1000's of entries,
The json data included is just an overview.
Edit: Code that I ma using to process the above Json
try{
JSONArray jArray = new JSONArray(jsonObj.getJSONObject("workers"));
if(jArray.length() == 0){
Log.d("Json Err", "JSON string has no entries");
return null;
}
JSONObject jObject = jArray.getJSONObject(0);
// To get one specific element:
JSONObject worker1 = jObject.getJSONObject("worker.1");
JSONObject worker2 = jObject.getJSONObject("worker.2");
// Iterate over all elements
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next(); // "worker.1", etc
if ( jObject.get(key) instanceof JSONObject ) {
JSONObject entry = jObject.getJSONObject(key);
// Do something with your entry here like:
String score = entry.optString("score", "");
Boolean alive = entry.optBoolean("alive", false);
Integer shares = entry.optInt("shares", 0);
Log.d("Json Success", score );
}
}
} catch (JSONException e){
Log.e("Json Err", "Failure converting JSON String", e);
}
Error that I am getting:
E2570 (5:10 PM):
org.json.JSONException: Value {"worker.1":{"last_share":1443694390,"score":"15.6018529132","alive":true,"shares":59880,"hashrate":0},"worker.2":{"last_share":1443694180,"score":"2.97304689833","alive":true,"shares":2048,"hashrate":0},"worker.3":{"last_share":1440778690,"score":"0.0","alive":false,"shares":0,"hashrate":0},"ivonme.ant4":{"last_share":1443701343,"score":"8688.78118933","alive":true,"shares":203088,"hashrate":78633}}
of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java)
at org.json.JSONArray.(JSONArray.java)
at org.json.JSONArray.(JSONArray.java)
So you have...
{ //JSONObject
"worker.1":{
"last_share":1443639029,
"score":"3722204.62578",
"alive":true,
"shares":1124332,
"hashrate":1047253
},
"worker.2":{
"last_share":1443639029,
"score":"3794755.69049",
"alive":true,
"shares":1069332,
"hashrate":1012070
} //,...
}
To get all your workers you have to...
try{
JSONObject jObject = new JSONObject(yourStringFromYourQuestion);
// To get one specific element:
JSONObject worker1 = jObject.getJSONObject("worker.1");
JSONObject worker2 = jObject.getJSONObject("worker.2");
// Iterate over all elements
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next(); // "worker.1", etc
if ( jObject.get(key) instanceof JSONObject ) {
JSONObject entry = jObject.getJSONObject(key);
// Do something with your entry here like:
String score = entry.optString("score", "");
Boolean alive = entry.optBoolean("alive", false);
Integer shares = entry.optInteger("shares", 0);
}
}
} catch (JSONException e){
Log.e(LOG_TAG, "Failure converting JSON String", e);
}
Try this:
JSONArray jArray=jsonObj.getJSONArray("workers");
instead of
JSONArray jArray = new JSONArray(jsonObj.getJSONObject("workers"));
The error is because of you are getting json array as object. I think so.

How to parse JSON with any key on android?

I want to parse JSON with any key on Android.
JSON data consists of any key, array or values.
Here are JSON data and my working code.
I want to put JSON data into a class by using JSON parsing.
JSON data :
{
"d520c8c17c8e":
{ "id":"25689123",
"number":"0e31b1994"
},
"d183c6e9913d":
{
"id":"25689123",
"number":"0e31b1994"
},
"content":"8090986565488990",
"text":"hello",
"status":"ok"
}
My code :
public static MyInfo getMyInfo(JSONObject json) {
MyInfo info = new MyInfo();
if (json == null)
return null;
try {
info.setContent(json.getString("content"));
info.setText(json.getString("text"));
info.setStatus(json.getString("status"));
ArrayList<MyList> mylists = new ArrayList<MyList>();
JSONArray panels = json.getJSONArray(????????????);
for(int i=0;i < panels.length();i++){
JSONObject e2 = panels.getJSONObject(i);
MyList info_list = new MyList();
info_list.setId(e2.getString("id"));
info_list.setNumber(e2.getString("number"));
info_list.add(info_answer);
}
info.setList(info_list);
} catch (JSONException e) {
}
return info;
}
please help me.
Yes this is possible.
Put the JSON you receive in a JSONObject. You can loop trough the keys and get the values out of it.
Example:
//Create json object from string
JSONObject newJson = new JSONObject(json);
// Get keys from json
Iterator<String> panelKeys = newJson.keys();
while(panelKeys.hasNext()) {
JSONObject panel = newJson.getJSONObject(panelKeys.next()); // get key from list
String id = panel.getString("id");
String number = panel.getString("number");
}
I hope this is what you were looking for

How to print the msg_content in textview android json here?

{
"status": "ERROR",
"msg_content": "Your old password was entered incorrectly. Please enter it again.",
"code": "400",
"msg_title": "Sorry. Error in processing your request"
}
if (str.startsWith("Bad Request"))
{
textview.setText(" ");
}
How to print inside the textview to display the msg_content using json
You need to parse json using JSON object.
JSONObject obj = new JSONObject(str);
Then find string from JSON object whatever you want.
if (obj.has("msg_content")) {
String value = obj.getString("msg_content");
textview.settext(value);
}
You will need to create a JSONObject and pass it the string as a parameter.
JSONObject obj = new JSONObject(str);
Then to find a key in the JSONObject just call, always check if the JSONObject has that key before trying to retrieve it.
if (obj.has("status"){
String status = obj.getString("status");
}
if (obj.has("msg_content"){
String content = obj.getString("msg_content");
textview.setText(content);
}
JsonReader is implemented in API 11. If you want to use it in GingerBread or below try this
Use following Code for extracting Information from JSON Objects:
try {
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if(key.equals("msg_content"))
textView.setText(jsonObject.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, if u have JSON as String, u can populate an object using following code:
try {
jsonObject = new JSONObject(theJsonString);
} catch (JSONException e1) {
e1.printStackTrace();
}
I'm quite new to JSON but I would create a JsonReader and parse the JSON as per here

Android Escaping special characters while parsing JSON

I am using following piece of code for parsing JSON in my android application.
String result = postHttpResponse(uri, json);
try {
JSONObject jsonResult = new JSONObject(result);
boolean authenticated = jsonResult.getBoolean("Authenticated");
if(authenticated){
user = new User();
JSONObject jsonUser = (JSONObject) jsonResult.get("User");
user.setName(jsonUser.getString("Name"));
user.setUserId(jsonUser.getString("UserId"));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
jsonUser.getString("UserId") returns the value "corp\\ns0017" instead of "corp\ns0017". Actualy it is escaping the character "\" in the string with one more "\". but at the time of parsing i want to remove the extra "\". How can i achieve it?

Categories

Resources