Below is my json, which I am trying to read (code Log.i("callinfo", callInfo + ""); onwards, but getting error. My code to read and error message are also mentioned.
{
"CallInfo":[
{
"ItemInfo":[
{
"chargeable":"True",
"itemID":"B13984350K"
},
{
"chargeable":"True",
"itemID":"B13984351A"
}
],
"numberOfCopies":2
}
],
"ISBN":[
""
],
"TitleAvailabilityInfo":null,
"author":"Chief Army Medical Officer.",
"baseCallNumber":"RC87.1 PRE",
"publisherName":"HQ Army Medical Services,",
"title":"Preventing heat injuries : the commanders' guide",
"titleID":9206,
"yearOfPublication":"2000"
}
Code:
public void readBarCode(String response, String scannedBarcode) {
final CountDownLatch latch = new CountDownLatch(1);
final String[] names = new String[4];
JSONArray mArray, mArray1, mArray2;
int totalCount = 0;
int avail = 0;
String author, title, publisherName;
try {
JSONObject obj = new JSONObject(response);
//Results
if (obj.getJSONObject("Results") != null) {
JSONObject obj1 = obj.getJSONObject("Results");
//LookupTitleInfoResponse
if (obj1.getJSONObject("LookupTitleInfoResponse") != null) {
JSONObject obj2 = obj1.getJSONObject("LookupTitleInfoResponse");
//TitleInfo
if (obj2.getJSONArray("TitleInfo") != null) {
mArray = obj2.getJSONArray("TitleInfo");
JSONObject callInfo = mArray.getJSONObject(0);
Log.i("callinfo", callInfo + "");
mArray2 = callInfo.getJSONArray("ItemInfo");
for (int i = 0; i <= mArray2.length(); i++) {
if (mArray2.getJSONObject(i).getString("chargeable").equals("False")) {
totalCount++;
}
if (mArray2.getJSONObject(i).getString("itemID").equals(scannedBarcode)) {
avail = 1;
}
}
author = mArray.getJSONObject(0).getString("author");
publisherName = mArray.getJSONObject(0).getString("publisherName");
title = mArray.getJSONObject(0).getString("title");
TitleTxt.setText(title);
PublisherTxt.setText(publisherName);
CreatorTxt.setText(author);
BookBarcode.setText(scannedBarcode);
AvailabiltyTxt.setText(totalCount);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Getting error on below line:
mArray2 = callInfo.getJSONArray("ItemInfo");
Error:
org.json.JSONException: No value for ItemInfo
03-28 16:33:09.953 17229-17229/com.androidatc.customviewindrawer W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
03-28 16:33:09.953 17229-17229/com.androidatc.customviewindrawer W/System.err: at org.json.JSONObject.getJSONArray(JSONObject.java:584)
Here we can clearly see that ItemInfo got value.
Can anyone tell me - how to resolve above error?
Many thanks in advance.
Try with below code
mArray = obj2.getJSONArray("TitleInfo");
JSONObject titleInfo = mArray.getJSONObject(0);
JSONArray arr1 = titleInfo.getJSONArray("CallInfo");
JSONObject callInfo = arr1.getJSONObject(0);
JSONArray arr2 = callInfo.getJSONArray("ItemInfo");
Log.i("ItemInfo", arr2 + "");
Here is full method
public void readBarCode(String response, String scannedBarcode) {
final CountDownLatch latch = new CountDownLatch(1);
final String[] names = new String[4];
JSONArray mArray, mArray1, mArray2;
int totalCount = 0;
int avail = 0;
String author, title, publisherName;
try {
JSONObject obj = new JSONObject(response);
//Results
if (obj.getJSONObject("Results") != null) {
JSONObject obj1 = obj.getJSONObject("Results");
//LookupTitleInfoResponse
if (obj1.getJSONObject("LookupTitleInfoResponse") != null) {
JSONObject obj2 = obj1.getJSONObject("LookupTitleInfoResponse");
//TitleInfo
if (obj2.getJSONArray("TitleInfo") != null) {
mArray = obj2.getJSONArray("TitleInfo");
JSONObject titleInfo = mArray.getJSONObject(0);
JSONArray arr1 = titleInfo.getJSONArray("CallInfo");
JSONObject callInfo = arr1.getJSONObject(0);
JSONArray arr2 = callInfo.getJSONArray("ItemInfo");
Log.i("ItemInfo", arr2 + "");
for (int i = 0; i < arr2.length(); i++) {
if (arr2.getJSONObject(i).getString("chargeable").equals("False")) {
totalCount++;
}
if (arr2.getJSONObject(i).getString("itemID").equals(scannedBarcode)) {
avail = 1;
}
}
author = mArray.getJSONObject(0).getString("author");
publisherName = mArray.getJSONObject(0).getString("publisherName");
title = mArray.getJSONObject(0).getString("title");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
I getting this error: JSONObject cannot be converted to JSONArray
caused by this part of code:
private int parse() {
try {
Log.d("Jou", "result");
JSONArray ja = new JSONArray(data);
JSONObject jo = null;
titles.clear();
skills.clear();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("ID");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("Jou", e.getMessage());
return 0;
}
Although I tried it before and it was exactly the same, then I added another string which is the date then I got the error. What could be wrong with the code?
This is the result from the server that needs to be parsed:
s = {"result":[{"post_id":"390","post_title":"Cart","post_date":"2017-02-07 12:17:29"},{"post_id":"421","post_title":"Front End Developer - Digital Arts","post_date":"2017-02-07 12:18:04"},{"post_id":"431","post_title":"Art Director","post_date":"2017-02-07 12:18:19"}]}
Here is the PHP script:
<?php
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ("Unable to connect") ;
if(! $conn )
{
echo 'Could not connect: ' . mysqli_error();
}
error_reporting(-1);
ini_set('display_errors', 'On');
mysqli_set_charset($conn, 'utf8');
$search ="";
if(isset($_REQUEST['query'] )){
$search = $_REQUEST['query'];
}
if($search != ""){
$sql = "SELECT ID,post_title,post_date FROM `wp_posts` WHERE post_title LIKE '%".$search."%'";
mysqli_select_db($conn,'');
$query = mysqli_query($conn, $sql ) or die ("Error: ".mysqli_error($conn));;
$result = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
array_push($result,
array('post_id'=>$row['ID'],
'post_title'=>$row['post_title'],
'post_date'=>$row['post_date']
));}
echo json_encode(array("result"=>$result));
}else{
echo 'No search field has been sent';
}
?>
Try following code :
try {
Log.d("Jou", "result");
JSONObject object = new JSONObject(data)
JSONArray ja = object.getJSONArray("result");
JSONObject jo = null;
titles.clear();
skills.clear();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("post_id");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("Jou", e.getMessage());
return 0;
}
Check with the following code. I hope it will work
private int parse(String data) {
try {
JSONObject jsonObject = new JSONObject(data); //get a response as Json Object and then get it as array by corresponding key
JSONArray ja = jsonObject.getJSONArray("result");
JSONObject jo = null;
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
String id = jo.getString("ID");
String title = jo.getString("post_title");
//String content = jo.getString("post_content");
String date = jo.getString("post_date");
Skill skill = new Skill();
skill.setId(id);
skill.setTitle(title);
//skill.setContent(content);
skill.setDate(date);
skills.add(skill);
titles.add(title);
}
return 1;
} catch (JSONException e) {
Log.d("TAG", e.getMessage());
return 0;
}
}
There is some problem in your json response it is taking extra character in post_date try to validate it in the below link.
http://www.jsoneditoronline.org/
Thank you guys.Finally i got the solution.If we want to check whether string is empty or null we must trim() the string.
String url="http://app name/Api/GetJobDetails/GetJobDetails?COMP_REQ_ID=" + title + "&StuEmail=" + e ; // this is the url
AQuery mAQuery = new AQuery(SecondActivity.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
public Object dataSource;
#Override
public void callback(String url, String data, AjaxStatus status)
{
uper.callback(url, data, status);
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Salary = json.optString("Req_From_Sal");
if (Salary == null || Salary.trim().equals("null") || Salary.trim().length() <= 0) {
b14.setText("Not Mentioned");
}
else
{
b14.setText(""+Salary);
}
}
}
}
});
Check you string if it is null or blank then print message what you want. For example:
if(StringData.length()==0){
//show message
}else{
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Salary = json.optString("Req_From_Sal");
if (Salary == null)
b14.setText("NA"+Salary);
else
b14.setText(""+Salary)
}
}
MoreOver if you want to show specific message for specific user then ask for the success parameter. If success==1 go for you logic else if success ==0 then ask for message parameter as well parse it and show it to user
1.Check whether StringData is null or empty.
2.Check if rootArray.length()==0
Try this.
if(StringData!=null) {
JSONArray rootArray = new JSONArray(StringData);
for (int i = 0; i < rootArray.length(); ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Job_Title = json.optString("Req_Title", "default_value");
String Designation = json.optString("Req_Designation_Role", "default_value");
String Salary = json.optString("Req_From_Sal", "Salary Not Mentioned");
b14.setText("" + Salary);
}
}else{
Log.d(TAG, "Invalid JSON Data");
b14.setText("Salary Not Mentioned");
}
USe TextUtils.isEmpty() to check for null and empty string.
Always add null check before getting any variable from object.
Modified code below:
JSONArray rootArray = new JSONArray(StringData);
if(rootArray!=null&&rootArray.length())
{
int len = rootArray.length();
for (int i = 0; i < len; ++i)
{
JSONObject json = rootArray.optJSONObject(i);
if (json != null) {
String Job_Title = json.optString("Req_Title");
String Designation = json.optString("Req_Designation_Role");
String Job_Type = json.optString("Req_Job_Type");
String Salary;
if (json.has("Req_From_Sal") && !TextUtils.isEmpty(json.getString("Req_From_Sal")) {
Salary = json.optString("Req_From_Sal");
} else {
Salary = "Not available";
}
b14.setText(Salary);
}
}
}
Thank you guys.Finally i got the solution. Here is edit code.To check the String is null or empty we should have to trim() the string.
Android side:-
String url="http://app name/Api/GetJobDetails/GetJobDetails?COMP_REQ_ID=" + title + "&StuEmail=" + e ; // this is the url
AQuery mAQuery = new AQuery(SecondActivity.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
public Object dataSource;
#Override
public void callback(String url, String data, AjaxStatus status) {
uper.callback(url, data, status);
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Job_Title = json.optString("Req_Title");
String Designation = json.optString("Req_Designation_Role");
String Job_Type = json.optString("Req_Job_Type");
String Salary = json.optString("Req_From_Sal");
if(Job_Title == null || Job_Title .trim().equals("null") ||Job_Title .trim().length<=0){
b1.setText("Job title not set.");
}else{
b1.setText("" +Job_Title);
}
if(Designation == null || Designation.trim().equals("null") ||Designation.trim().length() <= 0){
b3.setText("Job Designation not set.");
}else{
b3.setText("" +Designation);
}
if(Job_Type == null || Job_Type.trim().equals("null") || Job_Type.trim().length() <= 0){
b13.setText("Job Type not set.");
}else{
b13.setText("" +Job_Type);
}
if(Salary == null || Salary.trim().equals("null") || Salary.trim().length() <= 0){
b14.setText("Not yet Mentioned");
}else{
b14.setText(""+Salary);
}
}
}
}
});
i'm trying to parse this below json format such as:
[
[
{
"mobileNumber":"<Censored>","contactUserId":"17",
"userEwallets":
[
{"accountNumber":"<Censored>"},
{"accountNumber":"<Censored>"},
{"accountNumber":"<Censored>"}
]
}
]
,
[
{
"mobileNumber":"<Censored>","contactUserId":"1",
"userEwallets":
[
{"accountNumber":"<Censored>"}
]
}
]
]
for parsing second json array of that as
[
{
"mobileNumber":"<Censored>",
"contactUserId":"1",
"userEwallets":
[
{"accountNumber":"<Censored>"}
]
}
]
i get this error:
Index 1 out of range [0..1)
from below code my code can only parse the first array of that, for second array i get exception when i try to get mobileNumber of second json array object
for (int i = 0; i < response.length(); i++) {
try {
JSONArray jsonArray = response.getJSONArray(i);
final String mobileNumber = jsonArray.getJSONObject(i).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(i).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(i).getString("userEwallets");
Log.e("MobileNumber ", mobileNumber);
JSONArray ewallets = new JSONArray(userEwallets);
for (int j = 0; j < ewallets.length(); j++) {
JSONObject ewalletObject = ewallets.getJSONObject(j);
final String accountNumber = ewalletObject.getString("accountNumber");
Log.e("accountNumber ", accountNumber);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Try this one...
JSONArray response;
try {
response = new JSONArray(res);
for (int i = 0; i < response.length(); i++) {
JSONArray insideJSONArray = response.getJSONArray(i);
JSONObject jsonObject = insideJSONArray.getJSONObject(0);
String mobileNumber = jsonObject.getString("mobileNumber");
Log.e("TAG", "mobileNumber: " + mobileNumber);
String contactUserId = jsonObject.getString("contactUserId");
Log.e("TAG", "mobileNumber: " + contactUserId);
JSONArray userEwallets = jsonObject.getJSONArray("userEwallets");
for (int j = 0; j < userEwallets.length(); j++) {
JSONObject ewalletObject = userEwallets.getJSONObject(j);
final String accountNumber = ewalletObject.getString("accountNumber");
Log.e("accountNumber ", accountNumber);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Change:
final String mobileNumber = jsonArray.getJSONObject(i).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(i).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(i).getString("userEwallets");
to
final String mobileNumber = jsonArray.getJSONObject(0).getString("mobileNumber");
final String contactUserId = jsonArray.getJSONObject(0).getString("contactUserId");
final String userEwallets = jsonArray.getJSONObject(0).getString("userEwallets");
how I can access data from a JSONArray? It is this and contains this information:
"deadlines": [
{
"start": 1439539200,
"end": 1439542800
},
{
"start": 1440144000,
"end": 1440147600
},
{
"start": 0,
"end": 0
}
]
I need to have in a String tag each item "start". Thanks
EDIT
My code is this:
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
for (int j=0; j < array.length(); j++)
{
try
{
JSONObject obj = array.getJSONObject(j);
String start = obj.getString("start");
String end = obj.getString("end");
Log.e("", "start = " + start);
}
catch (JSONException e)
{
Log.e("", "error = " + e.getMessage());
}
}
I get this error:
"error = No value for start"
Do this
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
JSONArray jArray = array.getJSONObject(0).getJSONArray("deadlines");
for (int i = 0; i < jArray.length(); i++) // assuming your array is jArray
{
try
{
JSONObject obj = jArray.getJSONObject(i);
String start= obj.getString("start"); // store in an ArrayList
String end = obj.getString("end"); //// store in an ArrayList
}
catch (JSONException e)
{
// Error
}
}
JSONArray mJsonArray=new JSONArray("Deadlines");
for(int i=0;i<mJsonArray.length();i++){
JSONObject mJsonObject=new JSONObject(mJsonArray.get(i).toString));
String start = mJsonObject.optString("start","");
String end = mJsonObject.optString("end","");
}
Try this:
StringBuilder sb = new StringBuilder();
JSONArray arr = new JSONArray("deadlines");
for(int i=0;i<arr.length;i++){
JSONObject obj = arr.getJSONObject(i);
sb.append(obj.get("start").toString());
sb.append(",");
}
String strStartTag = sb;
JSONArray ja = new JSONArray(yourjsondata));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo_feed = new JSONObject(ja.get(i).toString());
String start = jo_feed.getString("start");
}
write Custom ArrayAdapter by example: http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter
i can't fill array in cycle.
working example:
Weather weather_data[] = new Weather[]
{ new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Cloudy"),
new Weather("http://www.ezzylearning.com/images/ImagesNew/net_framework.png", "Showers")
};
my code:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
You need to initialize this array:
NewsData[] NewsData_data;
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
NewsData_data=new NewsData[jsonMainNode.length()];//<------------HERE
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String header = jsonChildNode.optString("header");
String short_text = jsonChildNode.optString("short_text");
String team = jsonChildNode.optString("team");
String datatime = jsonChildNode.optString("datatime");
String photo_url = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header, short_text, team, datatime, photo_url);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(getActivity(),
R.layout.news_details, NewsData_data);
listView.setAdapter(adapter);
}
Simplified answer: your array is not initialized. Longer answer, you have to know how big it is going to be, then initialize it to that size. A simple example:
NewsData[] NewsData_data;
ArrayList<NewsData> newsDataArray = new ArrayList<NewsData>();
String header = "header";
String short_text = "short_text";
String team = "team";
String datatime = "datatime";
String photo_url = "photo_url";
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
newsDataArray.add(new NewsData(header, short_text, team, datatime, photo_url));
NewsData_data = new NewsData[newsDataArray.size()];
newsDataArray.toArray(NewsData_data);
System.out.println(NewsData_data);