I have to fetch text via json in url .
The hierarchy is given below :
object>array>object>array>object.
I want to get text with this code .But I am getting error :org.json.JSONException: No value for text
Below is the code :-
public class ListViewActivity extends Activity {
// Log tag
private static final String TAG = ListViewActivity.class.getSimpleName();
// change here url of server api
private static final String url = "http://2e9b8f52.ngrok.io/api/v1/restaurants?per_page=5&km=1&location=true&lat=19.0558306414&long=72.8339840099";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = movieList.get(position);
Intent intent = new Intent(ListViewActivity.this, SecondActivity.class);
intent.putExtra("name", movie.getName());
intent.putExtra("average_ratings", movie.getAverage_ratings());
intent.putExtra("full_address", movie.getAddress());
intent.putExtra("image_url", movie.getThumbnailUrl());
intent.putExtra("cuisine",movie.getCuisine());
intent.putExtra("cost",movie.getCost());
startActivity(intent);
}
});
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Please Keep patience.Its loading...");
pDialog.show();
// Creating volley request obj
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray
restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
//movie.setThumbnailUrl(obj.getString("image"));
movie.setThumbnailUrl(obj.getString("org_image_url"));
movie.setAverage_ratings(obj.getString("average_ratings"));
movie.setCuisine(obj.getString("cuisine"));
movie.setAddress(obj.getJSONObject("address").getString("area"));
// movie.setAddress(obj.getJSONObject("address").getString("full_address"));
movie.setCost(obj.getString("cost"));
movie.setDistance( obj.getDouble("distance"));
movie.settext(obj.getString("text"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
I am attaching snapshot of json data. In the snapshot we can see the color "Text=15% discount on bill " i have to access .
try {
String yourresponseString ="";// this string refer to your api response
JSONObject jsonObject = new JSONObject(yourresponseString);
JSONArray objJsonArray = new JSONArray(jsonObject.getString("restaurants"));
for (int i = 0; i < objJsonArray.length(); i++) {
JSONArray objInnerJsonArray = objJsonArray.getJSONObject(i).getJSONArray("restaurant_offers");
for (int j = 0; j < objInnerJsonArray.length(); j++) {
//Here you can acess youe bill discount value
JSONObject objInnerJSONObject = objInnerJsonArray.getJSONObject(j);
System.out.println("Discount==>" + objInnerJSONObject.getString("text"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You can parse like this.And using this classes you can parse any type of hierarchy.
JSONArray restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
JSONArray textJSONArray= obj.getJSONArray("restaurant_offers");
for (int j = 0; j < textJSONArray.length(); j++) {
JSONObject txtobj =textJSONArray.getJSONObject(i);
movie.settext(txtobj .getString("text"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
try this code restaurant_offers is a JSONArray so you can parse like this
You can parse like this
JSONObject apiResponseJsonObject= // Your API Response
try {
JSONArray restaurantJSONArray = apiResponseJsonObject.getJSONArray("restaurants");
// you can get any text from an object like this
restaurantJSONArray.getJSONObject(index).getString("name");
restaurantJSONArray.getJSONObject(index).getString("cost"); // Like this
//If you want to access phone numbers of specific object
JSONArray phoneJSONArray=restaurantJSONArray.getJSONObject(index).getJSONArray("phone_numbers");
// And you can get specific data from phoneNumber like this
phoneJSONArray.getJSONObject(phoneNumberIndex).getString("number");
//TO get Address, you can use like this
JSONObject addressJSONObject=restaurantJSONArray.getJSONObject(index).getJSONObject("address");
//Like this you can parse whatever you want.
} catch (JSONException e) {
e.printStackTrace();
}
You must change the for loop content like this
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
JSONArray restauranstOffersJSONArray = obj.getJSONArray("restaurants_offers");
for (int i = 0; i < restauranstOffersJSONArray.length(); i++) {
JSONObject offersObj = restauranstOffersJSONArray.get(i);
String text = offersObj.getString("text");
}
Related
I tried doing it multiple times using Volley library.
Link for JSON values: here
My android code to parse the values: here
public class GetUSGSjson extends AppCompatActivity
{
GridView jsonGridView;
ListView jsonListView;
Button jsonGetBtn;
RequestQueue USGSrequestqueue;
String USGSurl = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmag=6&limit=10";
ArrayList<String> mArrayList;
ArrayList<String>FK;
JsonObjectRequest USGSjsonObjectReq;
JSONObject _properties_;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.json_data);
jsonGridView = (GridView) findViewById(R.id.jsonGridView);
jsonGetBtn = (Button) findViewById(R.id.jsonGetBtn);
USGSrequestqueue = Volley.newRequestQueue(this);
mArrayList = new ArrayList<>();
FK = new ArrayList<>();
jsonGridView.setVisibility(View.GONE);
}
OnCllick of the button
public void USGSgetData(View view)
{
jsonGridView.setVisibility(View.VISIBLE);
USGSjsonObjectReq = new JsonObjectRequest(Request.Method.GET,USGSurl,null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try {
JSONObject _features_ = response.getJSONObject("features");
JSONArray _f_ = response.getJSONArray("features");
for (int x = 0; x < _f_.length(); x++)
{
JSONObject currentFeature = _f_.getJSONObject(x);
_properties_ = currentFeature.getJSONObject("properties"); //JsonObject
double mag = _properties_.getDouble("mag");
long time = _properties_.getLong("time");
String place = _properties_.getString("place");
mArrayList.add(String.valueOf(mag));
mArrayList.add(String.valueOf(time));
mArrayList.add(place);
ArrayAdapter VarrayAdapter = new ArrayAdapter<>(GetUSGSjson.this
,android.R.layout.simple_list_item_1, mArrayList);
jsonGridView.setAdapter(VarrayAdapter);
} catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(GetUSGSjson.this, "Exception: "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(GetUSGSjson.this, "onErrorResponse: "+error.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
USGSrequestqueue.add(USGSjsonObjectReq);
}
}
Try this,
try {
JSONArray arr_features=response.getJSONArray("features");
for(int i=0;i<arr_features.length();i++)
{
JSONObject obj=arr_features.getJSONObject(i);
String type=obj.getString("type");
JSONObject obj_properties=obj.getJSONObject("properties");
String mag=obj_properties.getString("mag");
String place=obj_properties.getString("place");
String time=obj_properties.getString("time");
String updated=obj_properties.getString("updated");
}
} catch (JSONException e) {
e.printStackTrace();
}
I found this way to solve my own problem
Remember that the "mag" is in double form "place" & "type" are in String form & "time" is a Unix time it's in long form.
try {
JSONArray _f_ = response.getJSONArray("features");
for (int x = 0; x < _f_.length(); x++)
{
JSONObject currentFeature = _f_.getJSONObject(x);
_properties_ = currentFeature.getJSONObject("properties"); //JsonObject
double mag = _properties_.getDouble("mag");
long time = _properties_.getLong("time");
String place = _properties_.getString("place");
String type = _properties_.getString("type");
// To add this on to ArrayList.
mArrayList.add("Place: "+place+"\n");
mArrayList.add("\nMagnitude: " + String.valueOf(mag)+"\n");
mArrayList.add("\nTime: " + String.valueOf(newTime)+"\n");
mArrayList.add("\nType: " + type+"\n");
}
I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})
I am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray
In my android application I'm receiving a JSONArray and I'm parsing it and storing it in a arraylist and appending that to listview but I'm facing an error entire list is showing in a single list item.but I'm receiving 4 items.This is all what I did.
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("topicsJSON",composeJSON());
client.post("http://www.example.com/load_topics.php",params,newAsyncHttpResponseHandler()
{
public void onSuccess(String response)
{
Gson gson = new GsonBuilder().create();
try
{
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
load_data();
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,String content)
{
if (statusCode == 404)
{
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
else if (statusCode == 500)
{
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
private String composeJSON() {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> check_in_List;
check_in_List = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("subject_code",received_subject_code);
check_in_List.add(map);
Gson gson = new GsonBuilder().create();
return gson.toJson(check_in_List);
}
public void load_data()
{
ArrayAdapter<String> phy = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
l1.setAdapter(phy);
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String pos = (String) l1.getItemAtPosition(position);
});
}
I'm facing an error entire list is showing in a single list item.but
I'm receiving 4 items
Because calling load_data(); inside for-loop which is used for getting data from JSONArray in ArrayList
Move load_data(); outside for-loop to show each item in separate row in ListView
don't every time add list item, create adapter,
set adapter one time with empty list.
after end parse Jsonarray and add data, adapter.notifyDataSetChanged();
Replace this:
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
load_data();
}
Via
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
}
load_data();
Follow this:
private List<String> list = new ArrayList<String>();
try{
JSONArray arr = json.getJSONArray("JSONArray Name");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
list.add(c.getString("Object Name"));
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
load_data();
In my android application I'm receiving an JSONArray now I should parse that and should show the data in the listview. I tried it and it is showing '{}' in all list items in listview.Cannot understand why its showing like that.
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("topicsJSON",composeJSON());
client.post("http://www.example.com/LSM_Sci-Mat/load_topics.php",params,new AsyncHttpResponseHandler()
{
public void onSuccess(String response)
{
Gson gson = new GsonBuilder().create();
try
{
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++)
{
JSONObject jsonObject = new JSONObject();
list.add(jsonObject.toString());
load_data();
//Toast.makeText(getApplicationContext(), "Element ==> "+list, 5000).show();
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,String content)
{
if (statusCode == 404)
{
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
else if (statusCode == 500)
{
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
private String composeJSON() {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> check_in_List;
check_in_List = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("subject_code",received_subject_code);
check_in_List.add(map);
Gson gson = new GsonBuilder().create();
return gson.toJson(check_in_List);
}
public void load_data()
{
ArrayAdapter<String> phy = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
l1.setAdapter(phy);
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
//String pos = (String) l1.getItemAtPosition(position);
int topic_index = position + 1;
String pos = String.valueOf(topic_index);
});
}
The error is due to these lines :
JSONObject jsonObject = new JSONObject();
list.add(jsonObject.toString());
Here you are not initializing the JSONObject from JSONArray , but you are creating a new one.
The solution could be to initialize it from JSONArray :
JSONObject jsonObject = arr.getJSONObject(i)
list.add(jsonObject.toString());
For parsing thing In your JSON nested JSONArrays are given.
you can try following code to parse it:
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONArray internalJSONArray=arr.getJSONArray(i);
for (int j=0;j<internalJSONArray.length();j++){
String data=internalJSONArray.getString(j);
System.out.println(data);
}
}