Sunday, 18 October 2015

Android restful webservice call and get and parse json data : Login example with php mysql

Most of the mobile apps requires user registration and login. In this tutorial I'm gonna guide you to create a login system for android using the android-async-http-library, which will also store the user login information in local sqlite database.


android login tutorial with php mysql




Steps included are:
1.Creating an xml layout file.
2.Download and add android-async-http-library  to your project.
3.Writing java codes for getting and sending the username and         password from user to server.
4.Writing PHP codes to manage server-side.

copy and paste the below xml to your layout xml file.

XML:
 <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"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin" >  
   <Button  
     android:id="@+id/resetbtn"  
     android:layout_width="100dp"  
     android:layout_height="55dp"  
     android:background="@drawable/bluebutton"  
     android:textColor="#fff"  
     android:textStyle="bold"   
     android:layout_below="@+id/password"  
     android:layout_centerHorizontal="true"  
     android:onClick="register"  
     android:text="Signup" />  
   <EditText  
     android:id="@+id/username"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentTop="true"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="78dp"  
     android:ems="10"  
     android:hint="Username" >  
       <EditText  
     android:id="@+id/password"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentTop="true"  
     android:layout_centerHorizontal="true"  
     android:layout_marginTop="78dp"  
       android:inputType="numberPassword"  
     android:ems="10"  
     android:hint="Password" >  
     <requestFocus />  
   </EditText>  
 </RelativeLayout>  


Java:
 package in.creativecodes.loginExample;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import com.loopj.android.http.AsyncHttpClient;  
 import com.loopj.android.http.AsyncHttpResponseHandler;  
 import com.loopj.android.http.RequestParams;  
 import in.wizzo.dataflasher.R;  
 import in.wizzo.dataflasher.R.layout;  
 import in.wizzo.dataflasher.R.menu;  
 import android.os.Bundle;  
 import android.app.Activity;  
 import android.content.Intent;  
 import android.database.sqlite.SQLiteDatabase;  
 import android.view.Menu;  
 import android.view.View;  
 import android.widget.EditText;  
 import android.widget.Toast;  
 public class Login extends Activity {  
      private static String DBNAME = "myCreativeCodes.db";  
      SQLiteDatabase mydb;  
      String username,password;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_login);  
      }  
      public void login(View v) {  
           EditText editText = (EditText) findViewById(R.id.username);  
           username = editText.getText().toString();  
           EditText editText2 = (EditText) findViewById(R.id.password);  
           password = editText2.getText().toString();  
           check();  
      }  
      public void check() {  
           // Create AsycHttpClient object  
           AsyncHttpClient client = new AsyncHttpClient();  
           RequestParams params;  
           // prgDialog.show();  
           params = new RequestParams();  
           params.put("username", username);  
           params.put("password", password);  
           client.post("MYDOMAIN.COM/LOGIN.PHP", params,  
                     new AsyncHttpResponseHandler() {  
                          @Override  
                          public void onSuccess(String response) {  
                               System.out.println(response);  
                               // prgDialog.hide();  
                               try {  
                                    JSONObject arr = new JSONObject(response);  
                                    System.out.println(arr.getInt("success"));  
                                    if (arr.getInt("success") == 1) {  
                                         try {  
                                              mydb = openOrCreateDatabase(DBNAME, 0, null);  
                                              mydb.execSQL("CREATE TABLE IF NOT EXISTS INFO (ID INTEGER PRIMARY KEY, PASSWORD TEXT, USERNAME TEXT);");  
                                              mydb.close();  
                                              mydb = openOrCreateDatabase(DBNAME, 0, null);  
                                              mydb.execSQL("INSERT INTO INFO(USERNAME, PASSWORD) VALUES('"  
                                                        + username + "' , '"+password+"')");  
                                              mydb.close();  
                                              Toast.makeText(getApplicationContext(),  
                                                        "You Had Successfully Registered!",  
                                                        1).show();  
                                              finish();  
                                         } catch (Exception var10_10) {  
                                              Toast.makeText(getApplicationContext(),  
                                                        var10_10.toString(), 1).show();  
                                              return;  
                                         }  
                                    } else {  
                                         Toast.makeText(getApplicationContext(),  
                                                   "Invalid UserName Or Password!", 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();  
                               }  
                          }  
                          @Override  
                          public void onFailure(int statusCode, Throwable error,  
                                    String content) {  
                               // TODO Auto-generated method stub  
                               // prgDialog.hide();  
                               if (statusCode == 404) {  
                                    Toast.makeText(getApplicationContext(),  
                                              "Requested resource not found",  
                                              Toast.LENGTH_LONG).show();  
                               } else if (statusCode == 500) {  
                                    Toast.makeText(getApplicationContext(),  
                                              "Something went wrong at server end",  
                                              Toast.LENGTH_LONG).show();  
                               } else {  
                                    Toast.makeText(  
                                              getApplicationContext(),  
                                              "Please connect to Internet and try again!",  
                                              Toast.LENGTH_LONG).show();  
                               }  
                          }  
                     });  
      }  
 }  

PHP:

login.php

 <?php  
 // array for JSON response  
 $response = array();  
 // include db connect class  
 require_once __DIR__ . '/db_connect.php';  
 // connecting to db  
 $db = new DB_CONNECT();  
 // check for post data  
 if (isset($_POST['username']) && isset($_POST['password'])) {  
   $username = $_POST['username'];  
   $password = $_POST['password'];  
   // get a product from products table  
   $result = mysql_query("SELECT * FROM users WHERE USERNAME = '$username' AND PASSWORD = '$password'");  
   if (!empty($result)) {  
     // check for empty result  
     if (mysql_num_rows($result) > 0) {  
       $response["success"] = 1;  
       // echoing JSON response  
       echo json_encode($response);  
     } else {  
       // no product found  
       $response["success"] = 0;  
       $response["message"] = "No user found";  
       // echo no users JSON  
       echo json_encode($response);  
     }  
   } else {  
     // no product found  
     $response["success"] = 0;  
     $response["message"] = "No user found";  
     // echo no users JSON  
     echo json_encode($response);  
   }  
 } else {  
   // required field is missing  
   $response["success"] = 0;  
   $response["message"] = "Required field(s) is missing";  
   // echoing JSON response  
   echo json_encode($response);  
 }  
 ?>  

db_connect.php
 <?php  
 /*  
 we are connecting to the database using the information in db_config.php file  
 */  
 class DB_CONNECT {  
   function __construct() {  
     $this->connect();  
   }  
   function __destruct() {  
     $this->close();  
   }  
   function connect() {  
     require_once __DIR__ . '/db_config.php';  
     $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());  
     $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());  
     return $con;  
   }  
   function close() {  
     mysql_close();  
   }  
 }  
 ?>  

db_config.php
 <?php  
 /*  
  * All database connection details  
  */  
 define('DB_USER', "root"); // your database username  
 define('DB_PASSWORD', "root"); // your database password  
 define('DB_DATABASE', "mydb"); // your database name  
 define('DB_SERVER', "localhost"); // your database server  
 ?>  

That's all, the login system is completed. Your questions maybe dropped as comments. Thankyou!




No comments:

Post a Comment