Home » Android » http – Volley Android Networking Library

http – Volley Android Networking Library

Posted by: admin March 11, 2020 Leave a comment

Questions:

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?
How to&Answers:
$ 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

Answer:

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.

Answer:

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.

Answer:

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

Answer:

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

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

Answer:

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.

Answer:

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

Answer:

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.

Answer:

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

Answer:

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

Answer:

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.

Answer:

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

Answer:

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.

Answer:

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.

Answer:

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);
 }

Answer:

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.

Answer:

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

Answer:

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

Answer:

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'

}