将数据从URL显示到列表视图 [英] Displaying data from URL into listview

查看:59
本文介绍了将数据从URL显示到列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个应用程序,当我从URL显示数据时,使用JSON数组请求从URL获取数据.

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:

如何在列表视图中显示此数据?这是我的代码:

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;
    }

}

}

这是我正在使用的URL

And this is the URL I am using

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

推荐答案

您的回答是这样的:

[
  {
    "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"
    }
  }
]

这里是json数组.您可以通过以下方式对其进行解析:

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

创建一个Java对象类.您的课程是这样的:

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

您的电话实体在这里:

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回调中使用以下代码行:

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);

现在您在yourList中有UserObject List.下一步是创建一个ListView并将其初始化.创建一个适配器,设置其项目布局,并使该项目的数据无效.

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.

假设您的ListView是这样的:

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" />

和您的列表项行如下:

<?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;
    }

}

现在,您只需在onResponse()回调中以这种方式调用

Now you just call this way in onResponse() callback

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

为什么选择Java对象

您有一个json数组.它的单个对象是这样的:

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"
        }
      }

在这里,它是一个json对象,它包含字符串和标记,分别是"name","email"和一个Json Object标记"phone".

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

因此,此对象包含一些字符串和一个json对象名称"phone".

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

在前面的讨论中,我创建了一个Java对象名称PhoneObject,它的标签是通过以下方式初始化的:

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

@SerializedName("home")
    public String home;

现在"phone"标签在主对象中.因此,我在该对象中创建了UserObject并初始化了PhoneObject.

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

注意:,您必须实现json结构,然后必须开始创建java对象.

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

这篇关于将数据从URL显示到列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆