Volley Android Networking Library

AndroidHttpAndroid NetworkingAndroid Volley

Android Problem Overview


I have few questions around using Volley in my projects:

  1. Can this library be used in any Java project or just Android?
  2. I see multiple branches here and no documentation on which branch is to start with. Which branch should I use to start with?
  3. How do you integrate this library in your own project? What approach is better: Make Volley as a standalone library project and spin a jar and put it in your project or copy the all source code inside your project?

Android Solutions


Solution 1 - Android

$ git clone https://android.googlesource.com/platform/frameworks/volley
$ cd volley
$ android update project -p .
$ ant jar

Then, copy bin/volley.jar into your libs/ folder and off you go!

source

Solution 2 - Android

In the Volley lesson, Google instructs as to either add Volley to our project as an Android Library project or as a .jar file.

Here's how to create the Volley .jar file using Android Studio or Eclipse:

NOTE:

In both cases I suggest renaming the .jar file to the date of Volley's latest commit, i.e. volley_20150319.jar, to keep versioning simple.


Android Studio:

  1. Clone the Volley repository via Git.
  2. Import the project into Android Studio. (I usually select the project's gradle file when importing in Android Studio)
  3. Build the project. (I had to change the gradle build settings to reflect the latest build tools and gradle version, but it's usually up to date).
  4. In your file explorer, navigate to [your local path to volley]/build/intermediate/bundles/
  5. In both the debug and release folders you'll find a JAR file called classes.jar.
  6. Copy either JAR file into your libs/ folder.
  7. Gradle sync, and you're done.

Eclipse:

  1. Clone the Volley repository via Git.
  2. Import the project into eclipse.
  3. Right-click the project and select Export...
  4. Select Java / JAR file.
  5. We're only interested in the src folder and nothing else. The easiest way to make sure only it is selected is to deselect the project and then select the src folder inside.
  6. Check the Export generated class files and resources option.
  7. OPTIONAL: If you want the Javadoc to be visible also select the Export Java source files resources.
  8. Create the JAR file and put it in your libs/ folder.

Solution 3 - Android

> 1) Is this library can also be used as networking library in normal Java projects also OR is it strictly for Android Only

It is for Android only, as it depends on Android-specific classes. You can tell this by looking at the source code, for stuff like RequestQueue.

> 2) I see multiple branches here and no documentation on which branch is to start with. Which branch should I use to start with?

The instructions from the Google I|O presentation were to just clone the git repo, which would pull from the master branch by default.

> 3) How to integrate this library in your own project? What approach is better: Make Volley as a standalone library project and spin a jar and put it in your project or Copy the all source code inside your project?

The instructions from the Google I|O presentation were to add the source code to your project. Personally, I find this to be a bizarre approach.

Solution 4 - Android

you can download the volley.jar

Source : AndroidHive

copy theVolley.jar to libs

Then

Right Click volley.jar -> Add As Library

enter image description here

Solution 5 - Android

The Volley library is now published by the Android Open Source Project:

dependencies {
    implementation 'com.android.volley:volley:1.1.0'
}

Solution 6 - Android

UPDATE: Volley is now official and is available through the JCenter. Here's how to import it:

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

DEPRICATED WAY:

If you're using Gradle, you can import Volley from here.

dependencies {
    compile 'com.mcxiaoke.volley:library:1.0.+'
}

Note

> This is an unofficial mirror (with some minor bugfix, see Changelog for details.) for android volley library, the source code will synchronize periodically with the official volley repository.

Solution 7 - Android

Plenty of ways

Since there are many answers about a single approach, but none that is comparing the different ways to get volley up and running, I also put my two cents in. Feel free to edit/enhance this answer as well.

Add it as library - (quick solution)

  1. Download it from: androidhive
  2. Place it in your [MyProjectPath]/app/libs/ folder
  3. In Android Studio right-click on it and select Add As Library...

Source files from git - (a rather official solution)

  1. Download / install the git client (if you don't have it on your system yet) (othervise via git clone https://github.com/git/git ... sry bad one, but couldn't resist ^^)
  2. Execute git clone https://android.googlesource.com/platform/frameworks/volley
  3. Copy the com folder from within [path_where_you_typed_git_clone]/volley/src to your projects app/src/main/java folder (or integrate it instead, if you already have a com folder there!! ;-))

The files show up immediately in Android Studio. For Eclipse you will have to right-click on the src folder and press refresh (or F5) first.

Doing it via git is what is officially suggested in the android tutorials (look here).

Gradle via an "unofficial" mirror - (dynamic solution)

  1. In your project's src/build.gradle file add following volley dependency:

      dependencies {
          compile fileTree(dir: 'libs', include: ['*.jar'])
          // ...
    
          compile 'com.mcxiaoke.volley:library:1.+'
      }
    
  2. Click on Try Again which should right away appear on the top of the file, or just Build it if not

The main "advantage" here is, that this will keep the version up to date for you, whereas in the other two cases you would have to manually update volley.

On the "downside" it is not officially from google, but a third party weekly mirror.

But both of these points, are really relative to what you would need/want. Also if you don't want updates, just put the desired version there instead e.g. compile 'com.mcxiaoke.volley:library:1.0.7'.

Solution 8 - Android

If you use GIT for your own code management, why not simply add it as a submodule to project...

git submodule add https://android.googlesource.com/platform/frameworks/volley -b master Volley

That way, as the Volley code base is updated, it is simple to update...

git submodule git pull

You can extend the main Volley class in your own project for modification, which keeps you from having to mess with coding your changes every time the Volley framework is updated.

Solution 9 - Android

Here is a small Quickstart for a Volley Http Request, It is extremely easy to integrate.

  • You need an application wide Volley RequestQueue:

     1. private static RequestQueue reqQueue;
    

You could put it in your Application class and make it statically available via getRequestQueue().

  • Then you can already use the RequestQueue.add() method to execute the first request with Volley.

     2. reqQueue.add(...)
    
  • Use JsonObjectRequest to query for a single object, use JsonArrayRequest to query for a list of objects.

     queue.add(new JsonArrayRequest(URL, new Listener<JSONArray>() {
    
     	@Override
     	public void onResponse(JSONArray response) {
     		//SUCCESS
     	}}, new ErrorListener() {
    
     	@Override
     	public void onErrorResponse(VolleyError error) {
     		//ERROR
     	}}));
    
  • Remember to set the Http Expires header correctly on your server-side so Volley can make use of it's integrated caching feature

Solution 10 - Android

Here another way with Android Studio ang Gradle:

You need the next in your build.gradle of your project (in your app structure level):

repositories {
    maven {
        url 'https://github.com/Goddchen/mvn-repo/raw/master/'
    }
    mavenCentral()
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    // You must install or update the Support Repository through the SDK manager to use this dependency.
    compile 'com.android.support:support-v4:20.+'
    compile 'com.android:volley:1.+'
}

Solution 11 - Android

First clone the project from Git

$git clone https://android.googlesource.com/platform/frameworks/volley
  • import volley in eclipse.
  • Right click on your project-> Property-> android
  • Add library-> choose volley (if you dont see volley there, rigth click volley library, goto property and android and click library)
  • after you add volley as library you can start using it in your application.

Some basic class of volley you should know are

  • RequestQueue
  • JsonArrayRequest
  • JsonObjectRequest

To use volley first you need to create object of RequestQueue

RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());

Second -> make a Request using either JsonArrayRequest or JsonObjectRequest

JsonArrayRequest mJsonRequest = new JsonArrayRequest(url, 
			new Listener<JSONArray>() {

				@Override
				public void onResponse(JSONArray response) {
					// here you can parse response and use accordingly
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					// here you will receive errors and show proper message according to error type
					
				}
			});

and at last put the request in queue. i.e.

mQueue.add(mJsonRequest);

Also I would suggest you to make a Singleton of RequestQuery.

Solution 12 - Android

Adding a Volley jar (or any jar) to Android Studio 1.0.2 is now considerably easier. From outside Android Studio, copy volley.jar into <yourproject>/app/libs (which should already exist). Because the default Gradle setup includes this line:

 compile fileTree(dir: 'libs', include: ['*.jar'])

... everything is now set up. That might not appear to be so because the default Project Structure view (File -> Project Structure) doesn't show the libs directory. To see it, you need to use the spinner just above the Project Structure view to change Android to Project.

You can see that it's working by building the app (may not be necessary), and then starting to type some code like this:

 RequestQueue request

You'll see that Android Studio prompts you with the completion RequestQueue (com.android.volley).

Solution 13 - Android

Its also pretty easy to get a debug aar built if thats your preference.

git clone https://android.googlesource.com/platform/frameworks/volley

Then make a new Android studio project (just a regular app project) in a different directory. Once thats complete, add a new submodule (File | New Module). Choose the import existing project option and point it to the directory where you checked out volley. Once thats done you can make your module and it will create an aar file.

Solution 14 - Android

Using eclipse Luna you have to:

  • clone it from GIT.
  • cut (copy & delete) the folder COM under the JAVA folder to below the SRC folder like in regular Android project.
  • change the project.properties target to 15 instead of 8.
  • build the project.
  • export the project as jar file including the source - use the export tool.
  • keep in the exported jar only the COM folder and the META-INF folder, delete all the others folders - use zip tool to delete the content of the jar.
  • use this jar as your Volley jar project.
  • put the Volley jar in the lib folder of your destination Android project.

Solution 15 - Android

If you are using Android Studio which you should do put this line in the gradle file

compile 'com.mcxiaoke.volley:library:1.0.15'

If you want to use the GET method you should have something like that.

private void weatherData() {
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(
        Request.Method.GET,
        "URL with JSON data",
        new Response.Listener<JSONObject>() {
             @Override
             public void onResponse(JSONObject response) {
                 try {
                      //Your code goes here      
                 } catch (JSONException e) {
                      Log.e("TAG", e.toString());
                 }
             }
        }, 
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);
}

But if you want to post data in the server,then you should construct a HashMap and Volley library converts those key/pair values into JSON objects before posting them in the server. Here is an example.

final HashMap<String, String> postParams = new HashMap<String, String>();
postParams.put("username", username);
postParams.put("password", password);

Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);

JsonObjectRequest jsonObjReq = new JsonObjectRequest(
    "YOUR URL WITH JSON DATA", 
    jsonObject,
    new com.android.volley.Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("TAG", response.toString());
            try {
                if (response.getString("status").equals("fail")) {

                } else if (response.getString("status").equals("success")) {

                } catch (JSONException e) {
                     Log.e("TAG", e.toString())
                }
            }
        }, 
        new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
             //VolleyLog.d("TAG", "Error: " + error.getMessage());
            //pDialog.dismiss();

        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }
    };
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

    VolleySingleton.getInstance(getApplicationContext()).
    addToRequestQueue(jsonObjRequest);
 }

Solution 16 - Android

I cloned the Volley project and added configuration files which allow building the library with Gradle.

With this you can install the library into your local Maven repository and reference it from an Android project via Gradle.

Requirements

  1. Maven
  2. Gradle

How to use

  1. Clone my repository
  2. Build and install the Volley library
  3. Reference the library in an Android project

Bugfixes

Please bear in mind that there are various clones out there which have improvements for the library. It might be necessary to integrate them and compile your private enhanced version of the library.

Benefits

In addition to the library itself the build script generates JavaDoc and sources archives.

Solution 17 - Android

I faced a problem when support library was listed on the second line. Reordering these two statements worked for me.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.mcxiaoke.volley:library:1.0.6'
    compile 'com.android.support:support-v4:20.+'
}

Solution 18 - Android

> Volley can be added as a git submodule in your current project repo. > This git submodule will point to the official git repo of Volley. > Hence you can get updates from official git repo just by updating the submodule > pointer. > > Further more if you add Volley as a Library Module in your main > project you can easily customise it. It will very useful for debugging > purpose as well.

To achieve this follow the below steps :

Step I :

Add volley as submodule in Android application project GIT Repo. git submodule add -b master https://android.googlesource.com/platform/frameworks/volley Libraries/Volley

Step II :

In settings.gradle, add the following to add volley as a studio project module. include ':Volley' project(':Volley').projectDir=new File('../Libraries/Volley')

Step III :

In app/build.gradle, add following line to compile Volley compile project(':Volley')

That would be all! Volley has been successfully added in the project.

> Every time you want to get the latest code from Google official > Volley's repo, just run the below command

git submodule foreach git pull

For more detailed information : https://gitsubmoduleasandroidtudiomodule.blogspot.in/

GIT Repo sample code : https://github.com/arpitratan/AndroidGitSubmoduleAsModule

Solution 19 - Android

For Future Readers

I love to work with Volley. To save development time i tried to write small handy library Gloxey Netwok Manager to setup Volley with my project. It includes JSON parser and different other methods that helps to check network availability.

Library provides ConnectionManager.class in which different methods for Volley String and Volley JSON requests are available. You can make requests of GET, PUT, POST, DELETE with or without header. You can read full documentation here.

Just put this line in your gradle file.

dependencies {

   compile 'io.gloxey.gnm:network-manager:1.0.1'

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbiancaView Question on Stackoverflow
Solution 1 - AndroidKevinView Answer on Stackoverflow
Solution 2 - AndroidItai HanskiView Answer on Stackoverflow
Solution 3 - AndroidCommonsWareView Answer on Stackoverflow
Solution 4 - AndroidMina GabrielView Answer on Stackoverflow
Solution 5 - AndroidSam SternView Answer on Stackoverflow
Solution 6 - AndroidC0D3LIC1OU5View Answer on Stackoverflow
Solution 7 - AndroidLeviteView Answer on Stackoverflow
Solution 8 - AndroidSimon.PonderView Answer on Stackoverflow
Solution 9 - Androiduser1234813View Answer on Stackoverflow
Solution 10 - AndroidSottiView Answer on Stackoverflow
Solution 11 - Androiduser98239820View Answer on Stackoverflow
Solution 12 - AndroidBrian MarickView Answer on Stackoverflow
Solution 13 - AndroidChrisView Answer on Stackoverflow
Solution 14 - AndroidYaron RonenView Answer on Stackoverflow
Solution 15 - AndroidTheoView Answer on Stackoverflow
Solution 16 - AndroidJJDView Answer on Stackoverflow
Solution 17 - AndroidSubramanya SheshadriView Answer on Stackoverflow
Solution 18 - AndroidArpit RatanView Answer on Stackoverflow
Solution 19 - AndroidAdnan Bin MustafaView Answer on Stackoverflow