Tutorial #94: Using Retrofit for Android

Hello friends!

In one of my previous tutorials, I had talked about using the Volley networking library in Android. However, Volley is less documented and is totally focused on handling individual, small HTTP requests.

Retrofit on the other hand makes it incredibly easy to download JSON or XML data from a web API and parse it into a Plain Old Java Object (POJO). It’s released by Square and offers very easy to use REST API’s. Through this tutorial, we will learn how to use Retrofit for Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Create a new Android application project called AndroidRetrofitExample with package name com.app.retrofit. Choose the target SDK as Android 4.4 (API level 19)

Step 2: Create REST service interface

Create a new interface called GithubApiService that will help fetch the list of contributors for a particular repository as follows,

GithubApiService.java

package com.app.retrofit;

import java.util.List;
import retrofit.http.GET;
import retrofit.http.Path;

public interface GithubApiService {
	@GET("/repos/{owner}/{repo}/contributors")
	List<Contributor> contributors(
			@Path("owner") String owner,
			@Path("repo") String repo
	);
}

Step 3: Create Activity class

Now, let’s implement our MainActivity class. We will create an AsyncTask in order to call the public Github API service.

MainActivity.java

package com.app.retrofit;

import java.util.List;
import retrofit.RestAdapter;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		new GetUserInfo().execute();
	}

	private class GetUserInfo extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub	
			try{ 
				RestAdapter restAdapter = new RestAdapter.Builder()
				.setEndpoint("https://api.github.com") 
				.build();

				GithubApiService github = restAdapter.create(GithubApiService.class);
				List<Contributor> contributors = github.contributors("pscholl", "glass_snippets");

				for (Contributor contributor : contributors) {
					Log.i("App", contributor.login + " - " + contributor.contributions);
				}

			}catch(Exception e){
				e.printStackTrace();
				return "failure";
			}	
           return "success";
	    }
      }
}

The RestAdapter is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.

Contributor.java

package com.app.retrofit;

//POJO class
public class Contributor {
	
	// GitHub username
	public String login; 
	// Commit count
	public int contributions;
	
	public String getLogin() {
		return login;
	}
	public void setLogin(String login) {
		this.login = login;
	}
	public int getContributions() {
		return contributions;
	}
	public void setContributions(int contributions) {
		this.contributions = contributions;
	} 
}

Note: Make sure you have added the android.permission.INTERNET feature in the AndroidManifest.xml file. One also needs to add the following .jar files in the libs folder of the Android project.

  • retrofit-1.4.1.jar
  • okhttp-1.3.0-jar-with-dependencies.jar
  • gson-2.2.4.jar

Finally, save all changes. Make no errors are present. Run the application on an Android device and you should the following output in the Logcat window!

output

That’s it for this tutorial. Stay tuned for more! 🙂

Reference: Retrofit for Android

Display list of WiFi networks in Android

Hello everyone!

Android provides the WiFiManager class for managing all aspects of WiFi connectivity. It is used to to define the names of various Intent actions that are broadcast upon any sort of change in WiFi state.

Through this post, we will learn how to display a list of available WiFi networks to which an Android device can be connected. The list can be viewed and updated, and attributes of individual entries can be modified.

Pre-requisites: Eclipse IDE, Android SDK

In any of your existing Android projects, create a new Activity named CheckWifiNetworkActivity and add the following code!

CheckWifiNetworkActivity.java

package com.app.wifi;

import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.TextView;

public class CheckWifiNetworkActivity extends Activity {

	private StringBuilder sb = new StringBuilder();
	private TextView tv;
	List<ScanResult> scanList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main); 
		tv= (TextView)findViewById(R.id.txtWifiNetworks);
		getWifiNetworksList();
	}

	private void getWifiNetworksList(){      
		IntentFilter filter = new IntentFilter();
		filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		final WifiManager wifiManager = 
				(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);;
				registerReceiver(new BroadcastReceiver(){

					@SuppressLint("UseValueOf") @Override
					public void onReceive(Context context, Intent intent) {
						sb = new StringBuilder();
						scanList = wifiManager.getScanResults();
						sb.append("\n  Number Of Wifi connections :" + " " +scanList.size()+"\n\n");    
						for(int i = 0; i < scanList.size(); i++){
							sb.append(new Integer(i+1).toString() + ". ");
							sb.append((scanList.get(i)).toString());
							sb.append("\n\n");
						}

						tv.setText(sb);  
					}

				},filter);        
		wifiManager.startScan();
	}
}

activity.main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
      <TextView
        android:id="@+id/txtWifiNetworks"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"/>
 
</RelativeLayout>

Make sure you add the necessary permissions in the manifest file!

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app.wifi"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
   
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.app.wifi.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Save all changes and run the application on an Android device. If no errors occur then you should see the following output!

detect_wifi_network

Hope this helps. Stay tuned for more! 🙂

Tutorial #81: Using Volley networking library in Android

At Google I/O last year, the search engine giant showcased a faster way to make network requests within an Android application by introducing the Volley networking library. Volley includes a lot of features useful for managing network requests and their response caches in a fast and easy way.

One can use Volley to run simultaneous requests on a pool of threads that can be given priority over another. In addition, it can be used to handle JSON requests, image request or files of that size and nature.

In this tutorial, we will learn how to setup Volley for Android and write a sample code to make a JSON request.

Pre-requisites: Eclipse IDE, Android SDK, Windows 7 (64 bit)

Step 1: Clone the Volley repository

In order to clone the Volley repository you need to have git client installed on your machine. Open a new git window and run the following command:

F:\programs\volley> git clone https://android.googlesource.com/platform/frameworks/volley

If you don’t have the git client installed then you can download it from over here. Once the project has been cloned you need to obtain the .jar file. To generate volley.jar, move into volley directory (cd volley) and execute below commands.

android update project -p .

ant jar

The volley.jar file will get created inside the bin folder.

Step 2: Create Android project

Once we have obtained the .jar file we can go ahead and create a new Android application project called AndroidVolleyDemo.

As recommended, lets create first a Singleton class that will return an instance of RequestQueue and one of ImageLoader. Also, we need to include a method to add our request to the RequestQueue.

VolleySingleton.java

package com.app.volley;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class VolleySingleton {

	private static VolleySingleton instance;
	private RequestQueue requestQueue;
	private ImageLoader imageLoader;

	private VolleySingleton(Context context) {
		requestQueue = Volley.newRequestQueue(context);

		imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
			private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);


			@Override
			public Bitmap getBitmap(String url) {
				return cache.get(url);
			}

			@Override
			public void putBitmap(String url, Bitmap bitmap) {
				cache.put(url, bitmap);
			}
		});
	}


	public static VolleySingleton getInstance(Context context) {
		if (instance == null) {
			instance = new VolleySingleton(context);
		}
		return instance;
	}

	public RequestQueue getRequestQueue() {
		return requestQueue;
	}

	public ImageLoader getImageLoader() {
		return imageLoader;
	}

	public <T> void addToRequestQueue(Request<T> req) {
		req.setTag("App");
		getRequestQueue().add(req);
	}

}

Now, let’s create our Activity class as follows!

MainActivity.java

package com.app.volley;

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.TextView;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;

public class MainActivity extends Activity {

	private TextView responseText;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		responseText = (TextView)findViewById(R.id.txt1);
		
		String url = "http://echo.jsontest.com/key/value/one/two";

		final ProgressDialog pDialog = new ProgressDialog(this);
		pDialog.setMessage("Loading...");
		pDialog.show();     

		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
				url, null,
				new Response.Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response) {
				Log.d("App", response.toString());
				responseText.setText("Response:" + " " +response.toString());
				pDialog.hide();
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				VolleyLog.d("App", "Error: " + error.getMessage());
				// hide the progress dialog
				pDialog.hide();
			}
		});

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

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

Do not forget to add the Internet permission in the AndroidManifest.xml file!

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

Finally, run the application on an Android device. If no errors occur, you should see the response of the JSON request! 🙂

output