Chaahid Ali Chaahid Ali - 2 years ago 201
Java Question

Displaying data from URL into listview

I have created an app which fetches data from a URL using a JSON array request when I display the data from URL like this:

it is like this

how can I show this data in a listview? Here is my code:

public class JsonRequestActivity extends Activity implements OnClickListener {

private String TAG = JsonRequestActivity.class.getSimpleName();
private Button btnJsonObj, btnJsonArray;
private TextView msgResponse;
private ProgressDialog pDialog;

// These tags will be used to cancel the requests
private String tag_json_obj = "jobj_req", tag_json_arry = "jarray_req";

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

btnJsonObj = (Button) findViewById(R.id.btnJsonObj);
btnJsonArray = (Button) findViewById(R.id.btnJsonArray);
msgResponse = (TextView) findViewById(R.id.msgResponse);

pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);

btnJsonObj.setOnClickListener(this);
btnJsonArray.setOnClickListener(this);
}

private void showProgressDialog() {
if (!pDialog.isShowing())
pDialog.show();
}

private void hideProgressDialog() {
if (pDialog.isShowing())
pDialog.hide();
}

/**
* Making json object request
* */
private void makeJsonObjReq() {
showProgressDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Const.URL_JSON_OBJECT, null,
new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {

/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}

@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Androidhive");
params.put("email", "abc@androidhive.info");
params.put("pass", "password123");

return params;
}

};

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);

// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}

/**
* Making json array request
* */
private void makeJsonArryReq() {
showProgressDialog();
JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(req,
tag_json_arry);

// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_arry);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnJsonObj:
makeJsonObjReq();
break;
case R.id.btnJsonArray:
makeJsonArryReq();
break;
}

}


}

And this is the URL I am using

http://api.androidhive.info/volley/person_array.json

Answer Source

Your response is like this:

[
  {
    "name": "Ravi Tamada",
    "email": "ravi8x@gmail.com",
    "phone": {
      "home": "08947 000000",
      "mobile": "9999999999"
    }
  },
  {
    "name": "Tommy",
    "email": "tommy@gmail.com",
    "phone": {
      "home": "08946 000000",
      "mobile": "0000000000"
    }
  }
]

Here it is json array. You can parse it this way:

Create a java object class. Your class is like this:

Your Phone Entity is here:

import com.google.gson.annotations.SerializedName;
public class PhoneObject{
@SerializedName("home")
public String home;
@SerializedName("mobile")
 public String mobile;
}

Your User object is it:

import com.google.gson.annotations.SerializedName;
public class UserObject{
@SerializedName("name")
public String name;

@SerializedName("email")
public String email;

@SerializedName("phone")
public PhoneObject phone;

public UserObject(){
phone=new Phone();
}

}

Now in your onResponse callback use this line of code:

Type listType = new TypeToken<List<UserObject>>() {}.getType();
List<UserObject> yourList = new Gson().fromJson(response.toString(), listType);

Now you have UserObject List in yourList. Next stage is create a ListView and initialize it. Create an adapter , set it's item layout and invalidate data of it's item.

Suppose your ListView is like this:

<ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#555"
        android:dividerHeight="1dp"
        android:listSelector="#000" />

and your list item row like this:

<?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="wrap_content"
    android:background="#fff"
    android:padding="8dp" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textStyle="bold" />

</RelativeLayout>

Now Your Adapter will like this:

public class CustomListAdapter extends BaseAdapter {
    private Context activity;
    private LayoutInflater inflater;
    private List<UserObject> items;

    public CustomListAdapter(Context activity, List<UserObject> items) {
        this.activity = activity;
        this.items = items;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int location) {
        return items.get(location);
    }

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

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

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);


        TextView name = (TextView) convertView.findViewById(R.id.name);

        // getting movie data for the row
        UserObject m = items.get(position);

        name.setText(m.name);

        return convertView;
    }

}

Now you just call this way in onResponse() callback

CustomListAdapter adapter = new CustomListAdapter(this, yourList);
        listView.setAdapter(adapter);

Edit: Why Java Object

You have a json Array. It's individual object is like this:

{
        "name": "Ravi Tamada",
        "email": "ravi8x@gmail.com",
        "phone": {
          "home": "08947 000000",
          "mobile": "9999999999"
        }
      }

Here, it is a json object, it contains string's and tag's are "name", 'email', and an Json Object tag "phone".

So here this object contains some string and a json object name "phone".

From previous discussion, I created a Java Object name PhoneObject it's tag's are initialized using this way:

@SerializedName("home")
    public String home;

Now "phone" tag is in main Object. So i created UserObject and initialized PhoneObject in that object.

Note: You have to realize the json structure and after that you have to start creating the java object.

All are done. If need more information visit here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download