How to call Web service or API on Android Application

0

 How to call Web service or API in Android Application?


Web service is used to communicate data from one platform to another using a web URL and Web method.

URL provides the location of resource and Web method is used to sending and receiving data.

Mostly we use Four Different Web Method?


1)  HttpPost:-  It is used to send data from client to server machine.it is a secure method hence we always use data insertion using HttpPost.


2)  HttpGet:-  It is used to send data from client to server machine, it is mostly used to select data from a database.


3)  HttpPut:-  It is used to create update web services.


4)  HttpDelete:-  It is used to create delete web services.


5) patch:-  It is used to create partial update web services.


As an android developer, you should know about Web URL, Web Method, Input Parameter, and Output Parameter.



Step to implement Web Service using ASYNCTASK?

1)  Create HTTPHANDLER Class 

package com.example.webviewexample;

import android.util.Log;

import java.io.BufferedInputStream;
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.ProtocolException;
import java.net.URL;

public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}



}

2)  Create Activity and Write following code XML file:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</RelativeLayout>

3)  Create Custom Layout for Activity (list_item.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>

<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="@color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />

<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="@color/colorAccent" />

<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>


4)  Code of MainActivity that contain calling of webservice method and create Inner class GetContact
that extends with AsyncTask

package com.example.webviewexample;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity2 extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;
private static String url = "https://api.androidhive.info/contacts/";
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContact().execute();
}

private class GetContact extends AsyncTask<Void ,Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity2.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {

try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");

// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");

// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();

// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);

// adding contact to contact list
contactList.add(contact);
}

} catch (final JSONException ex) {

}
}
return null;
}

@Override
protected void onPostExecute(Void result){

super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();

ListAdapter adapter = new SimpleAdapter(
MainActivity2.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}

}



GET DATA FROM API WITHOUT KEY:-

1)  All Code will be same only changed on   Main Activity and GETDetails doInBackground():-


package com.example.testapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class APIActivity13 extends AppCompatActivity {

ListView lstdata;
//private static String url = "https://shivaconceptdigital.com/api/viewallcourse.php";
private static String url = "https://gorest.co.in/public/v2/users";
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apiactivity13);
contactList = new ArrayList<>();
lstdata = findViewById(R.id.list);
new GetUserDetails().execute();

}
private class GetUserDetails extends AsyncTask<Void,Void,Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(APIActivity13.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}
@Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {

try {

JSONArray contacts = new JSONArray(jsonStr);

for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String gender = c.getString("gender");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("gender", gender);
contactList.add(contact);
}
}
catch (Exception e) {
e.printStackTrace();
}



}
return null;
}
@Override
protected void onPostExecute(Void result){

super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();

ListAdapter adapter = new SimpleAdapter(
APIActivity13.this, contactList,
R.layout.list_item, new String[]{"id","name", "email",
"gender"}, new int[]{R.id.id,R.id.name,
R.id.email, R.id.gender});
lstdata.setAdapter(adapter);
}
}
}






                      





Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)