Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

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

}






                      





Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post