Saturday, March 29, 2014

Connecting Android with Php web service


In the sample tutorial below a simple login form is presented to user which is used to connect to php web service to validate user via Json.
You can download project, php web service and database. Click here to download

Application Interface

Login Screen (JsonParseExampleActivity)





MainMenuActivity (Success screen)

JsonParseExampleActivity.Class (Login Activity)

 package com.rnd.android;  
 import java.util.ArrayList;  
 import java.util.List;  
 import org.apache.http.NameValuePair;  
 import org.apache.http.message.BasicNameValuePair;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import android.app.Activity;  
 import android.app.ProgressDialog;  
 import android.content.Intent;  
 import android.os.AsyncTask;  
 import android.os.Bundle;  
 import android.util.Log;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.EditText;  
 import android.widget.Toast;  
 import com.rnd.service.JsonParseClass;  
 public class JsonParseExampleActivity extends Activity {  
      private ProgressDialog pDialog;  
      private final String LOG_MSG = "Log tracing";  
      JsonParseClass jsonParse = new JsonParseClass();  
      String successTag = null;  
      private static final String connectingUrl = "http://10.0.2.2/rnd_webservice/webservice.php";  
      private static final String TAG_SUCCESS = "success";  
      EditText edittextUsername, edittextPassword;  
      Button buttonLogin;  
      /** Called when the activity is first created. */  
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.login);  
           edittextUsername = (EditText) findViewById(R.id.editText_username);  
           edittextPassword = (EditText) findViewById(R.id.editText_password);  
           buttonLogin = (Button) findViewById(R.id.Login);  
           buttonLogin.setOnClickListener(new View.OnClickListener() {  
                public void onClick(View v) {  
                     // TODO Auto-generated method stub  
                     ValidateUser validateUser = new ValidateUser();  
                     validateUser.execute();  
                }  
           });  
      }  
      // inner class  
      public class ValidateUser extends AsyncTask<String, String, String> {  
           ProgressDialog progressDialog;  
           JSONObject jObject;  
           @Override  
           protected void onPreExecute() {  
                // TODO Auto-generated method stub  
                super.onPreExecute();  
                progressDialog = new ProgressDialog(JsonParseExampleActivity.this);  
                progressDialog.setMessage("Logining please wait ...");  
                progressDialog.setIndeterminate(false);  
                progressDialog.setCancelable(true);  
                progressDialog.show();  
           }  
           @Override  
           protected String doInBackground(String... params) {  
                // TODO Auto-generated method stub  
                String username = edittextUsername.getText().toString().trim();  
                String password = edittextPassword.getText().toString().trim();  
                Log.d(LOG_MSG, "user name " + username);  
                List<NameValuePair> validateParams = new ArrayList<NameValuePair>();  
                validateParams.add(new BasicNameValuePair("username", username));  
                validateParams.add(new BasicNameValuePair("password", password));  
                System.out.println("before calling json object");  
                jObject = jsonParse.makeHttpRequest(connectingUrl, "POST",  
                          validateParams);  
                try {  
                     successTag = jObject.getString(TAG_SUCCESS);  
                     Log.d("Jeson result ", successTag);  
                } catch (JSONException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                }  
                return successTag;  
           }  
           @Override  
           protected void onPostExecute(String result) {  
                progressDialog.dismiss();  
                // TODO Auto-generated method stub  
                super.onPostExecute(result);  
                Log.d("Checking the result a post execute", result);  
                if (successTag.equalsIgnoreCase("1")) {  
                     Toast.makeText(JsonParseExampleActivity.this, "valid user",  
                               Toast.LENGTH_SHORT).show();  
                     Intent intent = new Intent(JsonParseExampleActivity.this,  
                               MainMenu.class);  
                     startActivity(intent);  
                } else {  
                     Toast.makeText(JsonParseExampleActivity.this, " invalid user",  
                               Toast.LENGTH_LONG).show();  
                }  
           }  
      }  
 }  

JsonParserClass.Class

 package com.rnd.service;  
 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 import java.io.UnsupportedEncodingException;  
 import java.util.List;  
 import org.apache.http.HttpEntity;  
 import org.apache.http.HttpResponse;  
 import org.apache.http.NameValuePair;  
 import org.apache.http.client.ClientProtocolException;  
 import org.apache.http.client.entity.UrlEncodedFormEntity;  
 import org.apache.http.client.methods.HttpPost;  
 import org.apache.http.impl.client.DefaultHttpClient;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import android.util.Log;  
 public class JsonParseClass {  
      DefaultHttpClient httpClient;  
      HttpPost httpPost;  
      HttpResponse httpResponse;  
      HttpEntity httpEntity;  
      static InputStream inputStream = null;  
      static JSONObject jsonObject = null;  
      static String jsonString = "";  
      public JSONObject makeHttpRequest(String url, String method,  
                List<NameValuePair> params)   
      {  
                try   
                {  
                     if(method == "POST")  
                     {  
                          //getting default http client to make request  
                          httpClient = new DefaultHttpClient();  
                          //creating http post request to the given url  
                          httpPost = new HttpPost(url);  
                     //setting inputs of android as html form inputs  
                     httpPost.setEntity(new UrlEncodedFormEntity(params));  
                     //execute http post request throuh response object with httpclient object  
                     httpResponse = httpClient.execute(httpPost);  
                     //getting entity object from response object  
                     httpEntity = httpResponse.getEntity();  
                     //getting contents of httpentity into inputstream  
                     inputStream = httpEntity.getContent();  
                     }  
                }  
                catch (UnsupportedEncodingException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                     System.out.println(e.toString());  
                } catch (ClientProtocolException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                     System.out.println(e.toString());  
                } catch (IOException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                     System.out.println(e.toString());  
                }  
                //GETTING BUFFERREADER TO READ INPUT STREAM       
                try {  
                     BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"),8);  
                     StringBuilder sb = new StringBuilder();  
                     String line = null;  
                     while ((line = bufferReader.readLine()) != null) {  
                          sb.append(line +"\n");  
                     }  
                     inputStream.close();  
                     jsonString = sb.toString();  
                } catch (UnsupportedEncodingException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                     Log.e("Buffer Error", "Error converting result " + e.toString());  
                } catch (IOException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                }       
                //parse the string to json object  
                try {  
                     jsonObject = new JSONObject(jsonString);  
                } catch (JSONException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                      Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+ jsonString);  
                }  
           return jsonObject;  
      }  
 }  

MainMenu.Class

 package com.rnd.android;  
 import android.app.Activity;  
 import android.os.Bundle;  
 public class MainMenu extends Activity {  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           // TODO Auto-generated method stub  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
      }  
 }  

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.rnd.android"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   <uses-sdk android:minSdkVersion="8" />  
   <uses-permission android:name="android.permission.INTERNET"/>  
   <application  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name" >  
     <activity  
       android:name=".JsonParseExampleActivity"  
       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="MainMenu"></activity>  
   </application>  
 </manifest>  

layout/login.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical" >  
   <TextView  
     android:id="@+id/textView1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Username"  
     android:textAppearance="?android:attr/textAppearanceLarge" />  
   <EditText  
     android:id="@+id/editText_username"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:ems="10" >  
     <requestFocus />  
   </EditText>  
   <TextView  
     android:id="@+id/textView2"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Password"  
     android:textAppearance="?android:attr/textAppearanceLarge" />  
   <EditText  
     android:id="@+id/editText_password"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:ems="10"  
     android:inputType="textPassword" />  
   <Button  
     android:id="@+id/Login"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:text="Login" />  
 </LinearLayout>  

layout/main.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="fill_parent"  
   android:orientation="vertical" >  
   <TextView  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="@string/hello" />  
   <ImageView  
     android:id="@+id/imageView2"  
     android:layout_width="220dp"  
     android:layout_height="wrap_content"  
     android:layout_weight="0.19"  
     android:src="@drawable/ic_launcher" />  
   <ImageView  
     android:id="@+id/imageView1"  
     android:layout_width="212dp"  
     android:layout_height="wrap_content"  
     android:layout_weight="0.39"  
     android:src="@drawable/ic_launcher" />  
 </LinearLayout>  

 Php web service file

 <?php  
           // array for JSON response  
           $response = array();  
      if(isset($_POST['username']) And isset($_POST['password']))  
      {  
                $un=$_POST['username'];  
                $pw=$_POST['password'];  
                //connect to the db  
                $host="localhost"; // Host name   
                $user="root"; // Mysql username   
                $pswd=""; // Mysql password   
                $db="rnd_android"; // Database name   
                $tbl_name="user"; // Table name  
                $conn = mysql_connect($host, $user, $pswd);  
                mysql_select_db($db, $conn);  
                //run the query to search for the username and password the match  
                //$query = "SELECT * FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'";  
                $query = "SELECT user_id FROM $tbl_name WHERE user_name = '$un' AND password = '$pw'";  
                $result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());  
                //this is where the actual verification happens  
                if(mysql_num_rows($result) > 0)  
                {  
                     // success  
                     $response["success"] = 1;  
                     // echoing JSON response  
                     echo json_encode($response);  
                     //echo mysql_result($result,0); // for correct login response  
                }                 
                else  
                {  
                     //echo 0; // for incorrect login response  
                     // no products found  
                     $response["success"] = 0;  
                     // echo no users JSON  
                     echo json_encode($response);  
                }  
      }  
      else  
      {  
                echo("no paramter found");  
      }  
 ?>  

No comments:

Post a Comment