Monday, July 25, 2016

Retrieve Data From MySQL Database in Android

<?php

if($_SERVER['REQUEST_METHOD']=='GET'){

$id  = $_GET['id'];

require_once('dbConnect.php');

$sql = "SELECT * FROM colleges WHERE id='".$id."'";

$r = mysqli_query($con,$sql);

$res = mysqli_fetch_array($r);

$result = array();

array_push($result,array(
"name"=>$res['name'],
"address"=>$res['address'],
"vc"=>$res['vicechancellor']
)
);

echo json_encode(array("result"=>$result));

mysqli_close($con);

}

dbConnect.php page code

<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','androiddb');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');



    Creating a new Android Project

     Add  app 
    1
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    • Now create a new Java class in your package. I created Config.java. Here we will declare some important constants.
    package net.simplifiedcoding.gettingspecificdata;

    public class Config {
        public static final String DATA_URL = "http://192.168.94.1/Android/College/getData.php?id=";
        public static final String KEY_NAME = "name";
        public static final String KEY_ADDRESS = "address";
        public static final String KEY_VC = "vc";
        public static final String JSON_ARRAY = "result";
    }


    • For creating the above layout you can use the following xml 

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/editTextId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
            <Button
                android:id="@+id/buttonGet"
                android:text="Get"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>
        <TextView
            android:id="@+id/textViewResult"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

    </LinearLayout>
    MAINACtivite.java
    package net.simplifiedcoding.gettingspecificdata;

    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {

        private EditText editTextId;
        private Button buttonGet;
        private TextView textViewResult;

        private ProgressDialog loading;

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

            editTextId = (EditText) findViewById(R.id.editTextId);
            buttonGet = (Button) findViewById(R.id.buttonGet);
            textViewResult = (TextView) findViewById(R.id.textViewResult);

            buttonGet.setOnClickListener(this);
        }

        private void getData() {
            String id = editTextId.getText().toString().trim();
            if (id.equals("")) {
                Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
                return;
            }
            loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

            String url = Config.DATA_URL+editTextId.getText().toString().trim();

            StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    loading.dismiss();
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                }
            });

            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.add(stringRequest);
        }

        private void showJSON(String response){
            String name="";
            String address="";
            String vc = "";
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
                JSONObject collegeData = result.getJSONObject(0);
                name = collegeData.getString(Config.KEY_NAME);
                address = collegeData.getString(Config.KEY_ADDRESS);
                vc = collegeData.getString(Config.KEY_VC);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
        }

        @Override
        public void onClick(View v) {
            getData();
        }
    }


    3 comments: