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();
Related
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");
}
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
here my jsonArray data like:
[{"LeadId":4,
"CoreLeadId":0,
"CompanyId":7,
"AccountNo":"5675",
"ScheduleOn":"2015-05-11T00:00:00"},
{"LeadId":7,
"CoreLeadId":2,
"CompanyId":8,
"AccountNo":"sample string 4",
"ScheduleOn":"2015-12-01T15:04:23.217"}]
i want to sort by dateandtime(ScheduleOn) and put into listview. below i side i send snnipt of my code where i set adapter. can we sort into listItemService. Please help me.
JSONArray jsonArray = dpsFunctionFlow.getAllServiceDetail("1");
listItemService = new Gson().fromJson(jsonArray.toString(),
new TypeToken<List<AppointmentInfoDto>>() {
}.getType());
mAdapter = new AdapterAppointment(getActivity(), listItemService);
listView.setAdapter(mAdapter);
You should be able to use Collections.sort(...) passing in a Comparator that will compare 2 AppointmentInfoDto objects.
Collections.sort(listItemService, new Comparator<AppointmentInfoDto>() {
#Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r) {
// Compare l.ScheduleOn and r.ScheduleOn
}
}
/// Sort JSON By any Key for date
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return CompareString1.compareTo(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
// _Sort JSON for any String Key value.........
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return isCase ? CompareString1.compareTo(CompareString2) : CompareString1.compareToIgnoreCase(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
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);
}
}
I've got a json object, which is being collected into a function as string.
It contains array
{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P.
REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH
SINGH"}
and here is the android code
public void func4(View view)throws Exception
{
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("pLat", "SELECT officer_name FROM iwmp_officer");
client.post("http://10.0.2.2/conc5.php", rp, new AsyncHttpResponseHandler() {
public final void onSuccess(String response) {
// handle your response here
ArrayList<String> User_List = new ArrayList<String>();
try {
/* here I need output in an array,
and only names not the "officer_name" */
} catch (Exception e) {
tx.setText((CharSequence) e);
}
//tx.setText(User_List.get(1));
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
tx.setText(response);
}
});
}
The output I've shown above is in String, need to get it in array. Please help!
If the output you got is something like this.
String outputJson=[{"officer_name":"V. M. ARORA"}{"officer_name":"Dr. C. P. REDDY"}{"officer_name":"ARTI CHOWDHARY"}{"officer_name":"JAGDISH SINGH"}]
Then its a JSON Array.
You can parse it as
JsonArray array=new JsonArray(outputJson);
Then loop this json array using
for(JsonObject jsonObj in array){
String officerName=[jsonObj getString("officer_name");
}
You can use something like above The mentioned code is not correct syntactically but yes conceptually correct. You can go ahead with this.
List < String > ls = new ArrayList< String >();
JSONArray array = new JSONArray( response );
for (int i = 0; i < array.length() ; i++ ) {
JSONObject obj = array.getJSONObject(Integer.toString(i));
ls.add(obj.getString("officer_name"));
}
This would work
try {
JSONArray array= new JSONArray(response);
//array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
//JSONObject obj = response.getJSONArray(i);
JSONObject jsonLineItem = (JSONObject) array.getJSONObject(i);
String name_fd = jsonLineItem.getString("officer_name");
User_List.add(jsonLineItem.getString("officer_name"));
Log.d("JSONArray", name_fd+" " +name_fd);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tx.setText( e.toString());
}