Friday, 28 August 2015

How to populate spinner from database using php mysql

This is the video tutorial along with code for fetching data from php Mysql and populate in the spinner in android.

I have used the one demo MyApplication for populating the data in spinner.
Few steps for guidance, still the video will be useful.

  • Create an android application using Android Studio using blank activity
  •  Under layout folder, in activity_main.xml, add a spinner
  • Under Src folder in mainactivity.java, do the desired coding done in video.
  • Create a table in mysql, as shown in video.
  • Code the php script for JSON response.
1. MainActivity.java

package com.spinner.demo.demo_spinner;

import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {



    InputStream is=null;
    String result=null;
    String line=null;

    String[] roll_no,name;

    Spinner spinner1,spinner2;

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

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner2 = (Spinner) findViewById(R.id.spinner2);
        final List<String> list1 = new ArrayList<String>();
        final List<String> list2 = new ArrayList<String>();

        Button b=(Button) findViewById(R.id.button1);

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub

                try
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://192.168.43.94/spinner.php");
                    HttpResponse response = httpclient.execute(httppost);
                    Log.e("Fail 1", "3");

                    HttpEntity entity = response.getEntity();
                    Log.e("Fail 2", "4");

                    is = entity.getContent();
                    Log.e("Pass 1", "connection success");


                }
                catch(Exception e)
                {
                    Log.e("Fail 3", e.toString());
                    Toast.makeText(getApplicationContext(), "Invalid IP Address",Toast.LENGTH_LONG).show();
                    finish();
                }


                try
                {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                }
                catch(Exception e)
                {
                    Log.e("Fail 2", e.toString());
                }


                try
                {
                    JSONArray JA=new JSONArray(result);
                    JSONObject json= null;
                    roll_no = new String[JA.length()];
                    name = new String[JA.length()];

                    for(int i=0;i<JA.length();i++)
                    {
                        json=JA.getJSONObject(i);
                        roll_no[i] = json.getString("roll_no");
                        name[i]=json.getString("name");
                    }
                    Toast.makeText(getApplicationContext(), "Data Loaded", Toast.LENGTH_LONG).show();

                    for(int i=0;i<roll_no.length;i++)
                    {
                        list1.add(roll_no[i]);
                        list2.add(name[i]);
                    }

                    spinner_fn();

                }
                catch(Exception e)
                {

                    Log.e("Fail 3", e.toString());


                }
            }
        });

    }


    private void spinner_fn() {
// TODO Auto-generated method stub

        ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_spinner_item, roll_no);
        dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(dataAdapter1);


        ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_spinner_item, name);
        dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(dataAdapter2);


        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
            {
// TODO Auto-generated method stub

                spinner2.setSelection(position);

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {
// TODO Auto-generated method stub
            }

        });


        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub

                spinner1.setSelection(position);

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
            }
        });

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2. activity_main.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: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">

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="10dp"
        android:layout_marginTop="99dp" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="99dp"
        android:layout_marginLeft="10dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />
</RelativeLayout>

3. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.spinner.demo.demo_spinner" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4. spinner.php

 <?php
$host='127.0.0.1';
$uname='';
$pwd='';
$db='test';
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$r=mysql_query("select * from class",$con);
while($row=mysql_fetch_array($r))
{
$cls[]=$row;
//echo $fin."<br>";
}
print(json_encode($cls));
mysql_close($con);
?>



Watch, Try, Learn.

Don't forget to Share and Subscribe to youtube channel "Srce Cde" for more fun in android.

No comments:

Post a Comment