Android Restful Webservice Tutorial – How to call RESTful webservice in Android – Part 3

Android Restful Webservice Tutorial – How to call RESTful webservice in Android – Part 3

In the Android RESTful tutorial series , I am discussing about creating and invoking RESTful webservice in Android applications.

In this particular post, I am going to discuss about how to invoke RESTful webservice (that has been created and deployed in local application server) from inside Android applications.

I already discussed about What is RESTful webservice and how to create it in couple of posts earlier. Have listed those posts links below, it would be helpful for you if you quickly take a look at those articles.

If you are new to RESTful webservice, I would recommend you to take a look at Introduction to RESTful webservice

This tutorial series will be published as three parts:

In this post, I will be discussing about invoking RESTful webservice we already created in the previous post (Read: How to create RESTFul webservice in Java?).

If you haven’t created the RESTful webservice yet, please go ahead and create it before proceeding with below steps.

Video Demo

 

  
Steps involved in invoking RESTful webservice in Android application:

By looking at the video demo, you got to know what are we going to develop.

About application

  • It is a simple application to register and login the users.
  • During registration and logging-in, user credentials (Username and Password) are taken to Server using RESTful webservice to register or authenticate the User.

You can download source code from here if you don’t want to create Application from scratch, otherwise please proceed with below listings.

Step 1: Create Android Application Project

  • Create new android project [File >> New >> Android Application Project] with project name AndroidRestFulWSExample
  • Enter package name as ‘com.prgguru.example’
  • Choose Minimum Required SDK, Target SDK and Compile with. Confused on choosing these options? Take a look at Minimum Required SDK – Target SDK – Compile With post.
  • Click Next button and finally click ‘Finish’ to create project

Step 2: Add library to project

Add below third party library into project’s ‘lib’ folder. You can also download it if you don’t have it with you.

Android Asynchronous Http Client – An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries which is used by Pinterest, Instagram etc.,. Download

Step 3: Design Screens

We are going to have three activities:

HomeActivity – Home Screen of the Application. Launched once after successful login.

LoginActivity – Login screen of the application

RegisterActivity – Register screen of the application

Before creating screens, make sure below String resources are added. Add string resources to strings.xml present under /res/values folder.

strings.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<? xml version = "1.0" encoding = "utf-8" ?>
< resources >
 
     < string name = "app_name" >AndroidRestFulWSExample</ string >
     < string name = "hello_world" >Hello world!</ string >
     < string name = "action_settings" >Settings</ string >
     < string name = "title_activity_login" >Login</ string >
     < string name = "title_activity_home" >HomeActivity</ string >
     < string name = "register_title" >Register</ string >
     < string name = "login_title" >Login</ string >
     < string name = "name" >Name</ string >
     < string name = "email" >Email</ string >
     < string name = "pwd" >Password</ string >
< string name = "btnRegister" >Register</ string >
</ resources >

Create three layout XMLs under /res/layout folder:

home.xml

Home Screen of the application that will be launched once after successful login by User.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< FrameLayout xmlns:android = "http://schemas.android.com/apk/res/android"
     xmlns:tools = "http://schemas.android.com/tools"
     android:id = "@+id/container"
     android:layout_width = "match_parent"
     android:layout_height = "match_parent"
     tools:context = "com.prgguru.example.HomeActivity"
     tools:ignore = "MergeRootFrame" >
 
     < TextView
         android:layout_width = "fill_parent"
         android:layout_height = "fill_parent"
         android:layout_gravity = "fill_vertical"
         android:layout_marginTop = "20pt"
         android:gravity = "center_horizontal"
         android:text = "Welcome User"
         android:textSize = "25dip" />
 
</ FrameLayout >

login.xml

Login screen of the application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<? xml version = "1.0" encoding = "utf-8" ?>
< ScrollView xmlns:android = "http://schemas.android.com/apk/res/android"
     android:layout_width = "fill_parent"
     android:layout_height = "fill_parent" >
 
     < LinearLayout
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:orientation = "vertical"
         android:padding = "10dip" >
 
         < TextView
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:layout_marginBottom = "10dip"
             android:text = "@string/login_title"
             android:textSize = "25sp"
             android:textStyle = "bold" />
 
         < EditText
             android:id = "@+id/loginEmail"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:hint = "Enter your Email ID"
             android:inputType = "textEmailAddress" />
 
         < TextView
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:layout_marginTop = "15dip"
             android:text = "@string/pwd" />
 
         < EditText
             android:id = "@+id/loginPassword"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:hint = "Enter Password"
             android:inputType = "textPassword" />
 
         < TextView
             android:id = "@+id/login_error"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:padding = "10dip"
             android:textColor = "#e30000"
             android:textStyle = "bold" />
 
         < Button
             android:id = "@+id/btnLogin"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:layout_marginTop = "20dip"
             android:background = "#ff6347"
             android:onClick = "loginUser"
             android:text = "Login"
             android:textColor = "#fff" />
 
         < Button
             android:id = "@+id/btnLinkToRegisterScreen"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:layout_marginTop = "40dip"
             android:background = "@null"
             android:onClick = "navigatetoRegisterActivity"
             android:text = "Signup"
             android:textColor = "#228b22"
             android:textStyle = "bold" />
     </ LinearLayout >
 
</ ScrollView >

register.xml

Registration screen of the application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<? xml version = "1.0" encoding = "utf-8" ?>
< ScrollView xmlns:android = "http://schemas.android.com/apk/res/android"
     android:layout_width = "fill_parent"
     android:layout_height = "fill_parent" >
 
     < LinearLayout
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:orientation = "vertical"
         android:padding = "5dip" >
 
         <!-- View Title Label -->
 
         < TextView
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:layout_marginBottom = "10dip"
             android:text = "@string/register_title"
             android:textSize = "25sp"
             android:textStyle = "bold" />
         <!-- Name Label -->
 
         < TextView
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:text = "@string/name" />
         <!-- Name TextField -->
 
         < EditText
             android:id = "@+id/registerName"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content" android:hint = "Enter your Name" />
 
         <!-- Email Label -->
 
         < TextView
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:text = "@string/email" />
         <!-- Email TextField -->
 
         < EditText
             android:id = "@+id/registerEmail"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:hint = "Enter your Email ID"
             android:inputType = "textEmailAddress" />
 
         <!-- Password Label -->
 
         < TextView
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:layout_marginTop = "15dip"
             android:text = "@string/pwd" />
         <!-- Password TextField -->
 
         < EditText
             android:id = "@+id/registerPassword"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:hint = "Enter Password"
             android:inputType = "textPassword" />
 
         <!-- Error message -->
 
         < TextView
             android:id = "@+id/register_error"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:gravity = "center"
             android:padding = "10dip"
             android:textColor = "#e30000"
             android:textStyle = "bold" />
 
         < Button
             android:id = "@+id/btnRegister"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:layout_marginTop = "20dip"
             android:background = "#ff6347"
             android:onClick = "registerUser"
             android:text = "@string/btnRegister"
             android:textColor = "#fff" />
 
         <!-- Link to Login Screen -->
 
         < Button
             android:id = "@+id/btnLinkToLoginScreen"
             android:layout_width = "fill_parent"
             android:layout_height = "wrap_content"
             android:layout_marginTop = "20dip"
             android:background = "@null"
             android:onClick = "navigatetoLoginActivity"
             android:text = "Login"
             android:textColor = "#228b22"
             android:textStyle = "bold" />
     </ LinearLayout >
 
</ ScrollView >

Step 4: Utility.java – Utitlity Class

We are done with Layout designing, let us jump into Coding.

Create Utility.Java under the package com.prgguru.example and fill it with below code. It has Utility methods to be used in other Activity classes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.prgguru.example;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
  * Class which has Utility methods
  *
  */
public class Utility {
     private static Pattern pattern;
     private static Matcher matcher;
     //Email Pattern
     private static final String EMAIL_PATTERN =
             "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
             + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$" ;
 
     /**
      * Validate Email with regular expression
      *
      * @param email
      * @return true for Valid Email and false for Invalid Email
      */
     public static boolean validate(String email) {
         pattern = Pattern.compile(EMAIL_PATTERN);
         matcher = pattern.matcher(email);
         return matcher.matches();
 
     }
     /**
      * Checks for Null String object
      *
      * @param txt
      * @return true for not null and false for null String object
      */
     public static boolean isNotNull(String txt){
         return txt!= null && txt.trim().length()> 0 ? true : false ;
     }
}

Step 5: Home.java – Home Activity Class

Home screen Activity which will be launched once after successful login by User.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.prgguru.example;
 
import android.app.Activity;
import android.os.Bundle;
/**
  *
  * Home Screen Activity
  */
public class HomeActivity extends Activity {
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         //Displays Home Screen
         setContentView(R.layout.home);
     }
 
}

Step 6: LoginActivity.java – Login Screen Activity Class

Login screen which will allow User to login to Application. Make sure the IP address has been changed in the AsyncHttp Get method with localhost or IP address of your machine.

LoginActivity.java is well commented, so by reading the comments you will understand the meaning of it. In case, if you still have question 29 Comments it right away.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package com.prgguru.example;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
/**
  *
  * Login Activity Class
  *
  */
public class LoginActivity extends Activity {
     // Progress Dialog Object
     ProgressDialog prgDialog;
     // Error Msg TextView Object
     TextView errorMsg;
     // Email Edit View Object
     EditText emailET;
     // Passwprd Edit View Object
     EditText pwdET;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.login);
         // Find Error Msg Text View control by ID
         errorMsg = (TextView)findViewById(R.id.login_error);
         // Find Email Edit View control by ID
         emailET = (EditText)findViewById(R.id.loginEmail);
         // Find Password Edit View control by ID
         pwdET = (EditText)findViewById(R.id.loginPassword);
         // Instantiate Progress Dialog object
         prgDialog = new ProgressDialog( this );
         // Set Progress Dialog Text
         prgDialog.setMessage( "Please wait..." );
         // Set Cancelable as False
         prgDialog.setCancelable( false );
     }
 
     /**
      * Method gets triggered when Login button is clicked
      *
      * @param view
      */
     public void loginUser(View view){
         // Get Email Edit View Value
         String email = emailET.getText().toString();
         // Get Password Edit View Value
         String password = pwdET.getText().toString();
         // Instantiate Http Request Param Object
         RequestParams params = new RequestParams();
         // When Email Edit View and Password Edit View have values other than Null
         if (Utility.isNotNull(email) && Utility.isNotNull(password)){
             // When Email entered is Valid
             if (Utility.validate(email)){
                 // Put Http parameter username with value of Email Edit View control
                 params.put( "username" , email);
                 // Put Http parameter password with value of Password Edit Value control
                 params.put( "password" , password);
                 // Invoke RESTful Web Service with Http parameters
                 invokeWS(params);
             }
             // When Email is invalid
             else {
                 Toast.makeText(getApplicationContext(), "Please enter valid email" , Toast.LENGTH_LONG).show();
             }
         } else {
             Toast.makeText(getApplicationContext(), "Please fill the form, don't leave any field blank" , Toast.LENGTH_LONG).show();
         }
 
     }
 
     /**
      * Method that performs RESTful webservice invocations
      *
      * @param params
      */
     public void invokeWS(RequestParams params){
         // Show Progress Dialog
          prgDialog.show();
          // Make RESTful webservice call using AsyncHttpClient object
          AsyncHttpClient client = new AsyncHttpClient();
          client.get( "http://192.168.2.2:9999/useraccount/login/dologin" ,params , new AsyncHttpResponseHandler() {
              // When the response returned by REST has Http response code '200'
              @Override
              public void onSuccess(String response) {
                  // Hide Progress Dialog
                  prgDialog.hide();
                  try {
                           // JSON Object
                          JSONObject obj = new JSONObject(response);
                          // When the JSON response has status boolean value assigned with true
                          if (obj.getBoolean( "status" )){
                              Toast.makeText(getApplicationContext(), "You are successfully logged in!" , Toast.LENGTH_LONG).show();
                              // Navigate to Home screen
                              navigatetoHomeActivity();
                          }
                          // Else display error message
                          else {
                              errorMsg.setText(obj.getString( "error_msg" ));
                              Toast.makeText(getApplicationContext(), obj.getString( "error_msg" ), Toast.LENGTH_LONG).show();
                          }
                  } catch (JSONException e) {
                      // TODO Auto-generated catch block
                      Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!" , Toast.LENGTH_LONG).show();
                      e.printStackTrace();
 
                  }
              }
              // When the response returned by REST has Http response code other than '200'
              @Override
              public void onFailure( int statusCode, Throwable error,
                  String content) {
                  // Hide Progress Dialog
                  prgDialog.hide();
                  // When Http response code is '404'
                  if (statusCode == 404 ){
                      Toast.makeText(getApplicationContext(), "Requested resource not found" , Toast.LENGTH_LONG).show();
                  }
                  // When Http response code is '500'
                  else if (statusCode == 500 ){
                      Toast.makeText(getApplicationContext(), "Something went wrong at server end" , Toast.LENGTH_LONG).show();
                  }
                  // When Http response code other than 404, 500
                  else {
                      Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]" , Toast.LENGTH_LONG).show();
                  }
              }
          });
     }
 
     /**
      * Method which navigates from Login Activity to Home Activity
      */
     public void navigatetoHomeActivity(){
         Intent homeIntent = new Intent(getApplicationContext(),HomeActivity. class );
         homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         startActivity(homeIntent);
     }
 
     /**
      * Method gets triggered when Register button is clicked
      *
      * @param view
      */
     public void navigatetoRegisterActivity(View view){
         Intent loginIntent = new Intent(getApplicationContext(),RegisterActivity. class );
         loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         startActivity(loginIntent);
     }
 
}

Step 7: RegisterActivity.java – RegisterScreen Activity Class

Register screen which will allow User to register him/herself to the Application. Make sure the IP address has been changed in the AsyncHttp Get method with localhost or IP address of your machine:

RegisterActivity.java is well commented, so by reading the comments you will understand the meaning of it. In case, if you still have question 29 Comments it right away.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package com.prgguru.example;
 
import org.json.JSONException;
import org.json.JSONObject;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
/**
  *
  * Register Activity Class
  */
public class RegisterActivity extends Activity {
     // Progress Dialog Object
     ProgressDialog prgDialog;
     // Error Msg TextView Object
     TextView errorMsg;
     // Name Edit View Object
     EditText nameET;
     // Email Edit View Object
     EditText emailET;
     // Passwprd Edit View Object
     EditText pwdET;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.register);
         // Find Error Msg Text View control by ID
         errorMsg = (TextView)findViewById(R.id.register_error);
         // Find Name Edit View control by ID
         nameET = (EditText)findViewById(R.id.registerName);
         // Find Email Edit View control by ID
         emailET = (EditText)findViewById(R.id.registerEmail);
         // Find Password Edit View control by ID
         pwdET = (EditText)findViewById(R.id.registerPassword);
         // Instantiate Progress Dialog object
         prgDialog = new ProgressDialog( this );
         // Set Progress Dialog Text
         prgDialog.setMessage( "Please wait..." );
         // Set Cancelable as False
         prgDialog.setCancelable( false );
     }
 
     /**
      * Method gets triggered when Register button is clicked
      *
      * @param view
      */
     public void registerUser(View view){
         // Get NAme ET control value
         String name = nameET.getText().toString();
         // Get Email ET control value
         String email = emailET.getText().toString();
         // Get Password ET control value
         String password = pwdET.getText().toString();
         // Instantiate Http Request Param Object
         RequestParams params = new RequestParams();
         // When Name Edit View, Email Edit View and Password Edit View have values other than Null
         if (Utility.isNotNull(name) && Utility.isNotNull(email) && Utility.isNotNull(password)){
             // When Email entered is Valid
             if (Utility.validate(email)){
                 // Put Http parameter name with value of Name Edit View control
                 params.put( "name" , name);
                 // Put Http parameter username with value of Email Edit View control
                 params.put( "username" , email);
                 // Put Http parameter password with value of Password Edit View control
                 params.put( "password" , password);
                 // Invoke RESTful Web Service with Http parameters
                 invokeWS(params);
             }
             // When Email is invalid
             else {
                 Toast.makeText(getApplicationContext(), "Please enter valid email" , Toast.LENGTH_LONG).show();
             }
         }
         // When any of the Edit View control left blank
         else {
             Toast.makeText(getApplicationContext(), "Please fill the form, don't leave any field blank" , Toast.LENGTH_LONG).show();
         }
 
     }
 
     /**
      * Method that performs RESTful webservice invocations
      *
      * @param params
      */
     public void invokeWS(RequestParams params){
         // Show Progress Dialog
         prgDialog.show();
         // Make RESTful webservice call using AsyncHttpClient object
         AsyncHttpClient client = new AsyncHttpClient();
         client.get( "http://192.168.2.2:9999/useraccount/register/doregister" ,params , new AsyncHttpResponseHandler() {
             // When the response returned by REST has Http response code '200'
              @Override
              public void onSuccess(String response) {
                 // Hide Progress Dialog
                  prgDialog.hide();
                  try {
                           // JSON Object
                          JSONObject obj = new JSONObject(response);
                          // When the JSON response has status boolean value assigned with true
                          if (obj.getBoolean( "status" )){
                              // Set Default Values for Edit View controls
                              setDefaultValues();
                              // Display successfully registered message using Toast
                              Toast.makeText(getApplicationContext(), "You are successfully registered!" , Toast.LENGTH_LONG).show();
                          }
                          // Else display error message
                          else {
                              errorMsg.setText(obj.getString( "error_msg" ));
                              Toast.makeText(getApplicationContext(), obj.getString( "error_msg" ), Toast.LENGTH_LONG).show();
                          }
                  } catch (JSONException e) {
                      // TODO Auto-generated catch block
                      Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!" , Toast.LENGTH_LONG).show();
                      e.printStackTrace();
 
                  }
              }
              // When the response returned by REST has Http response code other than '200'
              @Override
              public void onFailure( int statusCode, Throwable error,
                  String content) {
                  // Hide Progress Dialog
                  prgDialog.hide();
                  // When Http response code is '404'
                  if (statusCode == 404 ){
                      Toast.makeText(getApplicationContext(), "Requested resource not found" , Toast.LENGTH_LONG).show();
                  }
                  // When Http response code is '500'
                  else if (statusCode == 500 ){
                      Toast.makeText(getApplicationContext(), "Something went wrong at server end" , Toast.LENGTH_LONG).show();
                  }
                  // When Http response code other than 404, 500
                  else {
                      Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]" , Toast.LENGTH_LONG).show();
                  }
              }
          });
     }
 
     /**
      * Method which navigates from Register Activity to Login Activity
      */
     public void navigatetoLoginActivity(View view){
         Intent loginIntent = new Intent(getApplicationContext(),LoginActivity. class );
         // Clears History of Activity
         loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         startActivity(loginIntent);
     }
 
     /**
      * Set degault values for Edit View controls
      */
     public void setDefaultValues(){
         nameET.setText( "" );
         emailET.setText( "" );
         pwdET.setText( "" );
     }
 
}

Step 8: Add Activities in AndroidManifest.xml

Make sure you added activities we created in AndroidManifest.xml.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<? xml version = "1.0" encoding = "utf-8" ?>
< manifest xmlns:android = "http://schemas.android.com/apk/res/android"
     package = "com.prgguru.example"
     android:versionCode = "1"
     android:versionName = "1.0" >
 
     < uses-sdk
         android:minSdkVersion = "8"
         android:targetSdkVersion = "19" />
 
     < uses-permission android:name = "android.permission.INTERNET" />
 
     < application
         android:allowBackup = "true"
         android:icon = "@drawable/ic_launcher"
         android:label = "@string/app_name"
         android:theme = "@style/AppTheme" >
         < activity
             android:name = "com.prgguru.example.RegisterActivity"
             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 = "com.prgguru.example.LoginActivity"
             android:label = "@string/title_activity_login" >
         </ activity >
         < activity
             android:name = "com.prgguru.example.HomeActivity"
             android:label = "@string/title_activity_home" >
         </ activity >
     </ application >
 
</ manifest >

Step 9: Add Permission in AndroidManifest.xml

Don’t forget to add internet permission in AndroidManifest.xml:

1
2
<!-- Permission: Allow application to connect to Internet -->
  < uses-permission android:name = "android.permission.INTERNET" />
Error Handling

When the Http response code returned by REST web service is other 200, which means an error might have occurred at server end. Error can be easily handled inside onFailure() method of AsyncHttpClient’s post method as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
public void onFailure( int statusCode, Throwable error,
          String content) {
          // Hide Progress Dialog
          prgDialog.hide();
          // When Http response code is '404'
          if (statusCode == 404 ){
              Toast.makeText(getApplicationContext(), "Requested resource not found" , Toast.LENGTH_LONG).show();
          }
          // When Http response code is '500'
          else if (statusCode == 500 ){
              Toast.makeText(getApplicationContext(), "Something went wrong at server end" , Toast.LENGTH_LONG).show();
          }
          // When Http response code other than 404, 500
          else {
              Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]" , Toast.LENGTH_LONG).show();
          }
  }
RESTful Webservice Response – JSON

Login
When login is successful, the JSON returned by REST will look like:

1
2
3
4
{
tag: "login"
status: true
}

When login is unsuccessful (User entered incorrect Username or Password), the JSON returned by REST will look like:

1
2
3
4
5
{
tag: "login"
status: false
error_msg: "Incorrect Email or Password"
}

Registration
When registration is successful, the JSON returned by REST will look like:

1
2
3
4
{
tag: "register"
status: true
}

When registration is unsuccessful (User already registered), the JSON returned by REST will look like:

1
2
3
4
5
{
tag: "register"
status: false
error_msg: "You are already registered"
}

[pglinkadssmall1]

Demo

Make sure the RESTful webservice you created is up and running.

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.




Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse).

Download Source Code

*apk in Android  is the installation file similar to exe in windows.

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

Share

You are always welcome to provide your comments and feedback from 29 Comments box.

[pgwriteforus]

[pgfeedback]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值