Display data on android spinner from mysql using php

15/04/2017   03:49:38 PM
Hello in this android article i will explain how to display data on android spinner from mysql data base using PHP and then spinner selected related data display on text view.In this example display employee names in to spinner and when select employee name from that spinner,display details (Ex:-Name, Mail id) of that particular employee on textview of Android.
 
What is Spinner?
Dropdownlist is called as Spinner in Android.It is used to show data like dropdownlist.
 
1. Create a database and table in mysql.Here database name is sampleDB & table name is employeedetails
    In this example I used localhost wamp server
 

mysql database table display data on android spinner

2. Add some data in table employeedetails
 
display data on android spinner mysql database
 
3. Create a php page dbConnect.php for database connectivity
 
dbConnect.php
 
<?php
 $servername = "localhost";
$uname = "root";
$password = "";
$dbname = "sampledb";
$con = mysqli_connect($servername, $uname, $password, $dbname) or die('Unable to Connect'); 
 ?>
 
4. Create a php page getdata.php to get employee name from mysql to android
 
getdata.php
 
<?php 
$sql = "SELECT * FROM employeedetails";
require_once('dbConnect.php');
//$con=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
$r = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($r)){
 array_push($result,array(
'EmpName'=>$row['EmpName']
    ));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);?>

 

5. Create a new project in android àadd a spinner to activity_main.xml

Here we use volley library for fetch data from mysql database to spinner android.
 

What is volley?

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.
Volley is available through the open AOSP repository.
 

6. Add volley library to android project

Add this line to android project app gradle file compile 'com.android.volley:volley:1.0.0'
 
7. synch project it will download volley library to your project
 
8. Add following code on activity_main.xml for Design layout
 
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.xperiaitinnovations.getspinnermysql.PopulateSpinnerMysql"
    android:id="@+id/tvMailId">
    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spnrEmployee"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/tvName"
        android:layout_marginTop="49dp"
        android:layout_below="@+id/spnrEmployee"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/tvmailid"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>
 

 9.Add following code on MainActivity.java

package com.simplylearnprogramming.getspinnermysql;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
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;
import java.util.ArrayList;
public class PopulateSpinnerMysql extends AppCompatActivity {
    public static final String EmployeeNamearray = "EmpName";
    public static final String EmployeeName  = "EmpName";
    public static final String EmployeeMailid = "EmpMailid";
    public static final String JSON_ARRAY = "result";
    private JSONArray result;
    Spinner spinner;
    String  EmpName;
    private ArrayList<String> arrayList;
    TextView employeename,mailid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_populate_spinner_mysql);
        spinner= (Spinner) findViewById(R.id.spnrEmployee);
        employeename= (TextView) findViewById(R.id.tvName);
                mailid= (TextView) findViewById(R.id.tvmailid);
        arrayList = new ArrayList<String>();
        getdata();
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //Setting the values to textviews for a selected item
                employeename.setText(getemployeeName(position));
                mailid.setText(getmailid(position));
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                employeename.setText("");
                mailid.setText("");
            }
        });
    }
    private void getdata() {
        StringRequest stringRequest = new StringRequest("http://localhost IP or Domain name here/Project Folder Name/getdata.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        JSONObject j = null;
                        try {
                            j = new JSONObject(response);
                            result = j.getJSONArray(JSON_ARRAY);
                            empdetails(result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    private void empdetails(JSONArray j) {
        for (int i = 0; i < j.length(); i++) {
            try {
                JSONObject json = j.getJSONObject(i);
                arrayList.add(json.getString(EmployeeNamearray));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
       // arrayList.add(0,"Select Employee");
        spinner.setAdapter(new ArrayAdapter<String>(PopulateSpinnerMysql.this, android.R.layout.simple_spinner_dropdown_item, arrayList));
    }
    //Method to get student name of a particular position
    private String getemployeeName(int position){
        String name="";
        try {
            //Getting object of given index
            JSONObject json = result.getJSONObject(position);
            //Fetching name from that object
            name = json.getString(EmployeeName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Returning the name
        return name;
    }
    //Doing the same with this method as we did with getName()
    private String getmailid(int position){
        String mailid="";
        try {
            JSONObject json = result.getJSONObject(position);
            mailid = json.getString(EmployeeMailid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mailid;
    }
}

 

OUTPUT 

display data on android spinner from mysql using php

 

 

 

 


Output

                   

Support us by Sharing