The Android Network connection Operations
In this Networking tutorial, you will create a simple app which connects to the GitHub API to retrieve and display JSON responce.
Here, we will learn about the following:
Add the Method
Note:
Since OkHttp is built as a Java library, and not an Android library, it doesn’t take into consideration the Android Framework limitations of only permitting view updates on the main UI thread. To update any views, or post data back to the main thread, you will need to use
To use Volley, add the following dependency to build.gradle of the app module and rebuild the project:
To use Retrofit, add the following dependencies to build.gradle of the app module and rebuild the project:
Take a look to other annotations:
@Path – variable substitution for the API endpoint. For example movie id will be swapped for{id} in the URL endpoint.
@Query – specifies the query key name with the value of the annotated parameter.
@Body – payload for the POST call
@Header – specifies the header with the value of the annotated parameter.
Here, we will learn about the following:
- How to check your network connection status.
- How to perform network operations.
- How to use open source libraries to perform network operations.
Required Permissions.
Open AndroidManifest.xml, and add the following permissions just before the<application tag:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
Checking the Network Connection.
Open MainActivity.java, and add the following method to the class:
private boolean isNetworkConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); }
Determining the Connection Type.
private boolean isWifiConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return networkInfo != null && (ConnectivityManager.TYPE_WIFI == networkInfo.getType()) && networkInfo.isConnected(); }
Build and run your app; if your device is connected to a network, the app will show a ProgressDialog like so:
Now turn off all network connections on your device and start the app
again. The app should now show an alert with the Internet connection
error message as above screen.
Performing Network Operations using AsyncTask Class.
package com.kotlincoders.android.networkconnection; import android.os.AsyncTask; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by ravi on 1/30/18. */ public class DownloadDataTask extends AsyncTask<String, Integer, String> { DownloadCompleteListener downloadCompleteListener; public DownloadDataTask(DownloadCompleteListener downloadCompleteListener) { this.downloadCompleteListener = downloadCompleteListener; } @Override protected String doInBackground(String... strings) { try { return DownloadDATA(strings[0]); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); downloadCompleteListener.downloadCompleteData(s); } private String DownloadDATA(String urlString) throws IOException { InputStream inputStream = null; try { URL url = new URL(urlString); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); inputStream = httpURLConnection.getInputStream(); return convertStremToString(inputStream); } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } finally { if (inputStream != null) { inputStream.close(); } } } private String convertStremToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } return new String(stringBuilder); } }
Note:
AsyncTask<String, Integer, String>
The first parameter in the diamond operator determines the type of the input parameter to the doInBackground method while the third parameter in the diamond operator determines the type of the return value of the onPostExecute method. The second parameter determines the type of the return value of the onProgressUpdate method
.
We need to pass the downloaded data on to the Activity that started the task. we can use a listener, a type of interface, for this. DownloadCompleteListener.Java
Add
implements
DownloadCompleteListener
to the beginning of the class declaration of MainActivity.java so it looks like the following: public class MainActivity extends AppCompatActivity implements DownloadCompleteListener {
In the activity_main.xml make UI layouts as following.
Add the Method startDownload()
in MainActivity.java and also in Onclick property of Every Buttons.
(Hint:android:onClick="startDownload")
public void startDownload(View view) { txt_result.setText(" "); int id = view.getId(); if (isNetworkConnected()) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("Please wait..."); mProgressDialog.setCancelable(false); mProgressDialog.show(); if (id == R.id.AsyncTask) { new DownloadDataTask(this).execute(URL); } else if (id == R.id.Volley) { ConnectWithVolley(URL); } else if (id == R.id.OkHTTP) { ConnectWithOkHttp(URL); } else if (id == R.id.RetrofitCalls) { ConnectWithRetrofitCalls(URL); } } else { new AlertDialog.Builder(this) .setTitle("No Internet Connection") .setMessage("It looks like your internet connection is off. Please turn it " + "on and try again") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).setIcon(android.R.drawable.ic_dialog_alert).show(); } }
Open Source To The Rescue.
There are a number of open source libraries that simplify a lot of Android networking operations.Okhttp, Volley and Retrofit.We will each library One by One as fallows.
1:- OkHttp
OkHttp is an efficient HTTP client which supports synchronous and asynchronous calls. It handles the opening and closing of connections along with InputStream-to-string conversion.Note:
Since OkHttp is built as a Java library, and not an Android library, it doesn’t take into consideration the Android Framework limitations of only permitting view updates on the main UI thread. To update any views, or post data back to the main thread, you will need to use
runOnUiThread()
provided in the Android Activity superclass.To use OkHttp, you have to first add it as a dependency to your project.
Add the following dependency to build.gradle of the app module:compile 'com.squareup.okhttp3:okhttp:3.1.2'
Open MainActivity.java and add the following method:private void ConnectWithOkHttp(String url) { OkHttpClient client = new OkHttpClient(); Log.e("MainActivity", "BaseURL===>" + url); okhttp3.Request request = new okhttp3.Request.Builder().url(url).build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException { final String result = response.body().string(); Log.e("MainActivity", "onResponse===>" + result); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { downloadCompleteData(result); } }); } }); }
2:- Volley
Volley is an Android library for making fast and easy network calls,Volley makes all calls in an asynchronous manner. Since it’s an Android library, it doesn’t require any extra work to return data to the main thread or update views.To use Volley, add the following dependency to build.gradle of the app module and rebuild the project:
compile 'com.android.volley:volley:1.0.0'
Open MainActivity.java and add the following method:
private void ConnectWithVolley(String sURL) { RequestQueue requestQueue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.GET, sURL, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { downloadCompleteData(response); } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (mProgressDialog != null) { mProgressDialog.hide(); } } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { // HashMap Parameters for in Case POST mehto call Map<String, String> params = new HashMap<String, String>(); params.put("name", " "); params.put("domain", " "); return params; } }; requestQueue.add(stringRequest); }
Volley is one of the best tool for working with network requests. I have considered most common cases which can be helpful in your projects.
3:- Retrofit
Retrofit is an Android and Java library which is great at retrieving and uploading structured data such as JSON and XML. Retrofit makes HTTP requests using OkHttp. Unlike the case of Volley, where you have to convert a JSON string to a Repository object, Retrofit does that conversion for you. Retrofit also lets you specify any of the following libraries for the data conversion:To use Retrofit, add the following dependencies to build.gradle of the app module and rebuild the project:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
Define the Endpoints
The endpoints are defined inside of an interface using special retrofit annotations to encode details about the parameters and request method. In addition, the return value is always a parameterized Call<T> object such asCall<ArrayList<Repository>>.
For instance, the interface defines each endpoint in the following way.
Then create a new interface and name it RetrofitAPI; this will define the HTTP operations.
package com.kotlincoders.android.networkconnection; import java.util.ArrayList; import retrofit2.Call; import retrofit2.http.GET; /** * Created by ravi on 1/30/18. */ interface RetrofitAPI { @GET("/repositories") Call<ArrayList<Repository>> retrieveRepositories(); }
So, using this route the retrofit will generate the following URL:
https://api.github.com/repositories
Note:Each endpoint specifies an annotation of the HTTP method (GET, POST, etc.) and the parameters of this method can also have special annotations (@Query, @Path, @Body etc.)
Take a look to other annotations:
@Path – variable substitution for the API endpoint. For example movie id will be swapped for{id} in the URL endpoint.
@Query – specifies the query key name with the value of the annotated parameter.
@Body – payload for the POST call
@Header – specifies the header with the value of the annotated parameter.
Now open MainActivity.java and add the following method:
private void ConnectWithRetrofitCalls(String BaseURL) { Log.e("MainActivity", "BaseURL=>" + BaseURL); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BaseURL) // 1 .addConverterFactory(GsonConverterFactory.create()) .build(); RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class); Call<ArrayList<Repository>> call = retrofitAPI.retrieveRepositories(); call.enqueue(new Callback<ArrayList<Repository>>() { @Override public void onResponse(Call<ArrayList<Repository>> call, retrofit2.Response<ArrayList<Repository>> response) { mRepos = response.body(); String name = mRepos.get(0).getName(); String fullname = mRepos.get(0).getFullName(); String htmlURl = mRepos.get(0).getHTMLurl(); String login = mRepos.get(0).getOwner().getLogin(); String result = "Here we are just fetching only 1st index json data.\n\n\n\n\n" + name + "\n" + fullname + "\n" + htmlURl + "\n" + login + "\n"; Log.e("MainActivity", "htmlURl---->" + htmlURl); Log.e("MainActivity", "name---->" + name); Log.e("MainActivity", "fullname---->" + fullname); Log.e("MainActivity", "CoonectRetrofitCalls---->" + login); downloadCompleteData(result); } @Override public void onFailure(Call<ArrayList<Repository>> call, Throwable t) { Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); if (mProgressDialog != null) { mProgressDialog.hide(); } } }); }
Retrofit Output:-
DownloadDataTask,Volley And OkHttp Output:-
Comments
Post a Comment