can't fill array NewsData[] NewsData_data - android

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);

Related

JSONObject cannot be converted to JSONArray but after successfully tested

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/

Decode JSON String in Android

I have a contacts which is in the form of JSON. Now I want to decode them into String array. There are two arrays; names and phones. I'm using this code:
String[] names;
String[] phones;
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
JSONObject jsonObject = new JSONObject(jsonArray.toString());
Log.i("INFO", String.valueOf(jsonObject.length()));
} catch (JSONException e) {
e.printStackTrace();
}
This generates an error. How can I add all names in names array and all phones in phones array. Like names[0] is assigned A which is a first name and phones[0] assigned 911 which is first phone number corresponding to first name. How can I do that, I'm new in android?
The problem is in this line
JSONObject jsonObject = new JSONObject(jsonArray.toString());
you are trying to convert JSONArray in JSONObject , which you can't. if you want to access JSONObject inside of JSONArray you have to loop through each, or you can get specific object by it's index.
String[] names;
String[] phones;
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
phones = names = new String[jsonArray.length()];
for(int i = 0 ; i < jsonArray.length(); i ++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
names[i] = jsonObject.getString("name");
phones[i] = jsonObject.getString("phone");
Log.i("INFO", "name : " + jsonObject.getString("name") + " , phone : " + jsonObject.getString("phone"));
}
} catch (JSONException e) {
e.printStackTrace();
}
You can't convert json arrya to json object like that:
try {
JSONArray jsonArray = new JSONArray(test);
for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Your code goes here..
}
} catch (JSONException e) {
e.printStackTrace();
}
here is the required code.
ArrayList<String> names = new ArrayList<>();
ArrayList<String> phones = new ArrayList<>();
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String phone = jsonObject.getString("phone");
names.add(name);
phones.add(phone);
Log.i("INFO", name + ", " + phone);
}
} catch (JSONException e) {
e.printStackTrace();
}
above you have used simple arrays they can store data only of fixed size. But arrayList and List can store data of variable size or you do not need to fix their size.

how to resolve error in reading json?

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();
}
}

How to make Custom ArrayList<customeClass> using JsonObject values?

This is my codes :
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject jsonOb=jsonObject.getJSONObject("LocationMatrix");
Log.e(TAG,"jsonOb :"+jsonOb.toString());
Then print out :
jsonOb :{"45":"NUMANCIA 39-41","44":"DEMESTRE 10","35":"ALIÓ 19","22":"ALFONSO X EL SABIO 8","36":"ROSARI 42","23":"PI I MARGALL 101","33":"MELCHOR DE PALAU 65","24":"ROBRENYO, ESC.A 55","34":"SARDENYA 545","25":"ROBRENYO, ESC.B 55","39":"L´ERAMPPRUNYA 41","26":"ROSSELLO 230","27":" ENRIQUE GIMENEZ 10","37":"CALATRAVA 1-7 E","28":"GRAN VIA CORTS CATALANES 489","38":"AUGUSTA 276","29":"AUTOVIA DE CASTELLDEFELS 135","43":"ROSARIO 37","30":"GANDUXER 72","42":"VALLDEMOSA 64","41":"VALLDEMOSA 62","32":"CONSELL DE CENT 97","40":"VALLDEMOSA 60","31":"SANTA AMELIA 22"}
How to make custom ArrayList using JsonObject values?
For Example :
for (int i = 0; i < jsonOb.length(); i++) {
int mId = intValue;
String mTitle = StringValue;
locationList.add(new Location(mId, mTitle));
}
Where LocationList is one kind of custome ArrayList<Location>.
and Location is one kind of class which parameters id, title.
use gson library
How To Convert Java Object To / From JSON (Gson)
POJO
package com.mkyong.core;
import java.util.ArrayList;
import java.util.List;
public class DataObject {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods
#Override
public String toString() {
return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list="
+ list + "]";
}
}
JSON STRING
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
DataObject obj = gson.fromJson(str, DataObject.class);
link
Try this..
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject jsonOb=jsonObject.getJSONObject("LocationMatrix");
Log.e(TAG,"jsonOb :"+jsonOb.toString());
Iterator i = jsonOb.keys();
while (i.hasNext()) {
try {
String key = i.next().toString();
String j = jsonOb.getString(key);
locationList.add(new Location(Integer.parseInt(key), j));
} catch (JSONException e) {
e.printStackTrace();
}
}

How to set json data to list view?

I tried to add json data to listview.But i don't know how to add the json data to list adapter.
try {
mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
String address = jsonChildNode.optString("address");
String mobile = jsonChildNode.optString("mobile");
String direction = "Direction: "+jsonChildNode.optString("direction");
String bestTime = "Best time to visite: "+jsonChildNode.optString("bestTime");
String food = jsonChildNode.optString("food");
String dress = jsonChildNode.optString("dress");
String priceRange = "Price Range: "+jsonChildNode.optString("priceRange");
String rate = jsonChildNode.optString("Rate");
String comment = "Price Range: "+jsonChildNode.optString("comment");
map.put("restName",restName);
map.put("address",address);
map.put("mobile",mobile);
map.put("direction",direction);
map.put("bestTime",bestTime);
map.put("food",food);
map.put("dress",dress);
map.put("priceRange",priceRange);
map.put("rate",rate);
map.put("comment",comment);
mylist = new ArrayList<HashMap<String, String>>();
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
// ListAdapter adapter = new SimpleAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mylist);
// list.setAdapter(adapter);
}
Can anyone tel me how to set this data to list view.?
Try this..
Your doing reversely. declear the arraylist before for loop and declear the HashMap inside the for loop .
mylist = new ArrayList<HashMap<String, String>>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
HashMap<String, String> map = new HashMap<String, String>();
String address = jsonChildNode.optString("address");
//So on
map.put("restName",restName);
//So on
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
google-gson
I would use gson for this. Check the gson project website for more details on how. This is an example for object serialisation/deserialisation:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj

Categories

Resources