Android Web Service Tutorial

To authenticate or save the information in an external database like oracle, MySQL, PostgreSQL, SQL server using other applications developed in java, .net, PHP, etc., languages, a restful web service application is created in android.

What is Web Service?

For exchanging information between two or more different types of applications, irrespective of their language or platform, a standard is set and that is known as Web Service. For example, we can use the Web Service for exchanging information between an android application and java or .net application.

Example:

File: activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:hint="Username"
        android:ems="10" />
 
    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="67dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="24dp"
        android:layout_toRightOf="@+id/button1"
        android:text="Sign Up" />
 
    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="22dp" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/progressBar1"
        android:layout_marginLeft="22dp"
        android:text="Sign In" />
 
</RelativeLayout>

File: activity_register_user.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".RegisterUser">
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:ems="10"
        android:hint="Name" />
 
    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="50dp"
        android:ems="10"
        android:hint="New Password"
        android:inputType="textPassword" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Register" />
 
    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="87dp" />
 
</RelativeLayout>

File: build.gradle:

apply plugin: 'com.android.application'
 
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.radioapp"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            assets {
                srcDirs 'src/main/assets', 'src/main/res/assets/'
            }
        }
    }
}
 
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
 
 
        android {
            useLibrary 'org.apache.http.legacy'
        }
 
}

Activity class:(File: MainActivity.java)

package com.example.radioapp;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
 
public class MainActivity extends Activity {
    EditText password,userName;
    Button login,register;
    ProgressBar progressBar;
 
 
 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        password=(EditText) findViewById(R.id.editText2);
        userName=(EditText) findViewById(R.id.editText1);
        login=(Button) findViewById(R.id.button1);
        register=(Button) findViewById(R.id.button2);
 
        //progess_msz.setVisibility(View.GONE);
        progressBar=(ProgressBar) findViewById(R.id.progressBar1);
        progressBar.setVisibility(View.GONE);
 
 
        register.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent  intent=new Intent(MainActivity.this, RegisterUser.class);
                startActivity(intent);
            }
        });
        login.setOnClickListener(new OnClickListener() {
 
            public void onClick(View v) {
                progressBar.setVisibility(View.VISIBLE);
 
                String s1=userName.getText().toString();
                String s2=password.getText().toString();
                new ExecuteTask().execute(s1,s2);
 
            }
        });
 
 
    }
 
    class ExecuteTask extends AsyncTask<String, Integer, String>
    {
 
        @Override
        protected String doInBackground(String... params) {
 
            String res=PostData(params);
 
            return res;
        }
 
        @SuppressLint("WrongConstant")
        @Override
        protected void onPostExecute(String result) {
            progressBar.setVisibility(View.GONE);
            //progess_msz.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), result, 3000).show();
        }
 
    }
 
    public String PostData(String[] values) {
        String s="";
        try
        {
            HttpClient httpClient=new DefaultHttpClient();
            HttpPost httpPost=new HttpPost("http://10.0.0.8:7777/HttpPostServlet/servlet/Login");
 
            List<NameValuePair> list=new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("name", values[0]));
            list.add(new BasicNameValuePair("pass",values[1]));
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse httpResponse=  httpClient.execute(httpPost);
 
            HttpEntity httpEntity=httpResponse.getEntity();
            s= readResponse(httpResponse);
 
        }
        catch(Exception exception)  {}
        return s;
 
 
    }
    public String readResponse(HttpResponse res) {
        InputStream is=null;
        String return_text="";
        try {
            is=res.getEntity().getContent();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
            String line="";
            StringBuffer sb=new StringBuffer();
            while ((line=bufferedReader.readLine())!=null)
            {
                sb.append(line);
            }
            return_text=sb.toString();
        } catch (Exception e)
        {
 
        }
        return return_text;
 
    }
 
}

RegisterUser class:(File: RegisterUser.java)

package com.example.radioapp;
 
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
 
public class RegisterUser extends Activity {
    EditText userName,password;
    Button register,login;
    ProgressBar progressBar;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_user);
        userName=(EditText) findViewById(R.id.editText1);;
        password=(EditText) findViewById(R.id.editText2);
        register=(Button) findViewById(R.id.button1);
 
        progressBar=(ProgressBar) findViewById(R.id.progressBar1);
        progressBar.setVisibility(View.GONE);
 
        register.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
 
                progressBar.setVisibility(View.VISIBLE);
 
                String s1=userName.getText().toString();
                String s2=password.getText().toString();
                new ExecuteTask().execute(s1,s2);
            }
        });
 
 
 
 
    }
 
    class ExecuteTask extends AsyncTask<String, Integer, String>
    {
 
        @Override
        protected String doInBackground(String... params) {
 
            PostData(params);
            return null;
        }
 
        @Override
        protected void onPostExecute(String result) {
            progressBar.setVisibility(View.GONE);
        }
 
    }
 
 
 
    public void PostData(String[] values) {
        try
        {
            HttpClient httpClient=new DefaultHttpClient();
            HttpPost httpPost=new HttpPost(
                    "http://10.0.0.8:7777/HttpPostServlet/servlet/httpPostServlet");
            List<NameValuePair> list=new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("name", values[0]));
            list.add(new BasicNameValuePair("pass",values[1]));
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            httpClient.execute(httpPost);
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
 
    }
 
}

AndroidManifest:(File: AndroidManifest.xml)

In the AndroidManifest.xml file, we will add the code to provide the INTERNET permission.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.radioapp">
 
    <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
        <activity
            android:name=".RegisterUser"
            android:label="@string/app_name" >
        </activity>
    </application>
 
</manifest>

Output 1:

Output 2:

Please follow and like us:
Content Protection by DMCA.com