Volley Android Networking Library
Asked Answered
G

19

121

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?
Garner answered 20/5, 2013 at 22:54 Comment(2)
Whenever you see multiple branches in a git repo, you should always assume that they want you to clone and start using the master branch. Any other branch is secondary.Monosaccharide
You can also add Volley as a git submodule. Detailed explanation : gitsubmoduleasandroidtudiomodule.blogspot.inGareri
A
204
$ 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

Again answered 23/5, 2013 at 18:16 Comment(18)
NOTE: You will have to have fixed your PATH variable for this, to do this on linux do the following (in your .profile or wherever you put PATH variables): 1. export ANDROID_HOME=<android-sdk-dir>Aplanospore
@Johan: doesn't android update project -p . take care of this? (by creating local.properties)Tound
Sorry had a bad connection when writing, just saying you have to bind your path variable to use android create project -p.Aplanospore
It's amazing that I had to go to 5 different google results to find the instructions to install their own networking library.Zaibatsu
Fatal: remote error: Access Denied (not available in your country)! If i download jar and add jar to my project does it work in my country? Or even how can i download jar, without cloning it?!Lonnielonny
Thanks. It is bizzare that Google provides no doc, no git repo URI for Volley.Mahone
@Ray, if you Google "android volley" it's literally the first result.Dominquedominquez
Note: if you're a new Android Studio user, you might be surprised that copying volley.jar into libs doesn't seem to cause any change. That's because the default Project Structure view "helps" you by not showing you some files and directories. To see the actual jar, select the spinner just above Project Structure and change it from Android to Project. (Android Studio 1.0.2)Elianore
Serious Question: Why is there no straight download of the volley Jar File anywhere? Is there some problem with one universal JAR file for it?Stour
Does anyone else get "volley is not a vaild project (AndroidManifest.xml not found)Cadaverine
@johncarter I am too getting this error.. I am also not able to fire the command android update project -pConsultative
@ChintanSoni, I could not get it as a jar file so I ended up compiling it as a library. I watched this video which explained how. It is now working for me youtube.com/watch?v=TForBjArUNgCadaverine
@ChintanSoni, ~ 3 months ago, git submission c9ef93a says "Migrate from Gradle to Maven." Instead of running "android update -p .", you run maven commands, "mvn compile" and then "mvn package."Hylo
Error: C:\Users\Murilo\AndroidStudioProjects\MyApplication2\volley is not a valid proje ct (AndroidManifest.xml not found).Morion
I solve the androidManifest.xml not found error like that: android update project -p \app\src\main --target "android-19"Morion
It's not working anymore, seems they changed the repo somehow except if you checkout an older version of it otherwise this process is broken.Dracaena
When I run ant jar I get Buildfile: build.xml does not exist!. Anybody know why / how to fix?Successor
See my answer below, there is now com.android.volley:volley:1.0.0Vesuvianite
S
73

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.
Sauterne answered 28/7, 2013 at 10:39 Comment(2)
This is great. The most important tip for me was #5 (select only src), as this helped with other libraries I was trying to include as well.Grotius
You save me a day! "only check src folder" works for me :)Discombobulate
H
48

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.

Homeland answered 20/5, 2013 at 23:6 Comment(2)
Fatal: remote error: Access Denied (not available in your country)! If i download jar and add jar to my project does it work in my country? Or even how can i download jar, without cloning it?!Lonnielonny
Yes, their instructions seem to suggest using 'master' branch, but I find this a bit odd given that master seems to be actively changing. Perhaps would be better to find the latest release branch.Byng
S
41

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

Sarabia answered 3/10, 2014 at 19:25 Comment(3)
Thank you so much for this. Everybody just says 'copy the jar to your lib folder' and then leave it at that.Irmine
cURL says this jar hasn't been updated since May 01, 2014Successor
How about a new jar verson?Marbles
V
26

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

dependencies {
    implementation 'com.android.volley:volley:1.1.0'
}
Vesuvianite answered 12/2, 2016 at 20:51 Comment(1)
Make sure you remove volley.jar from your libs folder, if you have in there. And, remove the reference to volley.jar from your app/build.gradle file.Doubledealing
W
16

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.

Wolver answered 29/7, 2014 at 21:47 Comment(6)
Where in the file should this be?Linhliniment
If you are using Gradle to build your app, should be build.gradle file in your project. If you aren't using Gradle, then take a look at other solutions posted here.Wolver
Thanks, but I meant where in the build.gradle file should the above be?Linhliniment
As The Metal Beard stated in his comment. Inside the dependencies if you have one already declared. If not, declare it at the end of the file, but don't include it inside android tagSzechwan
NOTE: This is not official. It is a mirror of the Volley repo.Sauterne
This is now deprecated. You now should either clone the original repo and add as library or use dependencies { compile 'com.android.volley:volley:1.0.0' }Trajan
A
13

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'.

Analphabetic answered 27/10, 2014 at 11:35 Comment(0)
M
11

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.

Mulderig answered 24/7, 2013 at 15:24 Comment(4)
The problem is that the volley project is not defined as an android library.Forgiveness
You have to set Volley in your IDE as a library.Mulderig
Doing this will modify the project property and so the submodule will be in state "modified". Because of that I do not want to use this solution. With a project "correctly defined", I would have use the submodule but not for Volley. I created a jar of Volley so far.Forgiveness
You can still pull from Google source as they make changes. If you are wanting to modify their code and store that, then clone it, make your local repo reference two different remotes, and use one to pull from them, and the other to push the code you want to store. I am not sure why it bothers you to have a submodule as modified, if you are storing your project anywhere, and you push from the parent project, without committing the submodule anywhere, you will still push in the reference to the commit of the submodule when you added it.Mulderig
G
8

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

Glottis answered 28/5, 2013 at 11:10 Comment(1)
Before using the RequestQueue api, you need to add this library to your project...Monosaccharide
D
2

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.+'
}
Deft answered 22/7, 2014 at 16:3 Comment(1)
Bad idea to do this. That library in there is 1 year old. And doubt it will get updated ;-)Hurl
D
1

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.

Dime answered 21/1, 2014 at 18:1 Comment(0)
E
1

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

Elianore answered 16/1, 2015 at 17:36 Comment(0)
M
1

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.

Mendiola answered 26/1, 2015 at 20:8 Comment(0)
S
1

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.
Schenk answered 26/2, 2015 at 20:16 Comment(0)
C
1

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);
 }
Centipede answered 12/8, 2015 at 14:25 Comment(0)
B
0

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.

Boyse answered 3/4, 2014 at 13:12 Comment(0)
A
0

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.+'
}
Authors answered 11/9, 2014 at 17:28 Comment(0)
G
0

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

Gareri answered 9/7, 2016 at 9:54 Comment(0)
O
0

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'

}

Oversexed answered 18/7, 2017 at 20:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.