设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客
LUPA开源社区 首页 业界资讯 技术文摘 查看内容

Volley—简单迅捷的Android网络模块范例

2014-6-20 10:55| 发布者: joejoe0332| 查看: 6384| 评论: 0|原作者: zerob13|来自: 伯乐在线

摘要: olley 是一个提供给 Android 应用非常易用的网络库,更好的是这个库还加快了网络访问速度。本文会总览Volley库的主要功能,包括工作原理、常见工作模式以及如何使用该库从网络上并行加载缩略图到应用ListView中的流 ...

第五步: 在 activity_main.xml 中添加一个 ListView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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">
 
    <ListView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/listView"
            android:layout_alignParentTop="true" android:layout_alignParentLeft="true"/>
</RelativeLayout>


第六步: 为 ListView 的行布局新建一个“row_listview.xml”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="100dp">
 
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Large Text"
            android:id="@+id/txtTitle" android:layout_gravity="left|center_vertical"/>
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Medium Text"
            android:id="@+id/txtDesc" android:layout_gravity="left|center_vertical" android:textColor="#929292"
            android:minLines="2" android:ellipsize="end" android:maxLines="2"/>
    <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="Small Text"
            android:id="@+id/txtDate" android:layout_gravity="left|center_vertical" android:textColor="#d6d6d6"/>
</LinearLayout>


第七步: 把如下代码添加到 MainActivity.java 文件中
通过 Volley 去请求网络需要分三步。
1、通过 Volley 类来新建一个新的请求队列:

1
2
3
4
5
private RequestQueue mRequestQueue;
.
.
.
mRequestQueue = Volley.newRequestQueue(this);


2、新建一个 JsonObjectRequest 对象,并且设置好各项具体参数,比如url、http method以及监听结果的listeners

1
2
3
4
5
6
7
8
9
10
11
12
13
14
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.i(TAG,response.toString());
                parseJSON(response);
                va.notifyDataSetChanged();
                pd.dismiss();
;            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG,error.getMessage());
            }
        });


3、将JsonObjectRequest添加到 JsonObjectRequest中:

1
mRequestQueue.add(jr);

下面的代码是带有Adapter,以及Model的完整代码,为了方便阅读我把所有的类都放到了一个Java文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package com.kpbird.volleytest;
 
import android.app.ProgressDialog;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
 
import java.util.ArrayList;
 
public class MainActivity extends Activity {
 
    private String TAG = this.getClass().getSimpleName();
    private ListView lstView;
    private RequestQueue mRequestQueue;
    private ArrayList<NewsModel> arrNews ;
    private LayoutInflater lf;
    private VolleyAdapter va;
    private ProgressDialog pd;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lf = LayoutInflater.from(this);
 
 
        arrNews = new ArrayList<NewsModel>();
        va = new VolleyAdapter();
 
        lstView = (ListView) findViewById(R.id.listView);
        lstView.setAdapter(va);
        mRequestQueue =  Volley.newRequestQueue(this);
        String url = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json";
        pd = ProgressDialog.show(this,"Please Wait...","Please Wait...");
        try{
            Thread.sleep(2000);
        }catch(Exception e){
 
            }
        JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.i(TAG,response.toString());
                parseJSON(response);
                va.notifyDataSetChanged();
                pd.dismiss();
;            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG,error.getMessage());
            }
        });
        mRequestQueue.add(jr);
 
 
 
    }
 
    private void parseJSON(JSONObject json){
        try{
            JSONObject value = json.getJSONObject("value");
            JSONArray items = value.getJSONArray("items");
            for(int i=0;i<items.length();i++){
 
                    JSONObject item = items.getJSONObject(i);
                    NewsModel nm = new NewsModel();
                    nm.setTitle(item.optString("title"));
                    nm.setDescription(item.optString("description"));
                    nm.setLink(item.optString("link"));
                    nm.setPubDate(item.optString("pubDate"));
                    arrNews.add(nm);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
 
 
    }
 
 
    class NewsModel{
        private String title;
        private String link;
        private String description;
        private String pubDate;
 
        void setTitle(String title) {
            this.title = title;
        }
 
        void setLink(String link) {
            this.link = link;
        }
 
        void setDescription(String description) {
            this.description = description;
        }
 
        void setPubDate(String pubDate) {
            this.pubDate = pubDate;
        }
 
        String getLink() {
            return link;
        }
 
        String getDescription() {
            return description;
        }
 
        String getPubDate() {
            return pubDate;
        }
 
        String getTitle() {
 
            return title;
        }
    }
 
 
    class VolleyAdapter extends BaseAdapter{
 
        @Override
        public int getCount() {
            return arrNews.size();
        }
 
        @Override
        public Object getItem(int i) {
            return arrNews.get(i);
        }
 
        @Override
        public long getItemId(int i) {
            return 0;
        }
 
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder vh ;
           if(view == null){
               vh = new ViewHolder();
               view = lf.inflate(R.layout.row_listview,null);
               vh.tvTitle = (TextView) view.findViewById(R.id.txtTitle);
               vh.tvDesc = (TextView) view.findViewById(R.id.txtDesc);
               vh.tvDate = (TextView) view.findViewById(R.id.txtDate);
               view.setTag(vh);
          }
            else{
               vh = (ViewHolder) view.getTag();
           }
 
            NewsModel nm = arrNews.get(i);
            vh.tvTitle.setText(nm.getTitle());
            vh.tvDesc.setText(nm.getDescription());
            vh.tvDate.setText(nm.getPubDate());
            return view;
        }
 
         class  ViewHolder{
            TextView tvTitle;
             TextView tvDesc;
             TextView tvDate;
 
        }
 
    }
}

你也可以从 Github 上获取完整代码: https://github.com/kpbird/volley-example


原文链接: kpbird   翻译: 伯乐在线 - zerob13
译文链接: http://blog.jobbole.com/71078/

酷毙

雷人

鲜花

鸡蛋

漂亮
  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部