How to store nested JSONArray value in SQLite Database?
getting value from JSONArray and It is also stored it in ArrayList both working fine.
My JSONArray List is,
{
"resultFlag": true,
"successMessage": "Data Received",
"Questions": [
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "64",
"question": "Which section of the Indian IT act 2008 deals with cyber stalking?",
"answer": [
{
"ansID": "261",
"ans": "Section 24",
"correct": "0"
},
{
"ansID": "262",
"ans": "Section 72",
"correct": "1"
},
{
"ansID": "263",
"ans": "Section 27",
"correct": "0"
},
{
"ansID": "264",
"ans": "Section 42",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "66",
"question": "What should you do when your online friends want to meet you?",
"answer": [
{
"ansID": "269",
"ans": "Go ahead, make plans and meet them wherever and whenever they want",
"correct": "0"
},
{
"ansID": "270",
"ans": "Inform your parents and make sure that you meet where there are a lot of people around",
"correct": "1"
},
{
"ansID": "271",
"ans": "Never meet anyone in person that you met online, it’s just not safe",
"correct": "0"
},
{
"ansID": "272",
"ans": "Ignore their request",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "70",
"question": "te",
"answer": [
{
"ansID": "285",
"ans": "tr",
"correct": "1"
},
{
"ansID": "286",
"ans": "tr",
"correct": "0"
},
{
"ansID": "287",
"ans": "tr",
"correct": "0"
},
{
"ansID": "288",
"ans": "tr",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "91",
"question": "When A Player Deliberately Harasses Other Players Within An Online Game, it is known as ",
"answer": [
{
"ansID": "369",
"ans": "Griefing",
"correct": "1"
},
{
"ansID": "370",
"ans": "Spamming",
"correct": "0"
},
{
"ansID": "371",
"ans": "Scamming",
"correct": "0"
},
{
"ansID": "372",
"ans": "Grooming",
"correct": "0"
}
]
},
{
"questionType": "Trivia",
"timeRequired": "10",
"questionID": "153",
"question": "Which of the following is not a communication channel for a Phisher?",
"answer": [
{
"ansID": "617",
"ans": "Email Account",
"correct": "0"
},
{
"ansID": "618",
"ans": "Instant Messaging",
"correct": "0"
},
{
"ansID": "619",
"ans": "Social Media Account",
"correct": "0"
},
{
"ansID": "620",
"ans": "Search Engine",
"correct": "1"
}
]
}
]
}
I get Successfully response from Server but not store in ArrayList answer value for related question.
My Java Code is,
//Question
static String[] question_id;
static String[] question_type;
static String[] time_required;
static String[] question;
//Answer
static String[] answer_id;
static String[] answer;
static String[] correct;
//Question Array List
static List<String> arr_question_id = new ArrayList<String>();
static List<String> arr_question_type = new ArrayList<String>();
static List<String> arr_time_required = new ArrayList<String>();
static List<String> arr_question = new ArrayList<String>();
//Answer Array List
static List<String> arr_answer_id = new ArrayList<String>();
static List<String> arr_answer = new ArrayList<String>();
static List<String> arr_correct = new ArrayList<String>();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
Url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
Boolean resultFlag = response.getBoolean("resultFlag");
if (resultFlag == true) {
String success = response.getString("successMessage");
JSONArray json_array_question = response.getJSONArray("Questions");
question_type = new String[json_array_question.length()];
time_required = new String[json_array_question.length()];
question_id = new String[json_array_question.length()];
question = new String[json_array_question.length()];
for (int i = 0; i < json_array_question.length(); i++) {
JSONObject json_object_question = json_array_question.getJSONObject(i);
question_type[i] = json_object_question.getString("questionType");
time_required[i] = json_object_question.getString("timeRequired");
question_id[i] = json_object_question.getString("questionID");
question[i] = json_object_question.getString("question");
JSONArray json_array_answer = json_object_question.getJSONArray("answer");
answer_id = new String[json_array_answer.length()];
answer = new String[json_array_answer.length()];
correct = new String[json_array_answer.length()];
for (int j = 0; j < json_array_answer.length(); j++) {
JSONObject json_object_answer = json_array_answer.getJSONObject(j);
answer_id[j] = json_object_answer.getString("ansID");
answer[j] = json_object_answer.getString("ans");
correct[j] = json_object_answer.getString("correct");
arr_answer_id.add(answer_id[j]);
arr_answer.add(answer[j]);
arr_correct.add(correct[j]);
}
arr_question_type.add(question_type[i]);
arr_time_required.add(time_required[i]);
arr_question_id.add(question_id[i]);
arr_question.add(question[i]);
}
*for (int i = 0; i < arr_question_id.size(); i++) {
item_solo_trivia.setQuestionType(arr_question_type.get(i));
item_solo_trivia.setTimeRequired(arr_time_required.get(i));
item_solo_trivia.setQuestionId(arr_question_id.get(i));
item_solo_trivia.setQuestion(arr_question.get(i));
for (j = 0; j < arr_answer_id.size(); j++) {
item_solo_trivia.setAnswerId(arr_answer_id.get(j));
item_solo_trivia.setAnswer(arr_answer.get(j));
item_solo_trivia.setCorrect(arr_correct.get(j));
}
}*
} else if (resultFlag == false) {
String error = response.getString("errorMessage");
Toast.makeText(activity.getApplicationContext(), error, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(activity,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(activity,
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
Problem with This code, How to Resolve it?
for (int i = 0; i < arr_question_id.size(); i++) {
item_solo_trivia.setQuestionType(arr_question_type.get(i));
item_solo_trivia.setTimeRequired(arr_time_required.get(i));
item_solo_trivia.setQuestionId(arr_question_id.get(i));
item_solo_trivia.setQuestion(arr_question.get(i));
for (j = 0; j < arr_answer_id.size(); j++) {
item_solo_trivia.setAnswerId(arr_answer_id.get(j));
item_solo_trivia.setAnswer(arr_answer.get(j));
item_solo_trivia.setCorrect(arr_correct.get(j));
}
}
And Table is,
//Create Table
public static final String CREATE = "CREATE TABLE IF NOT EXISTS "
+ TABLE
+ " ( "
+ KEY_ID
+ "INTEGER AUTOINCREMENT,"
+ KEY_USER_ID
+ " text not null , "
+ KEY_QUESTION_TYPE
+ " text not null , "
+ KEY_QUESTION_ID
+ " text not null , "
+ KEY_QUESTION
+ " text not null , "
+ KEY_ANSWER_ID_1
+ " text not null , "
+ KEY_ANSWER_ID_2
+ " text not null , "
+ KEY_ANSWER_ID_3
+ " text not null , "
+ KEY_ANSWER_ID_4
+ " text not null , "
+ KEY_ANSWER_1
+ " text not null , "
+ KEY_ANSWER_2
+ " text not null , "
+ KEY_ANSWER_3
+ " text not null , "
+ KEY_ANSWER_4
+ " text not null , "
+ KEY_CORRECT_1
+ " text not null , "
+ KEY_CORRECT_2
+ " text not null , "
+ KEY_CORRECT_3
+ " text not null , "
+ KEY_CORRECT_4 + " text not null" + ");";
How to store Answer list into related Question in SqliteDatabase?
Please Help me and Suggest me.
Thanks.
Related
I'm trying to get the item name, brand name and total carbohydrate value out of the following JSON Array but am having problems with accessing the the individual values within the "fields" section. Anyone with any pointers to retrieve this info?
{
"total_hits": 49127,
"max_score": 11.919899,
"hits": [
{
"_index": "f762ef22-e660-434f-9071-a10ea6691c27",
"_type": "item",
"_id": "513fceb375b8dbbc21000022",
"_score": 11.919899,
"fields": {
"item_id": "513fceb375b8dbbc21000022",
"item_name": "Cheese, cheddar - 1 cup, diced",
"brand_name": "USDA",
"nf_total_carbohydrate": 4.08,
"nf_serving_size_qty": 1,
"nf_serving_size_unit": "serving"
}
},
{
"_index": "f762ef22-e660-434f-9071-a10ea6691c27",
"_type": "item",
"_id": "513fceb375b8dbbc21000021",
"_score": 11.788424,
"fields": {
"item_id": "513fceb375b8dbbc21000021",
"item_name": "Cheese, cheddar - 1 cup, melted",
"brand_name": "USDA",
"nf_total_carbohydrate": 7.54,
"nf_serving_size_qty": 1,
"nf_serving_size_unit": "serving"
}
/* sorry for some reason i can't get the formatting right but the "hits" is a parent of the whole highlighted code section*/
Try this:
try {
JSONObject object = new JSONObject(json);
JSONArray hits = object.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject fields = hits.getJSONObject(i).getJSONObject("fields");
String itemName = fields.getString("item_name");
String brandName = fields.getString("brand_name");
double carbohydrate = fields.getDouble("nf_total_carbohydrate");
Log.d("HitTag", itemName+" "+brandName+" "+carbohydrate);
}
} catch (JSONException e) {
e.printStackTrace();
}
I assume that you have this json:
{
"total_hits": 49127,
"max_score": 11.919899,
"hits": [
{
"_index": "f762ef22-e660-434f-9071-a10ea6691c27",
"_type": "item",
"_id": "513fceb375b8dbbc21000022",
"_score": 11.919899,
"fields": {
"item_id": "513fceb375b8dbbc21000022",
"item_name": "Cheese, cheddar - 1 cup, diced",
"brand_name": "USDA",
"nf_total_carbohydrate": 4.08,
"nf_serving_size_qty": 1,
"nf_serving_size_unit": "serving"
}
},
{
"_index": "f762ef22-e660-434f-9071-a10ea6691c27",
"_type": "item",
"_id": "513fceb375b8dbbc21000021",
"_score": 11.788424,
"fields": {
"item_id": "513fceb375b8dbbc21000021",
"item_name": "Cheese, cheddar - 1 cup, melted",
"brand_name": "USDA",
"nf_total_carbohydrate": 7.54,
"nf_serving_size_qty": 1,
"nf_serving_size_unit": "serving"
}
}
]
}
Here is the fully working code. Try this:
// Your JSON string
String jsonStr = "{\n" +
" \"total_hits\": 49127,\n" +
" \"max_score\": 11.919899,\n" +
" \"hits\": [\n" +
" {\n" +
" \"_index\": \"f762ef22-e660-434f-9071-a10ea6691c27\",\n" +
" \"_type\": \"item\",\n" +
" \"_id\": \"513fceb375b8dbbc21000022\",\n" +
" \"_score\": 11.919899,\n" +
" \"fields\": {\n" +
" \"item_id\": \"513fceb375b8dbbc21000022\",\n" +
" \"item_name\": \"Cheese, cheddar - 1 cup, diced\",\n" +
" \"brand_name\": \"USDA\",\n" +
" \"nf_total_carbohydrate\": 4.08,\n" +
" \"nf_serving_size_qty\": 1,\n" +
" \"nf_serving_size_unit\": \"serving\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"_index\": \"f762ef22-e660-434f-9071-a10ea6691c27\",\n" +
" \"_type\": \"item\",\n" +
" \"_id\": \"513fceb375b8dbbc21000021\",\n" +
" \"_score\": 11.788424,\n" +
" \"fields\": {\n" +
" \"item_id\": \"513fceb375b8dbbc21000021\",\n" +
" \"item_name\": \"Cheese, cheddar - 1 cup, melted\",\n" +
" \"brand_name\": \"USDA\",\n" +
" \"nf_total_carbohydrate\": 7.54,\n" +
" \"nf_serving_size_qty\": 1,\n" +
" \"nf_serving_size_unit\": \"serving\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray jsonArrayHits = jsonObject.getJSONArray("hits");
// Get all jsonObject from jsonArray
for (int i = 0; i < jsonArrayHits.length(); i++)
{
JSONObject jsonObjectFields = jsonArrayHits.getJSONObject(i).getJSONObject("fields");
String itemName = null, brandName = null;
double totalCarbohydrate = 0.0;
// Item name
if (jsonObjectFields.has("item_name") && !jsonObjectFields.isNull("item_name")) {
itemName = jsonObjectFields.getString("item_name");
}
// Brand name
if (jsonObjectFields.has("brand_name") && !jsonObjectFields.isNull("brand_name")) {
brandName = jsonObjectFields.getString("brand_name");
}
// Total carbohydrate
if (jsonObjectFields.has("nf_total_carbohydrate") && !jsonObjectFields.isNull("nf_total_carbohydrate")) {
totalCarbohydrate = jsonObjectFields.getDouble("nf_total_carbohydrate");
}
Log.d("SUCCESS", "JSON Object: " + "\nItem Name: " + itemName
+ "\nBrand Name: " + brandName
+ "\nTotal carbohydrate: " + totalCarbohydrate);
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
OUTPUT LOG:
D/SUCCESS: JSON Object:
Item Name: Cheese, cheddar - 1 cup, diced
Brand Name: USDA
Total carbohydrate: 4.08
D/SUCCESS: JSON Object:
Item Name: Cheese, cheddar - 1 cup, melted
Brand Name: USDA
Total carbohydrate: 7.54
Hope this will help~
I am parsing the following json response but there is some problem in parsing,the code I'm trying is not parsing and I am not getting any exception or response.
The code that I had applied to parse it is:
ArrayList<Model_BarcodeDetail> DownloadBarcode(String api_token) {
ArrayList<Model_BarcodeDetail> barcodeList = new ArrayList<Model_BarcodeDetail>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(Utility.BASE_URL
+ "?q=webservice/barcode_list&token=" + api_token +"&page="+"1"
+ "&return=json");
String url = Utility.BASE_URL
+ "?q=webservice/barcode_list&token=" + api_token +"&page="+"1"
+ "&return=json";
System.out.println("======url::"+url);
String result = "";
ArrayList<Model_BarcodeDetail> group_list = null;
ArrayList<Model_BarcodeList_Child> child_list = null;
try {
group_list = new ArrayList<Model_BarcodeDetail>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject root = new JSONObject(result);
JSONObject obj = root.getJSONObject("");
System.out.println("====objjjj: "+obj.toString());
JSONArray arraylist=obj.names();
for (int i = 0; i < arraylist.length(); i++) {
child_list = new ArrayList<Model_BarcodeList_Child>();
JSONObject jsonObj = arraylist.getJSONObject(i);
System.out.println("---json" + jsonObj);
Model_BarcodeDetail data = new Model_BarcodeDetail();
data.setReference((jsonObj.getString("ref")));
System.out.println("======refinprsing--"+data.getReference());
// data.setName((jsonObj.getString("name")));
// data.setDescription((jsonObj.getString("desc")));
// data.setPrice((jsonObj.getString("price")));
// data.setTotal(data.getPrice().trim());
// data.setFixedTotal(data.getPrice().trim());
JSONArray obj2 = jsonObj.getJSONArray("barcodes");
for (int j = 0; j < obj2.length(); j++) {
JSONObject json = obj2.getJSONObject(j);
System.out.println("---json" + json);
Model_BarcodeList_Child data2 = new Model_BarcodeList_Child();
data2.setBarcode((json.getString("barcode")));
System.out.println("=======barcodeinparsing: "+data2.getBarcode());
data2.setColor((json.getString("color")));
data2.setSize((json.getString("size")));
data2.setPrice(json.getString("price"));
data2.setStock(json.getString("stock"));
data2.setAlis_code(json.getString("alias_code"));
child_list.add(data2);
}
data.setChildItems(child_list);
group_list.add(data);
}
for (int k = 0; k < group_list.size(); k++) {
System.out.println("-----==data itemref "
+ group_list.get(k).getReference());
for (int y = 0; y < group_list.get(k).getChildItems().size(); y++) {
System.out.println("-----====data color "
+ group_list.get(k).getChildItems().get(y)
.getColor());
}
}
} catch (Exception e) {
Log.i("Exception in DownloadBarcodechanges method: ", e.getMessage());
return null;
}
return group_list;
}
Here is the json:
{
"000002": {
"ref": "000002",
"barcodes": [
{
"barcode": "000002014001",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "S",
"stock": "0"
},
{
"barcode": "000002014002",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "M",
"stock": "2"
},
{
"barcode": "000002014003",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "L",
"stock": "1"
},
{
"barcode": "000002014004",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "XL",
"stock": "0"
},
{
"barcode": "000002014005",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "XXL",
"stock": "1"
},
{
"barcode": "000002014006",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "13.50",
"size": "2XL",
"stock": "3"
},
{
"barcode": "000002014007",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "13.50",
"size": "3XL",
"stock": "5"
},
{
"barcode": "000002014008",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "13.50",
"size": "4XL",
"stock": "6"
},
{
"barcode": "000002014009",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "13.50",
"size": "5XL",
"stock": "5"
},
{
"barcode": "000002014010",
"path": null,
"alias_code": null,
"color": "GREY",
"price": "10.50",
"size": "6XL",
"stock": "2"
}
]
},
"000012": {
"ref": "000012",
"barcodes": [
{
"barcode": "000012030001",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "S",
"stock": "1"
},
{
"barcode": "000012030002",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "M",
"stock": "3"
},
{
"barcode": "000012030003",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "L",
"stock": "4"
},
{
"barcode": "000012030004",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "XL",
"stock": "2"
},
{
"barcode": "000012030005",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "XXL",
"stock": "0"
},
{
"barcode": "000012030006",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "2XL",
"stock": "0"
},
{
"barcode": "000012030007",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "3XL",
"stock": "0"
},
{
"barcode": "000012030008",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "4XL",
"stock": "0"
},
{
"barcode": "000012030009",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "5XL",
"stock": "0"
},
{
"barcode": "000012030010",
"path": null,
"alias_code": null,
"color": "BLUE",
"price": "19.99",
"size": "6XL",
"stock": "0"
}
]
},
"pager": {
"current_page": 1,
"start": 0,
"limit": 50,
"total": "354",
"pages": 8
}
}
According to your json Response do parsing like below
JSONObject root = new JSONObject(result);
JSONArray array = root.getJSONArray("array");
String boolean = root.getString("boolean");
String null= root.getString("null");
String number= root.getString("number");
String string = root.getString("string");
JSONArray array_1 = root.getJSONArray("object");
first check your result is not getting null ? please check log.
Based on the json provided change this:
JSONObject root = new JSONObject(result);
JSONObject obj = root.getJSONObject("");
System.out.println("====objjjj: "+obj.toString());
JSONArray arraylist=obj.names();
To this:
JSONObject root = new JSONObject(result);
JSONArray arraylist= root.names();
for (int i = 0; i < arraylist.length(); i++) {
child_list = new ArrayList<Model_BarcodeList_Child>();
JSONObject jsonObj = root.getJSONObject(arrayList.getString(i));
I would also add a check to see if the name equals pager, in that case continue;
Here is solution
JSONObject root = new JSONObject(result);
if(root != null){
Iterator iter = root.keys();
while (iter.hasNext()){
try {
String key = (String) iter.next();
JSONObject itemObject = root.getJSONObject(key);
} catch (JSONException e) {
}
}
}
This question already has answers here:
Parsing json with android
(4 answers)
Closed 8 years ago.
I am trying to parse this json:
[{
"codError": 0,
"msg": "OK"
}, {
"id": 1,
"role": {
"id": 4,
"name": "Super",
"description": "Roling.",
"rights": [],
"superuser": true,
"active": true,
"optimisticLock": 0
},
"now": null,
"points": [],
"firstName": null,
"lastName": null,
"loginName": "admin",
"password": null,
"connected": true,
"active": true,
"optimisticLock": null
},
["U4"]
]
I am not able to get the value of role id and loginName, my code is here:
private static final String TAG_ROLE = "role";
private static final String TAG_ID = "id";
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonarr =new JSONArray(jsonStr);
JSONObject jobj=jsonarr.getJSONObject(1);
JSONObject role =jobj.getJSONObject(TAG_ROLE);
String role_id = role.getString(TAG_ID);
} catch (JSONException e) {
e.printStackTrace();
}
I debug my app and String role_id doesn´t get any value, what is the problem of the code? Thank you
JSONArray array;
array = new JSONArray(jsonStr);
JSONObject obj = array.getJSONObject(1);
JSONObject obj2 = obj.getJSONObject("role");
int id = obj2.getInt("id");
String name = obj2.getString("name");
In case you aren't getting any values, you might want to check if the response is exactly how you're expecting it to be. Also, check the values of TAG_ROLE, TAG_ID.
Edit 1 :
String jsonStr = "[{\n \"codError\": 0,\n \"msg\": \"OK\"\n}, {\n \"id\": 1,\n \"role\": {\n \"id\": 4,\n \"name\": \"Super\",\n \"description\": \"Roling.\",\n \"rights\": [],\n \"superuser\": true,\n \"active\": true,\n \"optimisticLock\": 0\n },\n \"now\": null,\n \"points\": [],\n \"firstName\": null,\n \"lastName\": null,\n \"loginName\": \"admin\",\n \"password\": null,\n \"connected\": true,\n \"active\": true,\n \"optimisticLock\": null\n},\n[\"U4\"]\n\n]";
try {
JSONArray array;
array = new JSONArray(jsonStr);
JSONObject obj = array.getJSONObject(1);
JSONObject obj2 = obj.getJSONObject("role");
int id = obj2.getInt("id");
String name = obj2.getString("name");
System.out.println(id);
System.out.println(name);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'd like to parse the following items from JSON data below: title, year, runtime, critics consensus, the theater release date, the synopsis, poster thumbnails, and poster originals. But when I parse my data I get a JSON Exception: No value for TAG_TITLE, and basically nothing happens.
{"query": {
"count": 30,
"created": "2014-01-16T14:39:33Z",
"lang": "en-US",
"results": {
"movies": [
{
"id": "13065",
"title": "Gladiator",
"year": "2000.0",
"mpaa_rating": "R",
"runtime": "171.0",
"critics_consensus": "Ridley Scott and an excellent cast successfully convey the intensity of Roman gladitorial combat as well as the political intrigue brewing beneath.",
"release_dates": {
"theater": "2000-05-05",
"dvd": "2000-11-21"
},
"ratings": {
"critics_rating": "Certified Fresh",
"critics_score": "76.0",
"audience_rating": "Upright",
"audience_score": "87.0"
},
"synopsis": "",
"posters": {
"thumbnail": "http://content6.flixster.com/movie/11/16/89/11168944_mob.jpg",
"profile": "http://content6.flixster.com/movie/11/16/89/11168944_pro.jpg",
"detailed": "http://content6.flixster.com/movie/11/16/89/11168944_det.jpg",
"original": "http://content6.flixster.com/movie/11/16/89/11168944_ori.jpg"
},
"abridged_cast": [
{
"name": "Russell Crowe",
"id": "162652569",
"characters": "Maximus"
},
{
"name": "Joaquin Phoenix",
"id": "162655394",
"characters": "Commodus"
},
{
"name": "Connie Nielsen",
"id": "162653203",
"characters": "Lucilla"
},
{
"name": "Oliver Reed",
"id": "162662908",
"characters": "Proximo"
},
{
"name": "Derek Jacobi",
"id": "162656362",
"characters": "Gracchus"
}
],
"alternate_ids": {
"imdb": "0172495"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065.json",
"alternate": "http://www.rottentomatoes.com/m/gladiator/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/cast.json",
"clips": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/clips.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/13065/similar.json"
}
}
This is the code for extracting the data I want:
jsonObject = new JSONObject(result);
JSONObject queryJSONObject = jsonObject.getJSONObject("query");
JSONObject resultsJSONObject = queryJSONObject.getJSONObject("results");
JSONArray moviesJSONArray = resultsJSONObject.getJSONArray("movies");
for(int i = 0; i < moviesJSONArray.length(); i++){
JSONObject c = moviesJSONArray.getJSONObject(i);
String title = c.getString("TAG_TITLE");
String year = c.getString("TAG_YEAR");
String mpaa_rating = c.getString("TAG_RATING");
String runtime = c.getString("TAG_RUNTIME");
String critics_consensus = c.getString("TAG_CONSENSUS");
JSONObject dates = c.getJSONObject("release_dates");
String theater = dates.getString("TAG_THEATER");
JSONObject posters = c.getJSONObject("posters");
String thumbnail_posters = posters.getString("TAG_TBPOSTER");
String original_posters = posters.getString("TAG_ORIPOSTER");
Log.e(TAG,
", Title: " + title
+ ", Year: " + year
+ ", Rating: " + mpaa_rating
+ ", Runtime: " + runtime
+ ", Consensus :" + critics_consensus
+ ", Theater date: " + theater
+ ". Poster small: " + thumbnail_posters
+ ", Poster big: " + original_posters
);
HashMap<String, String> movie = new HashMap<String, String>();
movie.put(TAG_TITLE, title);
movie.put(TAG_YEAR, year);
movie.put(TAG_RATING, mpaa_rating);
movie.put(TAG_RUNTIME, runtime);
movie.put(TAG_CONSENSUS, critics_consensus);
movie.put(TAG_THEATER, theater);
movie.put(TAG_TBPOSTER, thumbnail_posters);
movie.put(TAG_ORIPOSTER, original_posters);
moviesList.add(movie);
And before my OnCreate I'm using these Strings for the TAGS:
private static final String TAG_CONSENSUS = "critics_consensus";
private static final String TAG_RATING = "mpaa_rating";
private static final String TAG_YEAR = "year";
private static final String TAG_THEATER = "theater";
private static final String TAG_TITLE = "title";
private static final String TAG_RUNTIME = "runtime";
private static final String TAG_DATE = "theater";
private static final String TAG_TBPOSTER = "thumbnail_posters";
private static final String TAG_ORIPOSTER = "original_posters";
JSONArray movies = null;
ArrayList<HashMap<String, String>> moviesList;
My TAG_TITLE is "title" which is also used in the JSON Data so I'm at a loss as to why I get this error? Or is my code wrong? Thanks in advance
Shouldn't you do
String title = c.getString(TAG_TITLE);
instead of
String title = c.getString("TAG_TITLE");
?
You should have to either write String directly like
JSONObject jsonobject = new JSONObject(jsonString);
JSONObject queryjson = jsonobject.getJSONObject("query");
String count = queryjson.getString("count");
OR
//This Code is As per Your Coding
JSONObject jsonobject = new JSONObject(jsonString);
JSONObject queryjson = jsonobject.getJSONObject(TAG_QUERY);
String count = queryjson.getString(TAG_COUNT);
Inshort Just Remove The " " before Or After String Name TAG_..
I have a string from http request and i want to replace multiple chars and strings with others.How i can do this?With Array for more efficient way?
String result =" "hourly": [ {"cloudcover": "0", "humidity": "93", "precipMM": "0.0", "pressure": "1013", "sigHeight_m": "0.7", "swellDir": "70", "swellHeight_m": "0.5", "swellPeriod_secs": "1.0", "tempC": "9", "tempF": "48", "time": "0", "v";
String result2 = result.replace("{", " ");
String result3 = result2.replace("}", " ");
String result4 = result3.replace("[", " ");
String result5 = result4.replace("]", " ");
String result6 = result5.replace("\"", "");
String result7 = result6.replaceAll("......", " ");
String result8 = result7.replaceAll("cloudcover", "\n \ncloudcover");
String result9 = result8.replaceAll("winddir:", " \nwinddir:");
String result10 = result9.replaceAll("tempC:", " \ntempC:");
WeatherInfos.setText( result10 );//Shows the weather info
Try following
String result = "{\"hourly\": [ {\"cloudcover\": \"15\", \"humidity\": \"93\", \"pressure\": \"1013\", \"tempC\": \"9\", \"winddir\": \"25\"}]}";
if(!result.startsWith("{"))
result = "{" + result + "}";
JSONObject JSONResult = new JSONObject(result);
JSONResult = (JSONObject) JSONResult.getJSONArray("hourly").get(0);
String cloudcover = JSONResult.getString("cloudcover");
String tempC= JSONResult.getString("tempC");
String winddir= JSONResult.getString("winddir"); //i do not see winddir in your result
Toast.makeText(getapplicationContext(), "Cloud Cover is "+ cloudcover , Toast.LENGTH_LONG).show();
now print cloudcover, winddir and tempC where ever you want.