带有示例的Android Volley教程

This is android volley tutorial. Here you will learn about android volley library and how to use it.

这是android排球教程。 在这里,您将了解android volley库以及如何使用它。

What is Volley?

什么是凌空?

Volley is a network library that helps in doing network related operations like fetching image or data.

Volley是一个网络库,可帮助执行与网络相关的操作,例如获取图像或数据。

Here are some features of this library.

这是该库的一些功能。

  • Supports request queuing and prioritization

    支持请求排队和优先级

  • Effective cache management

    有效的缓存管理

  • Multiple concurrent network connections can be established

    可以建立多个并发网络连接

  • Supports request cancelling

    支持取消请求

  • No need to use asynctask as it performs all network operations asynchronously.

    无需使用asynctask,因为它异步执行所有网络操作。

带有示例的Android Volley教程

Android Volley教程 (Android Volley Tutorial)

Using volley we can fetch simple string, image or json data. Below I have given example for each of them.

使用齐射,我们可以获取简单的字符串,图像或json数据。 下面我给出了每个示例。

First we create a request; it can be string, image or json. Then create a request queue and finally add the request in the request queue.

首先,我们创建一个请求; 它可以是字符串,图像或json。 然后创建一个请求队列,最后将请求添加到请求队列中。

先决条件 (Pre-requisites)

1. Add volley support in build.gradle by adding following line under dependencies section.  After adding just sync the project.

1.通过在依赖性部分下添加以下行,在build.gradle中添加截击支持。 添加后,只需同步项目即可。

1
compile 'com.android.volley:volley:1.0.0'
1
compile 'com.android.volley:volley:1.0.0'

2. Add internet access permission in AndroidManifest.xml file.

2.在AndroidManifest.xml文件中添加Internet访问权限。

1
<uses-permission android:name="android.permission.INTERNET"/>
1
<uses-permission android : name = "android.permission.INTERNET" />

提取字符串数据 (Fetching String Data)

StringRequest class is used to create a string request. We specify the URL and then receive the string in response. Below example shows how to do this.

StringRequest类用于创建字符串请求。 我们指定URL,然后接收响应字符串。 以下示例显示了如何执行此操作。

Create an android project with package name com.androidvolleyexample and add following code in respective files.

创建一个程序包名称为com.androidvolleyexample的android项目,并在相应文件中添加以下代码。

activity_main.xml

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout 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"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:id="@+id/txt"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Fetch Data"/>
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout 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"
    android : orientation = "vertical" >
     <TextView
        android : layout_width = "match_parent"
        android : layout_height = "wrap_content"
        android : layout_marginBottom = "10dp"
        android : id = "@+id/txt" />
     <Button
        android : layout_width = "match_parent"
        android : layout_height = "wrap_content"
        android : id = "@+id/btn"
        android : text = "Fetch Data" />
</LinearLayout>

MainActivity.xml

MainActivity.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.androidvolleyexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
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.StringRequest;
import com.android.volley.toolbox.Volley;
public class MainActivity extends Activity {
    TextView txt;
    Button btn;
    String url ="https://www.thecrazyprogrammer.com/wp-content/uploads/demo.txt";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (TextView)findViewById(R.id.txt);
        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
                    @Override
                    public void onResponse(String s) {
                        txt.setText(s);
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        txt.setText("Some error occurred!!");
                    }
                });
                RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
                rQueue.add(request);
            }
        });
    }
}
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
package com . androidvolleyexample ;
import android . app . Activity ;
import android . os . Bundle ;
import android . view . View ;
import android . widget . Button ;
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 . StringRequest ;
import com . android . volley . toolbox . Volley ;
public class MainActivity extends Activity {
     TextView txt ;
     Button btn ;
     String url = "https://www.thecrazyprogrammer.com/wp-content/uploads/demo.txt" ;
     @Override
     protected void onCreate ( Bundle savedInstanceState ) {
         super . onCreate ( savedInstanceState ) ;
         setContentView ( R . layout . activity_main ) ;
         txt = ( TextView ) findViewById ( R . id . txt ) ;
         btn = ( Button ) findViewById ( R . id . btn ) ;
         btn . setOnClickListener ( new View . OnClickListener ( ) {
             @Override
             public void onClick ( View v ) {
                 StringRequest request = new StringRequest ( Request . Method . GET , url , new Response . Listener <String> ( ) {
                     @Override
                     public void onResponse ( String s ) {
                         txt . setText ( s ) ;
                     }
                 } , new Response . ErrorListener ( ) {
                     @Override
                     public void onErrorResponse ( VolleyError volleyError ) {
                         txt . setText ( "Some error occurred!!" ) ;
                     }
                 } ) ;
                 RequestQueue rQueue = Volley . newRequestQueue ( MainActivity . this ) ;
                 rQueue . add ( request ) ;
             }
         } ) ;
     }
}

Screenshot

屏幕截图

带有示例的Android Volley教程

正在撷取图片 (Fetching Image)

ImageRequest class is used to create an image request. We specify the URL and then receive the bitmap in response. Below example shows how to do this.

ImageRequest类用于创建图像请求。 我们指定URL,然后接收位图作为响应。 以下示例显示了如何执行此操作。

Create an android project with package name com.androidvolleyexample and add following code in respective files.

创建一个程序包名称为com.androidvolleyexample的android项目,并在相应文件中添加以下代码。

activity_main.xml

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout 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"
    android:orientation="vertical">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:id="@+id/img"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Fetch Data"/>
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout 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"
    android : orientation = "vertical" >
     <ImageView
        android : layout_width = "match_parent"
        android : layout_height = "wrap_content"
        android : layout_marginBottom = "10dp"
        android : id = "@+id/img" />
     <Button
        android : layout_width = "match_parent"
        android : layout_height = "wrap_content"
        android : id = "@+id/btn"
        android : text = "Fetch Data" />
</LinearLayout>

MainActivity.xml

MainActivity.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
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
package com.androidvolleyexample;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
public class MainActivity extends Activity {
    ImageView img;
    Button btn;
    String url ="https://www.thecrazyprogrammer.com/wp-content/uploads/2015/07/The-Crazy-Programmer.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.img);
        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>(){
                    @Override
                    public void onResponse(Bitmap b) {
                        img.setImageBitmap(b);
                    }
                }, 0, 0, null,
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(MainActivity.this, "Some error occurred!!", Toast.LENGTH_LONG).show();
                    }
                });
                RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
                rQueue.add(request);
            }
        });
    }
}
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
package com . androidvolleyexample ;
import android . app . Activity ;
import android . graphics . Bitmap ;
import android . os . Bundle ;
import android . view . View ;
import android . widget . Button ;
import android . widget . ImageView ;
import android . widget . Toast ;
import com . android . volley . RequestQueue ;
import com . android . volley . Response ;
import com . android . volley . VolleyError ;
import com . android . volley . toolbox . ImageRequest ;
import com . android . volley . toolbox . Volley ;
public class MainActivity extends Activity {
     ImageView img ;
     Button btn ;
     String url = "https://www.thecrazyprogrammer.com/wp-content/uploads/2015/07/The-Crazy-Programmer.png" ;
     @Override
     protected void onCreate ( Bundle savedInstanceState ) {
         super . onCreate ( savedInstanceState ) ;
         setContentView ( R . layout . activity_main ) ;
         img = ( ImageView ) findViewById ( R . id . img ) ;
         btn = ( Button ) findViewById ( R . id . btn ) ;
         btn . setOnClickListener ( new View . OnClickListener ( ) {
             @Override
             public void onClick ( View v ) {
                 ImageRequest request = new ImageRequest ( url , new Response . Listener <Bitmap> ( ) {
                     @Override
                     public void onResponse ( Bitmap b ) {
                         img . setImageBitmap ( b ) ;
                     }
                 } , 0 , 0 , null ,
                 new Response . ErrorListener ( ) {
                     @Override
                     public void onErrorResponse ( VolleyError volleyError ) {
                         Toast . makeText ( MainActivity . this , "Some error occurred!!" , Toast . LENGTH_LONG ) . show ( ) ;
                     }
                 } ) ;
                 RequestQueue rQueue = Volley . newRequestQueue ( MainActivity . this ) ;
                 rQueue . add ( request ) ;
             }
         } ) ;
     }
}

Screenshot

屏幕截图

带有示例的Android Volley教程

提取JSON数据 (Fetching JSON Data)

JsonObjectRequest and JsonArrayRequest class is used to create a json request. We specify the URL and then receive the json data in response. Same as string and image fetched above, we can fetch json data. So I am not giving its example as you can easily do yourself.

JsonObjectRequestJsonArrayRequest类用于创建json请求。 我们指定URL,然后接收json数据作为响应。 与上面获取的字符串和图像相同,我们可以获取json数据。 因此,我不举任何例子,因为您可以轻松地做到自己。

传送资料 (Sending Data)

For sending some data we have to use post request and override getParams() method. The data is sent in key value pairs. It can be done in following way.

为了发送一些数据,我们必须使用post request并重写getParams()方法。 数据以键值对的形式发送。 可以通过以下方式完成。

MainActivity.java

MainActivity.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
package com.androidvolleyexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
    TextView txt;
    Button btn;
    String url ="http://192.168.1.8/JavaRESTfullWS/DemoService";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (TextView)findViewById(R.id.txt);
        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>(){
                    @Override
                    public void onResponse(String s) {
                        txt.setText(s);
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        txt.setText("Some error occurred!!");
                    }
                })
                {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> parameters = new HashMap<String, String>();
                        parameters.put("message", "Hello");
                        return parameters;
                    }
                };
                RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
                rQueue.add(request);
            }
        });
    }
}
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
package com . androidvolleyexample ;
import android . app . Activity ;
import android . os . Bundle ;
import android . view . View ;
import android . widget . Button ;
import android . widget . TextView ;
import com . android . volley . AuthFailureError ;
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 . StringRequest ;
import com . android . volley . toolbox . Volley ;
import java . util . HashMap ;
import java . util . Map ;
public class MainActivity extends Activity {
     TextView txt ;
     Button btn ;
     String url = "http://192.168.1.8/JavaRESTfullWS/DemoService" ;
     @Override
     protected void onCreate ( Bundle savedInstanceState ) {
         super . onCreate ( savedInstanceState ) ;
         setContentView ( R . layout . activity_main ) ;
         txt = ( TextView ) findViewById ( R . id . txt ) ;
         btn = ( Button ) findViewById ( R . id . btn ) ;
         btn . setOnClickListener ( new View . OnClickListener ( ) {
             @Override
             public void onClick ( View v ) {
                 StringRequest request = new StringRequest ( Request . Method . POST , url , new Response . Listener <String> ( ) {
                     @Override
                     public void onResponse ( String s ) {
                         txt . setText ( s ) ;
                     }
                 } , new Response . ErrorListener ( ) {
                     @Override
                     public void onErrorResponse ( VolleyError volleyError ) {
                         txt . setText ( "Some error occurred!!" ) ;
                     }
                 } )
                 {
                     @Override
                     protected Map < String , String > getParams ( ) throws AuthFailureError {
                         Map < String , String > parameters = new HashMap < String , String > ( ) ;
                         parameters . put ( "message" , "Hello" ) ;
                         return parameters ;
                     }
                 } ;
                 RequestQueue rQueue = Volley . newRequestQueue ( MainActivity . this ) ;
                 rQueue . add ( request ) ;
             }
         } ) ;
     }
}

Comment below if you found anything incorrect or have doubts related to above android volley tutorial.

如果您发现任何不正确的内容或与上述android volley教程相关的疑问,请在下面评论。

翻译自: https://www.thecrazyprogrammer.com/2016/07/android-volley-tutorial.html