Simple Parse JSON from Url on Android and Display in Listview

Simple parse JSON from URL on Android and display in listview

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following


Async task has three primary methods:

  1. onPreExecute() - most commonly used for setting up and starting a progress dialog

  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

class MyAsyncTask extends AsyncTask<String, String, Void> {

private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";

protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}

Then we need to set up the connection and how we want to handle the response:

    @Override
protected Void doInBackground(String... params) {

String url_select = "http://yoururlhere.com";

ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

try {
// Set up HTTP post

// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();

String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}

inputStream.close();
result = sBuilder.toString();

} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
} // protected Void doInBackground(String... params)

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
for(i=0; i < jArray.length(); i++) {

JSONObject jObject = jArray.getJSONObject(i);

String name = jObject.getString("name");
String tab1_text = jObject.getString("tab1_text");
int active = jObject.getInt("active");

} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

ANDROID, Parse JSON data from a web server and display on ListView

I happen to encounter similar problem. Here is the code that help me find resolution. Hope this will help you.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">


<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SEND GET REQUEST"
android:id="@+id/sendGet"
android:onClick="sendGetRequest"
android:layout_alignParentStart="true" />

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:layout_below="@+id/sendGet"
android:layout_centerHorizontal="true">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Response ....."
android:id="@+id/showOutput"
android:layout_alignEnd="@+id/scrollView"
android:layout_marginEnd="34dp" />

</ScrollView>

</RelativeLayout>

MainActivity.java

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.appindexing.Action;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

private ProgressDialog progress;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
// private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
// client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

public void sendGetRequest(View View) {
new GetClass(this).execute();
}

@Override
public void onStart() {
super.onStart();

// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
// client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.gunawardena.get_post_demo/http/host/path")
);
// AppIndex.AppIndexApi.start(client, viewAction);
}

@Override
public void onStop() {
super.onStop();

// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.gunawardena.get_post_demo/http/host/path")
);
// AppIndex.AppIndexApi.end(client, viewAction);
// client.disconnect();
}

private class GetClass extends AsyncTask<String, Void, Void> {

private final Context context;

public GetClass(Context c) {
this.context = c;
}

protected void onPreExecute() {
progress = new ProgressDialog(this.context);
progress.setMessage("Loading Get Method.....");
progress.show();
}

@Override
protected Void doInBackground(String... params) {
try {

final TextView outputView = (TextView) findViewById(R.id.showOutput);
URL url = new URL("https://dvlasearch.appspot.com/DvlaSearch?licencePlate=mt09nks&apikey=DvlaSearchDemoAccount");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");

int responseCode = connection.getResponseCode();

final StringBuilder output = new StringBuilder("Request URL " + url);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "GET");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while ((line = br.readLine()) != null) {
responseOutput.append(line);
}
br.close();

output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());

MainActivity.this.runOnUiThread(new Runnable() {

@Override
public void run() {
outputView.setText(output);
progress.dismiss();

}
});

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}

Output on the Emulator

Sample Image

HTH


References:

  • How to send HTTP request GET/POST in Java
  • Java HttpURLConnection Example to send HTTP GET/POST Requests
  • Android POST and GET Request using HttpURLConnection Tutorial

how to display fetched json data into listview using baseadapter

First u need t create row_listitem.xml file like:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:background="@drawable/list_selector"
android:orientation="vertical"
android:padding="5dp" >

<ImageView
android:id="@+id/iv_icon_social"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:background="@drawable/image_border"
android:src="@drawable/sms_t"
android:visibility="gone" />

<LinearLayout
android:id="@+id/thumbnail"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginRight="50dp"
android:layout_marginTop="0dp"
android:layout_toRightOf="@+id/iv_icon_social"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="5dip"
android:visibility="visible" >

<TextView
android:id="@+id/txt_ttlsm_row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="Sample text"
android:textSize="18dp"
android:textStyle="bold" />

<TextView
android:id="@+id/txt_ttlcontact_row2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp"
android:layout_marginTop="3dp"
android:paddingLeft="10dp"
android:maxEms="20"
android:maxLines="2"
android:singleLine="false"
android:ellipsize="end"
android:text="Sample text2"
android:textColor="#808080"
android:textSize="15dp"
android:textStyle="normal"
android:visibility="visible" />


</LinearLayout>

</RelativeLayout>

Now, u need to create Custom BaseAdapter like:

  public class BaseAdapter2 extends BaseAdapter {

private Activity activity;
// private ArrayList<HashMap<String, String>> data;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;

public BaseAdapter2(Activity a, ArrayList b, ArrayList bod) {
activity = a;
this.title = b;
this.notice=bod;

inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
return title.size();
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.row_listitem, null);

TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row); // title
String song = title.get(position).toString();
title2.setText(song);


TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice
String song2 = notice.get(position).toString();
title22.setText(song2);

return vi;

}

}

Now, u can set up your main activity like:

public class MainActivity extends Activity {

ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
BaseAdapter2 adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
new TheTask().execute();
}

class TheTask extends AsyncTask<Void, Void, String> {

@Override
protected String doInBackground(Void... params) {
String str = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return str;

}



@Override
protected void onPostExecute(String result) {

super.onPostExecute(result);

String response = result.toString();
try {


JSONArray new_array = new JSONArray(response);

for (int i = 0, count = new_array.length(); i < count; i++) {
try {
JSONObject jsonObject = new_array.getJSONObject(i);
title_array.add(jsonObject.getString("title").toString());
notice_array.add(jsonObject.getString("notice").toString());

} catch (JSONException e) {
e.printStackTrace();
}
}

adapter = new BaseAdapter2(MainActivity.this, title_array, notice_array);
list.setAdapter(adapter);

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// tv.setText("error2");
}

}
}

}

Parse JSON And Show In Listview Retrieve/Fetch URL Server No Data

I have updated the parsing method. Check below

public ArrayList<DemandeModel> getInfo(String response) {
ArrayList<DemandeModel> demandeModelArrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getJSONObject("status").optString("success").equals("true")) {

JSONArray dataArray = jsonObject.getJSONArray("demandes");

for (int i = 0; i < dataArray.length(); i++) {
DemandeModel playersModel = new DemandeModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playersModel.setId(dataobj.getString("id"));
playersModel.setDate(dataobj.getString("dateCreation"));
playersModel.setNom(dataobj.getString("tagDemand"));
playersModel.setDescription(dataobj.getString("descDemande"));
playersModel.setImgURL(dataobj.getString("imageUrl"));
demandeModelArrayList.add(playersModel);

}
}

} catch (JSONException e) {
e.printStackTrace();
}
return demandeModelArrayList;
}

EDIT below method is updated a bit

public boolean isSuccess(String response) {

try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getJSONObject("status").optString("success").equals("true")) {
return true;
} else {

return false;
}

} catch (JSONException e) {
e.printStackTrace();
}
return false;
}

EDIT 2

change below line

response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();

to

response = req.prepare().sendAndReadString();

Populating JSON from this link to android Listview

Continuing your class:

public class MainActivity extends Activity {

private static String url="https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Create a JSON parser Instance ----- Used JSON parser from Android
JSONParser jParser=new JSONParser();

//Getting JSON string from URL ------ Used JSON Array from Android
JSONArray json=jParser.getJSONFromUrl(url);

List<WhateverObject> yourData = new ArrayList<WhateverObject>();

try {
for(int i=0;i<json.length();i++)
{
JSONObject c=json.getJSONObject(i);// Used JSON Object from Android

//Storing each Json in a string variable
int AGE=c.getInt("age");
String NAME=c.getString("name");
String CITY=c.getString("city");
String GENDER=c.getString("Gender");
String BIRTHDATE=c.getString("birthdate");


yourData.add(new WhateverObject(NAME, CITY, GENDER, BIRTHDATE));

}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

ListView yourListView = (ListView) findViewById(R.id.itemListView);

ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);

yourListView.setAdapter(customAdapter);

}


}

adater:

public class ListAdapter extends ArrayAdapter<Item> {

public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}

private List<Item> items;

public ListAdapter(Context context, int resource, List<Item> items) {

super(context, resource, items);

this.items = items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

View v = convertView;

TextView tt = null;
TextView tt1 = null;
TextView tt2 = null;
TextView tt3 = null;
TextView tt4 = null;

if (v == null) {

LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);

tt = (TextView) v.findViewById(R.id.age);
tt1 = (TextView) v.findViewById(R.id.name);
tt2 = (TextView) v.findViewById(R.id.city);
tt3 = (TextView) v.findViewById(R.id.gender);
tt4 = (TextView) v.findViewById(R.id.birthdate);
}

Item p = items.get(position);

if (p != null) {

if (tt != null) {
tt.setText(""+p.getAge());
}
if (tt1 != null) {

tt1.setText(""+p.getName());
}
if (tt2 != null) {

tt2.setText(""+p.getCity());
}

if (tt3 != null) {

tt3.setText(""+p.getGender());
}

if (tt4 != null) {

tt4.setText(""+p.getBirthdate());
}
}



return v;

}
}

object holding data:

public class WhateverObject{
private int age;
private String name;
private String city;
private String gender;
private String birthdate;

public WhateverObject(int age, String name, String city, String gender, String birthdate){
this.age = age;
this.name = name;
this.city = city;
this.gender = gender;
this.birthdate = birthdate;
}

public int getAge(){
return this.age;
}

public String getName(){
return this.name;
}

public String getCity(){
return this.city;
}

public String getGender(){
return this.gender;
}

public String getBirthdate(){
return this.birthdate;
}
}

xml for listview item (save under itemlistrow name):

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">

<TableRow android:layout_width="fill_parent"
android:id="@+id/TableRow01"
android:layout_height="wrap_content">

<TextView
android:id="@+id/age"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="age" android:textStyle="bold"
android:gravity="left"
android:layout_weight="1"
android:typeface="monospace"
android:height="40sp"/>
</TableRow>

<TableRow android:layout_height="wrap_content"
android:layout_width="fill_parent">

<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="name"
android:layout_weight="1"
android:height="20sp"/>
</TableRow>

<TableRow android:layout_height="wrap_content"
android:layout_width="fill_parent">

<TextView
android:id="@+id/city"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="city"
android:layout_weight="1"
android:height="20sp"/>
</TableRow>

<TableRow android:layout_height="wrap_content"
android:layout_width="fill_parent">

<TextView
android:id="@+id/gender"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="city"
android:layout_weight="1"
android:height="20sp"/>
</TableRow>

<TableRow android:layout_height="wrap_content"
android:layout_width="fill_parent">

<TextView
android:id="@+id/birthdate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="city"
android:layout_weight="1"
android:height="20sp"/>
</TableRow>

</TableLayout>

Reused elements from https://stackoverflow.com/a/8166802/1276374


Simpler example:

public class MainActivity extends Activity {

private static String url="https://www.dropbox.com/s/rhk01nqlyj5gixl/jsonparsing.txt?dl=1";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Create a JSON parser Instance ----- Used JSON parser from Android
JSONParser jParser=new JSONParser();

//Getting JSON string from URL ------ Used JSON Array from Android
JSONArray json=jParser.getJSONFromUrl(url);

List<Map<String, String>> personList = new ArrayList<Map<String,String>>();

try {
for(int i=0;i<json.length();i++)
{
JSONObject c=json.getJSONObject(i);// Used JSON Object from Android

//Storing each Json in a string variable
int AGE=c.getInt("age");
String NAME=c.getString("name");
String CITY=c.getString("city");
String GENDER=c.getString("Gender");
String BIRTHDATE=c.getString("birthdate");


personList.add(createPerson(AGE, NAME, CITY, GENDER, BIRTHDATE));

}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

ListView yourListView = (ListView) findViewById(R.id.itemListView);

simpleAdpt = new SimpleAdapter(this, personList, android.R.layout.simple_list_item_1, new String[] {"person"}, new int[] {android.R.id.text1});

yourListView.setAdapter(simpleAdpt);

}

private HashMap<String, String> createPerson(int age, String name, String city, String gender, String birthdate) {
HashMap<String, String> person = new HashMap<String, String>();
person.put("person", name+" | "+age + " | "+city + " | "+gender + " | "+birthdate);
return person;
}



}

Thanks to http://www.javacodegeeks.com/2013/06/android-listview-tutorial-and-basic-example.html

how to parse a json file into a Listview with volley

Hi replace your request code like below and you will not faced crash. I have also checked in my device and now I can fill listview with array.
And ya don't forget to give permission of internet in manifest.

 StringRequest req = new StringRequest(urlJsonArry,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {

try {

ArrayList al = new ArrayList();
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.has("name")) {
al.add(jsonObject.getString("name"));
}
}

ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, al);
nameList.setAdapter(adapter);
}


Related Topics



Leave a reply



Submit