Web Service

How the REST API works between Android Application and PHP Web Server

By akplays7 June 14, 2019 No Comments

Before going deeper into web service API implementation, Let’s go through the what is web service, why do we need a web service, what is REST API and then implementation.

Web Service

Web service is a collection of open protocols and standards used for exchanging data between two different applications or systems.

Why do we need a Web Service?

Web Service allows various applications to communicate and share information with each other. For Example, Java Application can communicate to PHP application through API.

Basically, our Android application cannot access our web server directly. So we need some medium between our application and web server. To interact with the MySQL database that resides on our web server, we need to build REST API.

What is RESTful Web Service?

REpresentational State Transfer API is an Application Programming Interface that uses HTTP method to process the data.

Steps to implement web service for Android Application and PHP Application

  1. Create a web service(PHP).
  2. Initialize the web service URL.
  3. Create a Java class for sending HTTP Request.
  4. Implement Login Activity interaction with PHP Web Server.

1. Create a Web service

To create a Web service, create a new PHP file called api.php.  Create a database and configure the database information in the config.php file and include the file in api.php. Create a users table with the following fields (id, username, email, phone, password).

The final code for user login API.

<?php
	require_once 'config.php';
	$response = array();
	if(isset($_GET['apicall'])){
		switch($_GET['apicall']){

		case 'login':
									
			$username = $_POST['username'];
			$password = md5($_POST['password']);			
			$stmt = $con->prepare("SELECT id, username, email, phone FROM users WHERE username = ? AND password = ?");
			$stmt->bind_param("ss",$username, $password);
			$stmt->execute();
			$stmt->store_result();
			if($stmt->num_rows > 0){
				$stmt->bind_result($id, $username, $email, $phone);
				$stmt->fetch();
				$user = array(
					'id'=>$id, 
					'username'=>$username, 
					'email'=>$email,
					'phone'=>$phone
				);
				$response['error'] = false; 
				$response['message'] = 'Login successful'; 
				$response['user'] = $user; 
			}else{
				$response['error'] = false; 
				$response['message'] = 'Invalid username or password';
			}
		break; 

		default: 
			$response['error'] = true; 
			$response['message'] = 'Invalid Operation Called';
		}
	}
	else{
		$response['error'] = true; 
		$response['message'] = 'Invalid API Call';
	}

We can further add multiple API calls like Sign Up, Forgot Password and Reset Password. We just need to create another case for Sign Up, Forgot Password and Reset Password.

2.Initialize the web service URL

Create a new Java class called WebServiceURL.java and add the following code.

public class WebServiceURL {

   private static final String ROOT_URL = "http://138.58.91.233/TinnysAndroidAppTest/api.php?apicall=";

   public static final String URL_REGISTER = ROOT_URL + "signup";
   public static final String URL_LOGIN = ROOT_URL + "login";
   public static final String URL_PRODUCT = ROOT_URL + "product";
   public static final String URL_UPDATEUSER = ROOT_URL + "update";
   public static final String URL_FORGOTPASSWORD = ROOT_URL + "forgotPassword";
   public static final String URL_RESETPASSWORD = ROOT_URL + "resetPassword";
   public static final String URL_ORDERCONFIRM = ROOT_URL + "orderConfirm";
}

Note: On the above code 138.58.91.233 – Change your IP address. Localhost will not work for the API call.

3. Create a class for sending http Request

In this example, we have used only the POST request. To send a POST request to Web Service URL, Create another Java class called RequestHandler.java.

public class RequestHandler {
       public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
       URL url;
       StringBuilder sb = new StringBuilder();
       try {
           url = new URL(requestURL);
           HttpURLConnection conn = (HttpURLConnection) url.openConnection();
           conn.setReadTimeout(15000);
           conn.setConnectTimeout(15000);
           conn.setRequestMethod("POST");
           conn.setDoInput(true);
           conn.setDoOutput(true);

           OutputStream os = conn.getOutputStream();

           BufferedWriter writer = new BufferedWriter(
                   new OutputStreamWriter(os, "UTF-8"));
           writer.write(getPostDataString(postDataParams));

           writer.flush();
           writer.close();
           os.close();
           int responseCode = conn.getResponseCode();

           if (responseCode == HttpsURLConnection.HTTP_OK) {

               BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
               sb = new StringBuilder();
               String response;

               while ((response = br.readLine()) != null) {
                   sb.append(response);
               }
           }

       } catch (Exception e) {
           e.printStackTrace();
       }
       return sb.toString();
   }


   //this method is converting key-value pairs data into a query string as needed to send to the server
   private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
       StringBuilder result = new StringBuilder();
       boolean first = true;
       for (Map.Entry<String, String> entry : params.entrySet()) {
           if (first)
               first = false;
           else
               result.append("&");

           result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
           result.append("=");
           result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
       }

       return result.toString();
   }
}

4. Implement Login Activity interaction with PHP Web Server.

Create a new activity called LoginActivity.  Design the login screen in activity_login.xml with two fields Username and Password field.

Create / Implement the following functions in LoginActivity.java.

  1. Initialize the Username and Password edit text fields.
  2. If user presses the login button, call the user login function. user login function will have the following functions.
    • First, get a user entered values of Username and Password field.
    • Validating the input by checking not empty fields.
    • If validation is passed, Create a request handler object to send the request to the web server.
    • Then create a request parameters for username and password.
    • Return the Response of the POST request.
    • Convert the Response to the JSON object.
    • Getting the user information from the response.
    • Create a new user object.
    • Store the user object information into the shared preference manager.
    • Start another Activity / Dashboard Activity.
    •  

Add the following code inside the LoginActivity.java. Final Code will look like this.


public class LoginActivity extends AppCompatActivity {

   EditText editTextUsername, editTextPassword;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_login);

       editTextUsername = (EditText) findViewById(R.id.editTextUsername);
       editTextPassword = (EditText) findViewById(R.id.editTextPassword);

       //if user presses on login
       //calling the method userLogin
       findViewById(R.id.buttonLogin).setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               userLogin();
           }
       });

       //if user presses on not registered
       findViewById(R.id.textViewRegister).setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               //open register screen
               finish();
               startActivity(new Intent(getApplicationContext(), SignupActivity.class));
           }
       });

       findViewById(R.id.textViewForgotPassword).setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               finish();
               startActivity(new Intent(getApplicationContext(), ForgotPasswordActivity.class));
           }

       });
   }

   private void userLogin() {
       Log.d("newwwss", "Login Function Called");
       //first getting the values
       final String username = editTextUsername.getText().toString();
       final String password = editTextPassword.getText().toString();

       //validating inputs
       if (TextUtils.isEmpty(username)) {
           editTextUsername.setError("Please enter your username");
           editTextUsername.requestFocus();
           return;
       }

       if (TextUtils.isEmpty(password)) {
           editTextPassword.setError("Please enter your password");
           editTextPassword.requestFocus();
           return;
       }

       //if everything is fine

       class UserLogin extends AsyncTask<Void, Void, String> {

           ProgressBar progressBar;

           @Override
           protected void onPreExecute() {
               Log.d("newwwss", "Login Function Called PreExecute");
               super.onPreExecute();
               progressBar = (ProgressBar) findViewById(R.id.progressBar);
               progressBar.setVisibility(View.VISIBLE);
           }

           @Override
           protected void onPostExecute(String s) {

               super.onPostExecute(s);
               progressBar.setVisibility(View.GONE);


               try {

                   Log.d("newwwss", s);
                   //converting response to json object
                   JSONObject obj = new JSONObject(s);
                   Log.d("JsonObject", String.valueOf(obj));
                   //if no error in response
                   if (!obj.getBoolean("error")) {

                       Log.d("Errror Display","Inside Loop");
                       Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                       //getting the user from the response
                       JSONObject userJson = obj.getJSONObject("user");

                       //creating a new user object
                       User user = new User(
                               userJson.getInt("id"),
                               userJson.getString("username"),
                               userJson.getString("email"),
                               userJson.getString("phone")
                       );

                       //storing the user in shared preferences
                       SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);

                       //starting the profile activity
                       finish();
                       startActivity(new Intent(getApplicationContext(), NavigationDrawerActivity.class));
                   } else {
                       Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
                   }
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }

           @Override
           protected String doInBackground(Void... voids) {
               //creating request handler object
               RequestHandler requestHandler = new RequestHandler();

               //creating request parameters
               HashMap<String, String> params = new HashMap<>();
               params.put("username", username);
               params.put("password", password);

               //returning the Response of user login
               return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);
           }
       }
       UserLogin ul = new UserLogin();
       ul.execute();
   }
}

Leave a Reply