Skip to main content

How to call Web service or API on Android Application

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






                      





Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...