How to set json data to list view? - android

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

Related

How to convert JSONObject to Hashmap?

String jsonString = "{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}";
JSONObject jValueObject = new JSONObject(jsonString);
Iterator<?> values = jValueObject.keys();
while(values.hasNext()){
String final_key = (String)values.next();
String final_value = jValueObject.getString(final_key);
if (final_value != "")
map.put(final_key, final_value);
if (!final_key.equals("")) {
sbkeys.append(final_key).append(',');
}
}
Log.e("Final_Map", String.valueOf(map));
itemList = sbkeys.toString();
Output : {name=kd,isMe=yes,time=10:12 AM}
Try this code:
HashMap map = new HashMap<String, String>();
Iterator<?> values = jValueObject.keys();
while(values.hasNext()) {
String final_key = (String)values.next();
String final_value = jValueObject.optString(final_key, "");
if (!final_value.equals(""))
map.put(final_key, final_value);
}
for (k : map.keySet()) {
Log.d("Final_Map", "map[" + key + "] : " + map.get(k));
}
this is a duplicate question,
please check these answers
Convert JSONObject to Map
use Jackson(http://jackson.codehaus.org/) from http://json.org/
HashMap<String,Object> result =
new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);
or
You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.
HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);
First off, if its a json array that you need in the string then wrap your string in square brackets. (I'd expect you've escaped the double quotes as well).
String jsonString = "[{\"name\":\"kd\",\"isMe\":\"yes\",\"time\":\"10:12 AM\"},{\"name\":\"you\",\"isMe\":\"no\",\"time\":\"10:12 AM\"}]";
Now its a JSONArray and not a JSONObject. So to get a list of Maps,
JSONArray jValueArray = new JSONArray(jsonString);
List<Object> listOfMaps = jValueArray.toList();
System.out.println(listOfMaps);
Prints:
[{isMe=yes, name=kd, time=10:12 AM}, {isMe=no, name=you, time=10:12 AM}]
JSONObject jObject = new JSONObject(jsonString);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
map = new HashMap<String, String>();
sbkeys = new StringBuilder();
String key = (String) keys.next();
String value = jObject.getString(key);
try{
JSONObject jValueObject = new JSONObject(value);
Iterator<?> values = jValueObject.keys();
while (values.hasNext()) {
String final_key = (String) values.next();
String final_value = jValueObject.getString(final_key);
if (!final_value.equalsIgnoreCase("")) {
map.put(final_key, final_value);
sbkeys.append(final_key).append(',');
}
}
}catch (Exception e){
e.fillInStackTrace();
}
try {
//// Your Code..
} catch (Exception e) {
errorCode = "1";
}
}

how can i store muliple rows in JsonArray?

The problem is that in first row data save normally but in second row or move on data redundant Like:
public void Save(){
String register;
JSONObject jsonObj;
JSONObject json;
JSONArray jsonTempArray = new JSONArray();
JSONObject jsonObject=new JSONObject();
JSONArray jsonArray=new JSONArray();
try{
JSONObject jsonObjs=new JSONObject();
jsonObj=new JSONObject();
json=new JSONObject();
Integer.valueOf(mGeneralID);
str_UpdatedGeneralID= "6832";
String str_FMeasurementSamplesize = "";
if (txtFMeasurementSamplesize.getText().toString().equals("")){
str_FMeasurementSamplesize = "0";
}else {
str_FMeasurementSamplesize = txtFMeasurementSamplesize.getText().toString();
}
String Samplesize = txt_Sample_Size.getText().toString();
String Qtypersize = txt_Qty_per_Size.getText().toString();
String TotalnoofmeasPointsizeA = txtTotalnoOfmeasPointsizeA.getText().toString();
String TotalnoofmeasPointsizeAA = txtTotalnoOfmeasPointsizeAA.getText().toString();
String TotalnoofmeasPointsizeB = txtTotalnoOfmeasPointsizeB.getText().toString();
String TotalnoofmeasPointsizeBB = txtTotalnoOfmeasPointsizeBB.getText().toString();
String NomeasurementptoutoftolA = txtNomeasurementptoutoftolA.getText().toString();
String NomeasurementptoutoftolB = txtNomeasurementptoutoftolB.getText().toString();
String PASS = txt_pass.getText().toString();
String Fail = txt_fail.getText().toString();
String Pending = txt_pending.getText().toString();
String Remarks = txt_Remarks_F.getText().toString();
DateFormat df = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
String CreationDate = df.format(Calendar.getInstance().getTime());
int a =0;
for (int i=0; i < MeasurementArrayList.size(); i++){
String MeasurementSheetDetailID = MeasurementArrayList.get(i).getmeasurementSheetDetailID();
String MeasurementPointID = MeasurementArrayList.get(i).getmeasurementPointID();
String MeasurementPoints = MeasurementArrayList.get(i).getmeasurementPoints();
String SpecSizeA = MeasurementArrayList.get(i).getSpecSizeA();
String SpecSizeAOne = MeasurementArrayList.get(i).getSpecSizeAOne();
String SpecSizeATwo = MeasurementArrayList.get(i).getSpecSizeATwo();
String SpecSizeAThree = MeasurementArrayList.get(i).getSpecSizeAThree();
String SpecSizeAFour = MeasurementArrayList.get(i).getSpecSizeAFour();
String SpecSizeAFive = MeasurementArrayList.get(i).getSpecSizeAFive();
String SpecSizeB = MeasurementArrayList.get(i).getSpecSizeB();
String SpecSizeBOne = MeasurementArrayList.get(i).getSpecSizeBOne();
String SpecSizeBTwo = MeasurementArrayList.get(i).getSpecSizeBTwo();
String SpecSizeBThree = MeasurementArrayList.get(i).getSpecSizeBThree();
String SpecSizeBFour = MeasurementArrayList.get(i).getSpecSizeBFour();
String SpecSizeBFive = MeasurementArrayList.get(i).getSpecSizeBFive();
String Tolerance = MeasurementArrayList.get(i).gettolerance();
jsonObj.put("MeasurementSheetID", str_FMeasurementSamplesize);
jsonObj.put("GeneralID", str_UpdatedGeneralID);
jsonObj.put("Samplesize", Samplesize);
jsonObj.put("Measurement", str_sp_Measurement);
jsonObj.put("Qtypersize", Qtypersize);
jsonObj.put("Color", str_sp_Color);
jsonObj.put("SpecSizeA", str_sp_SpecSizeA);
jsonObj.put("SpecSizeB", str_sp_SpecSizeB);
jsonObj.put("TotalnoofmeasPointsizeA",TotalnoofmeasPointsizeA);
jsonObj.put("TotalnoofmeasPointsizeAA", TotalnoofmeasPointsizeAA);
jsonObj.put("TotalnoofmeasPointsizeB", TotalnoofmeasPointsizeB);
jsonObj.put("TotalnoofmeasPointsizeBB", TotalnoofmeasPointsizeBB);
jsonObj.put("NomeasurementptoutoftolA", NomeasurementptoutoftolA);
jsonObj.put("NomeasurementptoutoftolB", NomeasurementptoutoftolB);
jsonObj.put("PASS", PASS);
jsonObj.put("Fail", Fail);
jsonObj.put("Pending", Pending);
jsonObj.put("Remarks", Remarks);
jsonObj.put("CreationDate", CreationDate);
jsonObj.put("MeasurementSheetDetailID", MeasurementSheetDetailID);
jsonObj.put("MeasurementPointID", MeasurementPointID);
jsonObj.put("MeasurementPoints", MeasurementPoints);
jsonObj.put("SpecSizeA", SpecSizeA);
jsonObj.put("SpecSizeAOne", SpecSizeAOne);
jsonObj.put("SpecSizeATwo", SpecSizeATwo);
jsonObj.put("SpecSizeAThree", SpecSizeAThree);
jsonObj.put("SpecSizeAFour", SpecSizeAFour);
jsonObj.put("SpecSizeAFive", SpecSizeAFive);
jsonObj.put("SpecSizeB", SpecSizeB);
jsonObj.put("SpecSizeBOne", SpecSizeBOne);
jsonObj.put("SpecSizeBTwo", SpecSizeBTwo);
jsonObj.put("SpecSizeBThree", SpecSizeBThree);
jsonObj.put("SpecSizeBFour", SpecSizeBFour);
jsonObj.put("SpecSizeBFive", SpecSizeBFive);
jsonObj.put("Tolerance", Tolerance);
jsonTempArray.put(jsonObj);
}
jsonObject.put("jsondata",jsonTempArray);
register=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
return;
}
new save(register).execute();
}
Result: Both rows are same that`s the problem
Row 1
[{"MeasurementSheetID":"0","GeneralID":"6832","Samplesize":"10","Measurement":"INCH","Qtypersize":"5","Color":"Black","SpecSizeA":"6.5","SpecSizeB":"6.5","TotalnoofmeasPointsizeA":"30","TotalnoofmeasPointsizeAA":"125","TotalnoofmeasPointsizeB":"30","TotalnoofmeasPointsizeBB":"125","NomeasurementptoutoftolA":"0","NomeasurementptoutoftolB":"0","PASS":"d","Fail":"h","Pending":"k","Remarks":"g","CreationDate":"2018-11-305
05:04:28","MeasurementSheetDetailID":"0","MeasurementPointID":"2","MeasurementPoints":"BACK
POCKET POSITION POSITION OUTER
EDGE","SpecSizeAOne":"","SpecSizeATwo":"","SpecSizeAThree":"","SpecSizeAFour":"","SpecSizeAFive":"","SpecSizeBOne":"","SpecSizeBTwo":"","SpecSizeBThree":"","SpecSizeBFour":"","SpecSizeBFive":"","Tolerance":"+/-0.5"},
Row 2
{"MeasurementSheetID":"0","GeneralID":"6832","Samplesize":"10","Measurement":"INCH","Qtypersize":"5","Color":"Black","SpecSizeA":"6.5","SpecSizeB":"6.5","TotalnoofmeasPointsizeA":"30","TotalnoofmeasPointsizeAA":"125","TotalnoofmeasPointsizeB":"30","TotalnoofmeasPointsizeBB":"125","NomeasurementptoutoftolA":"0","NomeasurementptoutoftolB":"0","PASS":"d","Fail":"h","Pending":"k","Remarks":"g","CreationDate":"2018-11-305
05:04:28","MeasurementSheetDetailID":"0","MeasurementPointID":"2","MeasurementPoints":"BACK
POCKET POSITION POSITION OUTER
EDGE","SpecSizeAOne":"","SpecSizeATwo":"","SpecSizeAThree":"","SpecSizeAFour":"","SpecSizeAFive":"","SpecSizeBOne":"","SpecSizeBTwo":"","SpecSizeBThree":"","SpecSizeBFour":"","SpecSizeBFive":"","Tolerance":"+/-0.5"}]
You need to put this jsonObj=new JSONObject(); inside your loop.
So every time loop execute it will create new JSONObject and put it into JSONArray
JsonArray is composed by jsonObjects.
You need to empty jsonobject, populate it and put in jsonarray for every object in jsonArray.
jsonObj = new JSONObject();
Some documentation

Store json array keys data in separate arrayLists

I have this kind of json data returning from url as shown in Image1 Image2 Image3
Basically there are dates inside data and then within these dates there are further 5 different things i.e. session_from, session_to, rate, bookingFound and promotion. What i want is that i want to store all these dates data in separate arraylist.
For example:
sessionfrom0 contains data for 09-09-2018 and all its objects
sessionfrom1 contains data for 10-09-2018 and all its objects
sessionfrom2 contains data for 11-09-2018 and all its objects
I have tried with following piece of code but its not working correctly
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
JSONObject datesObject1 = datesArray.getJSONObject(i);
JSONObject datesObject2 = datesArray.getJSONObject(i);
sessionsfrom0.add(datesObject0.getString("session_from") + " - " +datesObject0.getString("session_to");
sessionsfrom1.add(datesObject1.getString("session_from") + " - " +datesObject1.getString("session_to");
sessionsfrom2.add(datesObject2.getString("session_from") + " - " +datesObject2.getString("session_to");
} }
This code not working correctly, as you can see that date 09-09-2018 contains further array of size 4 and and in those array there are further 5 items inside each jjson object so i want to store all this in first arraylist i.e. sessionfrom0 and then go to next date and pick all its arrays and json objects and store data in sessionfrom1 arraylist and so on.
Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
switch (key) {
case "2018-09-09":
fillSessions(datesArray, sessionsfrom0);
break;
case "2018-10-09":
fillSessions(datesArray, sessionsfrom1);
break;
....so on....
}
}
You can create a function instead of rewriting the for loop logic on each case:
void fillSessions(JSONArray jsonArray, List<String> sessionList) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
sessionList.add(datesObject.getString("session_from") + " - " +datesObject0.getString("session_to");
}
}
You can do this by using HashMap
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
HashMap<String, ArrayList<String>> map = new HashMap<>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
list.add(datesObject0.getString("session_from") + " - " + datesObject0.getString("session_to");
}
map.put(key, list);
}
Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Map<String, ArrayList<String>> map = new TreeMap<>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> tmp = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
tmp.add(datesObject.getString("session_from") + " - "+datesObject.getString("session_to"));
}
map.put(key, tmp);
}
Probably you don't have all keys inside data so using switch case is not sensitive.

Get JSONObject - Android

Here is my JSON:
{
"id": "11111",
"title": "title?",
"url": "www.example.com",
"fulltext": {
"page1": "<p>balblabba</p>",
"page2": "<p>avavaava</p>"
},
"related_articles": [
{
"id": "123",
"title": "title",
"image_name": "www.example.com/image1.png"
}
]
}
I need to put everything in Strings. I'm using this code:
String data = JSON TEXT!!!;
JSONObject jRealObject = new JSONObject(data);
String title = jRealObject.getString("title").toString();
String url = jRealObject.getString("url").toString();
String fulltext = jRealObject.getString("fulltext").toString();
String page1 = ????
String page2 = ????
jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
String relatedId = jRealObject.getString("id").toString();
String relatedTitle = jRealObject.getString("title").toString();
String relatedImage = jRealObject.getString("image_name").toString();
}
I'm getting everything, But I want to split "fultext" into two variables. but I don't know how can I get "page1" and "page2".
Here in your response "fulltext" is another Jsonobject use below code to get other data.
JSONObject fulltextobj = jRealObject.getJSONObject("fulltext");
String page1 = fulltextobj.getString("page1");
String page2 = fulltextobj.getString("page2");
JSONObject obj = jRealObject.getJSONObject("fulltext");
String var1 = obj.getString("page1");
String var2 = obj.getString("page2");
EDIT: You have a JSONObject nested into another JSONObject. fulltext is not a String, is a JSONObject indeed, so you have to get a JSONObject from parent
Try this way,hope this will help you to solve your problem.
try{
JSONObject jsonObject = new JSONObject("{\"id\":\"11111\",\"title\":\"title?\",\"url\":\"www.example.com\",\"fulltext\":{\"page1\":\"<p>balblabba</p>\",\"page2\":\"<p>avavaava</p>\"},\"related_articles\":[{\"id\":\"123\",\"title\":\"title\",\"image_name\":\"www.example.com/image1.png\"}]}");
HashMap<String,Object> responseMap = new HashMap<String, Object>();
ArrayList<HashMap<String,String>> articleList = new ArrayList<HashMap<String, String>>();
responseMap.put("id",jsonObject.getString("id"));
responseMap.put("title",jsonObject.getString("title"));
responseMap.put("url",jsonObject.getString("url"));
JSONObject fullTextJsonObject = jsonObject.getJSONObject("fulltext");
responseMap.put("page1",fullTextJsonObject.getString("page1"));
responseMap.put("page2",fullTextJsonObject.getString("page2"));
JSONArray relatedArticleJsonArray = jsonObject.getJSONArray("related_articles");
for(int i=0;i<relatedArticleJsonArray.length();i++){
HashMap<String,String> articleRow = new HashMap<String, String>();
articleRow.put("id", relatedArticleJsonArray.getJSONObject(i).getString("id"));
articleRow.put("title", relatedArticleJsonArray.getJSONObject(i).getString("title"));
articleRow.put("image_name", relatedArticleJsonArray.getJSONObject(i).getString("image_name"));
articleList.add(articleRow);
}
responseMap.put("related_articles",articleList);
System.out.print("id : "+responseMap.get("id").toString());
System.out.print("title : "+responseMap.get("title").toString());
System.out.print("url : "+responseMap.get("url").toString());
System.out.print("page1 : "+responseMap.get("page1").toString());
System.out.print("page2 : "+responseMap.get("page2").toString());
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>)responseMap.get("related_articles");
for (HashMap<String,String> row : list){
System.out.print("id : "+row.get("id"));
System.out.print("title : "+row.get("title"));
System.out.print("image_name : "+row.get("image_name"));
}
}catch (Throwable e){
e.printStackTrace();
}
You are making string again toString which having no sense. please do some modification in your code .I have also done changes that you requrie.
String data = JSON TEXT!!!;
JSONObject jRealObject = new JSONObject(data);
String title = jRealObject.getString("title");
String url = jRealObject.getString("url");
String fulltext = jRealObject.getString("fulltext");
JSONObject obj = jRealObject.getJSONObject("fulltext");
String strPage1 = obj.getString("page1");
String strPage2 = obj.getString("page2");
jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
String relatedId = jRealObject.getString("id");
String relatedTitle = jRealObject.getString("title");
String relatedImage = jRealObject.getString("image_name");
}

can't fill array NewsData[] NewsData_data

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

Categories

Resources