Академический Документы
Профессиональный Документы
Культура Документы
Volley is a HTTP library developed by Google and was first introduced during Google I/O
2013. This library is used to transmit data over the network. It actually makes networking
faster and easier for Apps. It is available through AOSP(Android Open Source Project)
repository.
The volley library has the features like automatic scheduling of network request, multiple
concurrent connections, request prioritization, cancel/block a request, easier
management of UI with data fetched asynchronously from the network and also offers
easier customization.
Important Note: Volley uses cache to improve the App performance by saving memory
and bandwidth of remote server.
After instantiating RequestQueue, a request must be created. The default request classes
already included in Volley library are String request, JSON request, and image request.
You can also create custom request by extending Volley’s request class.
Request Constructors used in Volley takes 4 parameter:
First Parameter: Request.Method.GET – The GET is used to read. You can also use POST
(to create), PUT (To update/replace), DELETE (to delete), PATCH (to update/modify) and
more.
Second Parameter: URL – The url that will response to the HTTP request.
Third Parameter: Successful Response Listener – Where your data will go after the
request is successfully complete.
}
}
Fourth Parameter: Error Listener – What will be told if there was a problem with your
request. For example, you can display it in Log to see the error.
}
}
Now the last step is to add your request to Request queue and rest volley will handle for
you.
queue.add(request);
Here you can also add more requests to the queue that you would like at one time and
the response will be send to their respective response/error classes.
Volley Basic HTTP Example In Android Studio:
In this example we have created a button and on click of a button a HTTP request will be
send to server. The response from the server is then displayed using Toast on the screen.
Below you can download code, see final output and step by step explanation of example.
Download Code (Password: abhiandroid)
Step 1: Create a new project and name it VolleyBasicExample.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we create one Button which will be used to fire an HTTP request to server.
<Button
android:id="@+id/buttonRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#414af4"
android:text="Click Here To Send HTTP Request To Server And See Response Disp
layed As Toast"
android:textColor="#ffffff"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp" />
</RelativeLayout>
Step 3: To use volley library you will need to add the below dependency in your gradle
build. Open build.gradle (Module: app) and add the below line in dependencies and click
sync now:
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "abhiandroid.com.volleybasicexample"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-r
ules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
testCompile 'junit:junit:4.12'
compile 'com.android.volley:volley:1.0.0' // dependency file for Volley
}
Step 4: As our App will be sending request to the server and receiving response on button
click which means it requires internet. So define internet permission in Android Manifest
file.
Manifest.xml code:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Step 5: Now we will need to generate an HTTP request for our App. Below are the simple
steps to generate it:
a) First we will need sample JSON code. Below is the code I am using:
Related Read: JSON Parsing Tutorial With Example in Android Studio
{
"users": [
{
"id": "1087",
"name": "Abhishek Saini",
"email": "info@abhiandroid.com",
"gender" : "male",
"contact": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "1088",
"name": "Gourav",
"email": "gourav9188@gmail.com",
"gender" : "male",
"contact": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]
}
b) Now we will open the mocky.io and put the JSON code in it.
Step 6: Now open app -> java -> package -> MainActivity.java and add the below code.
In this step we will initialize the button and set on click listener on it. When the button is
click, it will send HTTP request to the url that we generated in the previous step and
display the response as Toast on the screen.
Here we have used simple StringRequest and default RequestQueue that volley provide
us.
package abhiandroid.com.volleybasicexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
sendAndRequestResponse();
}
}
);
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(this);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mRequestQueue.add(mStringRequest);
}
}
Output:
Now run the App and click on the button. You will see HTTP response from server on click
of it.
Creating New Project: Create a new Project File -> New ->Android Application Project
Step 1: Open your layout file of main activity and add a ListView element.
actvity_main.xml
<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"
tools:context=".MainActivity" >
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
/>
</RelativeLayout>
Step 2: We will now create another layout file for ListView row and name this file
as list_row.xml
<!-- category-->
<TextView
android:id="@+id/category"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/category"
android:textSize="@dimen/category"
android:textStyle="bold"
android:layout_below="@+id/title"
android:layout_marginTop="20dp"
android:layout_marginLeft="1dp" />
package com.example.abhishek.json;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
return cacheSize;
}
public ImageClass() {
this(getDefaultLruCacheSize());
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
@Override
public Bitmap getBitmap(String url) {
return get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
package com.example.abhishek.json;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
return mRequestQueue;
}
</manifest>
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.android.volley:volley:1.0.0'
}
Step 7: Create Model.java. This model class will be used to provide data to list view after
parsing the json.
package com.example.abhishek.json;
public Model() {
}
public Model(String title, String category, String thumbnailUrl) {
this.title=title;
this.category=category;
this.thumbnailUrl = thumbnailUrl;
}
Step 8: Create a class CustomAdapter.java with below code. This is a custom adapter class
which provides data to ListView
package com.example.abhishek.json;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
@Override
public int getCount() {
return modelItems.size();
}
@Override
public Object getItem(int location) {
return modelItems.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);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
// category
category.setText("Category: "+ String.valueOf(m.getCategory()));
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
return convertView;
}}
Step 9: Now open your main activity class (MainActivity.java) and add the below code.
We created volley’s JsonArrayRequest to get the json from url. Upon parsing the json, we
stored all the json data into an ArrayList as Model objects.
package com.example.abhishek.json;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes so that it renders the list view with u
pdated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}}
<color name="category">#b932ca</color>
<color name="title">#6b2cd9</color>
</resources>
values ->dimens.xml
<resources>
<dimen name="title">22dp</dimen>
<dimen name="category">20dip</dimen>
</resources>
<string name="app_name">VolleyExample</string>
</resources>
<resources>
</resources>
Output:
Now run the App and test it once. You will see title, category and image in App which are
fetched from server.
<Button
android:id="@+id/btnRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#414af4"
android:text="Click Here To Send HTTP Request To Server And See Response Disp
layed As Toast"
android:textColor="#ffffff"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp" />
</RelativeLayout>
Step 3: To use volley library you will need to add the below dependency in your gradle
build. Open build.gradle (Module: app) and add the below line in dependencies and click
sync now:
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "abhiandroid.com.volleycustomrequestqueueexample"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-r
ules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
Step 4: As our App will be sending request to the server and receiving response on button
click which means it requires internet. So define internet permission in Android Manifest
file.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 5: Now we will need to generate an HTTP request for our App. Below are the simple
steps to generate it:
a) First we will need sample JSON code. Below is the code I am using:
{
"users": [
{
"id": "1087",
"name": "Abhishek Saini",
"email": "info@abhiandroid.com",
"gender" : "male",
"contact": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "1088",
"name": "Gourav",
"email": "gourav9188@gmail.com",
"gender" : "male",
"contact": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]
}
b) Now we will open the mocky.io and put the JSON code in it.
Step 5: Now open app -> java -> package -> MainActivity.java and add the below code.
In this step we will initialize the button and set on click listener on it. When the button is
click, it will send HTTP request to the url that we created in the previous step and display
the response as Toast on the screen.
Here we have used custom StringRequest and default RequestQueue that volley provide
us.
package abhiandroid.com.volleycustomrequestqueueexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Network;
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.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.StringRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRequest.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick (View v){
requestQueue.add(stringRequest);
}
});
}
Output:
Now run the App and click on button. You will see http response from server on click of
it.