Saturday, 24 October 2015

Android restful webservice call and get and parse json array using java ( assynchttp.jar ), php and mysql

      In this tutorial we are gonna use android-async-http-library to create a restful webservice call, And get and parse the JSON array data. We will cover the Java codes for the android and PHP codes to manage the server-side. Also we will connect PHP with MySql to load data from the database!


Steps involved:
1.Download and add android-async-http-library to your project.
2.Writing java codes.
3.Copy and paste the xml codes.
4.Creating PHP pages to manage the server side.
5. And finally check your console log for the received JSON data. 

Java:

MainActivity.java
 import org.json.JSONArray;   
  import org.json.JSONException;   
  import org.json.JSONObject;   
  import android.app.Activity;   
  import android.os.Bundle;   
  import android.util.Log;   
  import android.widget.Toast;   
  import com.loopj.android.http.AsyncHttpClient;   
  import com.loopj.android.http.AsyncHttpResponseHandler;   
  import com.loopj.android.http.RequestParams;   
  public class MainActivity extends Activity {   
    JSONArray products = null;   
    String PHP_File_Path = "http://google.com/getData.php";   
    @Override   
    protected void onCreate(Bundle savedInstanceState) {   
       super.onCreate(savedInstanceState);   
       setContentView(R.layout.main_activity);   
       doCall("Mycreativecodes", PHP_File_Path);   
    }   
    public void doCall(String username, String path) {   
       AsyncHttpClient client = new AsyncHttpClient();   
       RequestParams params;   
       params = new RequestParams();   
       params.put("username", username);   
       client.post(path, params,   
            new AsyncHttpResponseHandler() {   
              @Override   
              public void onSuccess(String response) {   
                 System.out.println(response);   
                 try {   
                   JSONObject arrg = new JSONObject(response);   
                   System.out.println(arrg.getInt("success"));   
                   if (arrg.getInt("success") == 1) {   
                        for (int i = 0; i < products.length(); i++) {   
                           JSONObject c = products.getJSONObject(i);   
                           String value1 = c.getString("value1");   
                           String value2 = c.getString("value2");   
                           String value3 = c.getString("value3");   
                        Log.d("value1=", value1);   
                        Log.d("value2=", value2);   
                        Log.d("value3=", value3);   
                        }   
                   } else {   
                      Toast.makeText(getApplicationContext(),   
                           "No data found!", Toast.LENGTH_LONG)   
                           .show();   
                      finish();   
                   }   
                 } catch (JSONException e) {   
                   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) {   
                 if (statusCode == 404) {   
                   Toast.makeText(getApplicationContext(),   
                        "Requested page not found",   
                        Toast.LENGTH_LONG).show();   
                 } else if (statusCode == 500) {   
                   Toast.makeText(getApplicationContext(),   
                        "Something went wrong at server side",   
                        Toast.LENGTH_LONG).show();   
                 } else {   
                   Toast.makeText(   
                        getApplicationContext(),   
                        "Unexpected Error occcured! (Most common Error: Device might not be connected to Internet)",   
                        Toast.LENGTH_LONG).show();   
                 }   
              }   
            });   
    }   
  }   
That's all for the android part!

PHP:
getData.php
 <?php  
 /*  
  * Following code will list all the products  
  */  
 // array for JSON response  
 $response = array();  
 $status=0;  
 $isUserPresent=0;  
 // include db connect class  
 require_once __DIR__ . '/db_connect.php';  
 // connecting to db  
 $db = new DB_CONNECT();  
 if (isset($_POST['username'])) {  
   $masterId = $_POST['username'];  
 // get all products from products table  
 $result = mysql_query("SELECT * FROM incoming where tomaster = '$masterId'") or die(mysql_error());  
 // check for empty result  
 if (mysql_num_rows($result) > 0) {  
   // looping through all results  
   // products node  
   $response["products"] = array();  
   while ($row = mysql_fetch_array($result)) {  
     // temp user array  
     $product = array();  
     $product["id"] = $row["id"];  
     $product["frommaster"] = $row["frommaster"];  
     $product["description"] = $row["description"];  
     $product["amount"] = $row["amount"];  
     $product["date"] = $row["DATE1"];  
     // push single product into final response array  
     array_push($response["products"], $product);  
   }  
   // success  
   $response["success"] = 1;  
   // echoing JSON response  
   echo json_encode($response);  
  } else {  
   // no products 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