我创建了一个应用程序,当我从URL显示数据时,使用JSON数组请求从URL获取数据,如下所示:
如何在列表视图中显示此数据?这是我的代码:
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;
}
}
}
这是我正在使用的网址
http://api.androidhive.info/volley/person_array.json
答案 0 :(得分:0)
您可以使用:
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
ListView listView = (ListView) findViewById(R.id.lvItems);
listView.setAdapter(itemsAdapter);
有用的链接:https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView
答案 1 :(得分:0)
你必须为此编写一些代码。
您可以从以下链接中获取帮助:
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
http://www.vogella.com/tutorials/AndroidListView/article.html
答案 2 :(得分:0)
您的回答是这样的:
object
这是json数组。你可以用这种方式解析它:
创建一个java对象类。你的班级是这样的:
您的电话实体在此处:
[
{
"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"
}
}
]
您的用户对象是:
import com.google.gson.annotations.SerializedName;
public class PhoneObject{
@SerializedName("home")
public String home;
@SerializedName("mobile")
public String mobile;
}
现在在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();
}
}
回调中使用以下代码行:
onResponse
现在你在Type listType = new TypeToken<List<UserObject>>() {}.getType();
List<UserObject> yourList = new Gson().fromJson(response.toString(), listType);
中有了UserObject List。下一步是创建一个ListView并初始化它。创建一个适配器,设置它的项目布局并使其项目的数据无效。
假设你的ListView是这样的:
yourList
和您的列表项行如下:
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#555"
android:dividerHeight="1dp"
android:listSelector="#000" />
现在你的适配器会喜欢这个:
<?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>
现在,您只需在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;
}
}
回拨
onResponse()
编辑:为什么选择Java对象
你有一个json数组。它的个人对象是这样的:
CustomListAdapter adapter = new CustomListAdapter(this, yourList);
listView.setAdapter(adapter);
这里,它是一个json对象,它包含字符串,标签是“name”,“email”和Json Object标签“phone”。
所以这里这个对象包含一些字符串和一个json对象名称“phone”。
从前面的讨论中,我创建了一个Java对象名{
"name": "Ravi Tamada",
"email": "ravi8x@gmail.com",
"phone": {
"home": "08947 000000",
"mobile": "9999999999"
}
}
,它的标签是用这种方式初始化的:
PhoneObject
现在“phone”标签位于主对象中。所以我创建了@SerializedName("home")
public String home;
并在该对象中初始化了UserObject
。
注意:你必须实现json结构,之后你必须开始创建java对象。
一切都完成了。如果需要更多信息,请访问here