2016-05-15 55 views
0

我已经建立时,我显示数据从URL这样从使用JSON数组请求的URL获取数据的应用程序:显示从URL数据到列表视图

it is like this

如何可以显示此数据在一个列表视图?这里是我的代码:

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", "[email protected]"); 
      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 
+1

你到底需要什么帮助?你已经尝试了什么?你的代码中没有提到ListView。 – Egor

+0

我想要像那样的建议,应该为列表视图还是其他活动创建自定义布局?然后我应该在哪里声明arraylist,我怎么可以在ArrayList中显示url来显示它在列表视图 –

+0

恐怕你的问题太广泛了。请搜索文章和教程,解释如何实现您需要的功能,如果您有更具体的问题,请返回。 – Egor

回答

0

您的回答是这样的:

[ 
    { 
    "name": "Ravi Tamada", 
    "email": "[email protected]", 
    "phone": { 
     "home": "08947 000000", 
     "mobile": "9999999999" 
    } 
    }, 
    { 
    "name": "Tommy", 
    "email": "[email protected]", 
    "phone": { 
     "home": "08946 000000", 
     "mobile": "0000000000" 
    } 
    } 
] 

这是JSON数组。你可以这样解析它:

创建一个java对象类。您的类是这样的:

电话号码实体是在这里:

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

现在您拥有yourList中的用户对象列表。下一阶段是创建一个ListView并初始化它。创建一个适配器,设置它的项目布局并使其项目的数据无效。

假设你的ListView是这样的:

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

和您的列表项的行这样的:刚

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

} 

现在你:

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

现在你的适配器会喜欢这个请拨打onResponse()回拨

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

编辑:为什么Java对象

你有一个JSON数组。它的单个对象是这样的:

{ 
     "name": "Ravi Tamada", 
     "email": "[email protected]", 
     "phone": { 
      "home": "08947 000000", 
      "mobile": "9999999999" 
     } 
     } 

在这里,它是一个JSON对象,它包含字符串的和标签的是“名”,“电子邮件”以及JSON对象标签“手机”。

所以这里这个对象包含一些字符串和一个json对象名称“phone”。

从前面的讨论中,我创造了它的标签的使用这种方式初始化的Java对象名称PhoneObject

@SerializedName("home") 
    public String home; 

现在,“手机”的标签是主要对象。所以我创建了UserObject并在该对象中初始化了PhoneObject

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

一切都完成了。如果需要更多信息,请访问here

+0

非常感谢你看起来像工作,但我有点困惑在Java对象类我如何创建?我的意思是在我的jsonr equest活动中写入该代码,还是应该为它创建新的Java类? –

+0

@Ali,我编辑了我的答案。请检查一下。 –

+0

我明白一切,但在java对象类困惑,我怎么能创建它?它给我一个错误,什么是Gson和类型的令牌? –

0

你有为此编写一些代码。

  • 解析JSON响应并创建对象(也可以使用HashMap)。
  • 在xml中创建布局文件以显示列表视图的项目。
  • 创建一个自定义的适配器类并膨胀xml布局,获取视图并将值设置为视图。
  • 将适配器设置为您的列表视图。

您可以帮助从下面的链接:

http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

http://www.vogella.com/tutorials/AndroidListView/article.html