Skip to content

Instantly share code, notes, and snippets.

@donn
Last active January 14, 2020 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donn/2df0353468db60e25c1530e761da7b2e to your computer and use it in GitHub Desktop.
Save donn/2df0353468db60e25c1530e761da7b2e to your computer and use it in GitHub Desktop.
Using Volley, Gson and Picasso for Android Newbies

Android HTTP 101

Manifest

Right below the <manifest /> tag:

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

build.gradle

Add to dependencies in the build.gradle inside "app"; your gradle dependencies should look something like this (do not copy this file or your app WILL break, this is just an example):

dependencies {
    //[...] Other libraries here
    implementation 'com.google.code.gson:gson:2.7.+'
    implementation 'com.android.volley:volley:1.0.+'
    implementation 'com.squareup.picasso:picasso:2.71828'
    //[...] More libraries here
}

Request Code

//Imports
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 com.google.gson.Gson;

//Request Code
    RequestQueue queue = Volley.newRequestQueue(this);
    
    StringRequest example = new StringRequest(Request.Method.POST, //Make sure to use .GET if it's  a get request.
        checkAppIDURL,
        new Response.Listener<String>() //This is an in-lined function that waits for a response from the server running asynchronously- you do not need to set up the async yourself.
        {
            @Override
            public void onResponse(String response)
            {
                if (StringUtils.isNumeric(response))
                {
                    display.setText("Successfully recieved number.");
                }
                else
                {
                    display.setText("Fatal app error.");
                }
            }

        },
        new Response.ErrorListener() //This is an in-lined function that handles CONNECTION errors. Errors from the SERVER (i.e. wrong username/password, et cetera) should still be handled by Response.Listener.
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                display.setVisibility(View.GONE);
                Toast.makeText(ExampleActivity.this, "Connection error. Try again later.", Toast.LENGTH_SHORT).show();
            }
        }
    )
    {
        // POST REQUEST ONLY
        @Override
        public byte[] getBody()
        // To set the POST request body, we need to override the "getBody" function. String.getBytes() usually works here.
        // You should use it in conjunction with the Google Gson library to easily convert classes to JSON.
        {
            Gson gson = new Gson();
            String json = gson.toJson(exampleObject);
            return json.getBytes();
        }
    };
    
    queue.add(example);

Tips on using Gson

A simple Gson tutorial exists here: https://www.tutorialspoint.com/gson/gson_first_application.htm

Try to match the names between the JSON file and the Java class, i.e.

"MyKey": "value"

...means that the java property should be...

String MyKey;

If the JSON has an invalid character in it, i.e. something like this:

"My πŸ˜‚πŸ˜‚πŸ˜‚    Key": "value"

You can let GSON know by using an annotation.

@SerializedName("My πŸ˜‚πŸ˜‚πŸ˜‚    Key") String key;

Of course, if you're using emoji in your keys I would recommend you re-evaluate your life choices but you get the idea.

Using Picasso

    ImageView image = (ImageView)findViewById(R.id.imageView);
    String url = "https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg";
    
    Picasso.
    get().
    load(url). // URL to Image
    fit(). // Fit in frame
    centerCrop(). // Crop until image is centered
    into(image); // Put result in imageView

Licensing Note

This document and all code are under the UNLICENSE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment