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
Related
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";
}
}
I want to get one array from PHP that one of the fileds is an array.
How can get basket's data with jsonArray and jsonObject ?
(In the code below, the basket is an array that contains 5 parameters).
It's my array:
[{"orderCode":11514,"orderDate":"2017/05/21","orderPrice":"19200","fullName":"Jack","address":"addr 1","cellphone":"09151515730","basket":[{"b_qty":"4","pid":"8","b_price":"9500","b_discount":"10","title":"obj1"}]
Edit
String b_price ="";
String b_discount="";
String b_qty ="";
String title= "";
String pid="";
try
{
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String orderCode = object.getString("orderCode");
String orderDate = object.getString("orderDate");
String orderPrice = object.getString("orderPrice");
String fullName = object.getString("fullName");
String address = object.getString("address");
String cellphone = object.getString("cellphone");
JSONArray orderBasket = object.getJSONArray("basket");
for (int j = 0; j < orderBasket.length(); j++){
JSONObject object1 = orderBasket.getJSONObject(j);
b_qty = object1.getString("b_qty");
pid = object1.getString("pid");
b_price = object1.getString("b_price");
b_discount = object1.getString("b_discount");
title = object1.getString("title");
}
CustomOrderList customOrderList = new CustomOrderList(getApplicationContext());
customOrderList.orderCode.setText(orderCode);
customOrderList.orderDate.setText(orderDate);
customOrderList.orderTotalPrice.setText(orderPrice);
customOrderList.orderFullName.setText(fullName);
customOrderList.orderAddress.setText(address);
customOrderList.orderCellphone.setText(cellphone);
customOrderList.basketPrice.setText(b_price);
customOrderList.basketDiscount.setText(b_discount);
customOrderList.basketTitle.setText(title);
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearOrders.addView(customOrderList);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String orderCode = object.getString("orderCode");
String orderDate = object.getString("orderDate");
String orderPrice = object.getString("orderPrice");
String fullName = object.getString("fullName");
String address = object.getString("address");
String cellphone = object.getString("cellphone");
//Now orderBasket is jsonArray
JSONArray orderBasket = object.getJSONArray("basket");
// So fetch all objects from orderBasket array
for (int j = 0; j < orderBasket.length(); j++){
JSONObject objectbsk = orderBasket.getJSONObject(j);
String b_qty = objectbsk.getString("b_qty");
String pid = objectbsk.getString("pid");
String b_price = objectbsk.getString("b_price");
String b_discount = objectbsk.getString("b_discount");
String title = objectbsk.getString("title");
// Create a orderBasket list for Basket with these keys also as you have created for CustomOrderList and use it
}
CustomOrderList customOrderList = new CustomOrderList(getApplicationContext());
customOrderList.orderCode.setText(orderCode);
customOrderList.orderDate.setText(orderDate);
customOrderList.orderTotalPrice.setText(orderPrice);
customOrderList.orderFullName.setText(fullName);
customOrderList.orderAddress.setText(address);
customOrderList.orderCellphone.setText(cellphone);
customOrderList.orderBasket.setText(orderBasket);
// here you can't do set text since it's jsonarray. So use basketlist to show the data`
layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearOrders.addView(customOrderList);
}
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");
}
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
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);