My previous tutorial Android Populating Spinner data from SQLite Database explained how to pupulate spinner data from SQLite database. In this tutorial we are going to learn how to do the same, except the spinner data is being loaded from MySQL database. I choose PHP as server side technology which acts as a connecting layer between android app and mysql database.

If you haven’t tried connecting android with PHP and MySQL, How to connect Android with PHP, MySQL will give you complete overview of communicating android app with MySQL.

android populating spinner mysql database

Installing WAMP Server

WAMP lets you install Apache, PHP and MySQL with a single installer which reduces burden of installing & configuring them separately. Alternatively you can use XAMP, LAMP (on Linux) and MAMP (on MAC). WAMP also provides you phpmyadmin to easily interact with MySQL database.

Download & install WAMP from http://www.wampserver.com/en/. Choose the correct version which suits your operating system (32bit or 64bit). Once you have installed it, open the program from Start -> All Programs -> Wamp Server -> Start WampServer.

Open http://localhost/ and http://localhost/phpmyadmin/ to verify WAMP is installed successfully or not.

Creating MySQL Database

To demonstrate this tutorial I have taken an example of Food Categories API where we do two operations. Once is getting list of food categories and other is creating new food category. So let’s start creating a database for this.

Open phpmyadmin from http://localhost/phpmyadmin/ and create a database and tables using following SQL queries. Also you can use phpmyadmin GUI to create database and tables.

Creating database

CREATE DATABASE food;

Creating categories table & inserting some data.

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `categories` (`name`) VALUES
('Beverages'),
('Bread'),
('Cereals'),
('Cheese'),
('Citrus Fruits');

Creating PHP Project

On windows PC default location of the WAMP installation is C:\wamp. Go to this directory and open www directory. All the PHP projects will go into this directory.

The PHP project we are going to create will have following list of files.

Config.php – All the configuration variables like database name, username, password and other things goes here.
DbConnect.php – A class to open and close the database connection.
get_categories.php – To fetch list of food categories
new_category – To create a new food category in database.

I have used Netbeans IDE to develop my php project. This is optional, you can use your favorite IDE.

1. Create a new folder named food_api under C:\wamp\www directory for our project.

2. Create a new file named Config.php and write following code. Here we mentioned database name, username, password and host name. If your mysql database is having a password, don’t forget to define it here.

<?php
/**
 * Database configuration
 */
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'food');
?>

3. The first API call is listing all food categories. So create a file named get_categories.php with following content. Here we simply open the database connection, run a select query and build a response array and echo the json.

<?php
include_once './DbConnect.php';

function getCategories(){
    $db = new DbConnect();
    // array for json response
    $response = array();
    $response["categories"] = array();
    
    // Mysql select query
    $result = mysql_query("SELECT * FROM categories");
    
    while($row = mysql_fetch_array($result)){
        // temporary array to create single category
        $tmp = array();
        $tmp["id"] = $row["id"];
        $tmp["name"] = $row["name"];
        
        // push category to final json array
        array_push($response["categories"], $tmp);
    }
    
    // keeping response header to json
    header('Content-Type: application/json');
    
    // echoing json result
    echo json_encode($response);
}

getCategories();
?>

You can see the output of this file by opening http://localhost/food_api/get_categories.php

4. The second API call is creating a new food category. So create a file named new_category with following content. This api call accepts POST method and check for parameter name which is name of the new category to be created in database.

<?php

include_once './DbConnect.php';

function createNewCategory() {
    if (isset($_POST["name"]) && $_POST["name"] != "") {
        // response array for json
        $response = array();
        $category = $_POST["name"];
        
        $db = new DbConnect();

        // mysql query
        $query = "INSERT INTO categories(name) VALUES('$category')";
        $result = mysql_query($query) or die(mysql_error());
        if ($result) {
            $response["error"] = false;
            $response["message"] = "Category created successfully!";
        } else {
            $response["error"] = true;
            $response["message"] = "Failed to create category!";
        }
    } else {
        $response["error"] = true;
        $response["message"] = "Category name is missing!";
    }
    
    // echo json response
    echo json_encode($response);
}

createNewCategory();
?>

The url for this api call is http://localhost/food_api/new_category.php.

Until now we are done with server side part. It’s time to move on to android part.

Creating Android Project

1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project. I had left my main activity name as MainActivity.java and gave the package name as info.androidhive.spinnermysql

2. As this application is going to use internet, we need to add INTERNET permission in AndroidManifest.xml file. Open your AndroidManifest.xml file and add following permission.

<uses-permission android:name=”android.permission.INTERNET”/>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.spinnermysql"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    
    <!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="info.androidhive.spinnermysql.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>

3. Create a class file named Category.php. This model class will be useful to convert json data into objects.

package info.androidhive.spinnermysql;

public class Category {
	
	private int id;
	private String name;
	
	public Category(){}
	
	public Category(int id, String name){
		this.id = id;
		this.name = name;
	}
	
	public void setId(int id){
		this.id = id;
	}
	
	public void setName(String name){
		this.name = name;
	}
	
	public int getId(){
		return this.id;
	}
	
	public String getName(){
		return this.name;
	}

}

4. I am creating another class to take care of making API calls and handling the response. Create a class named ServiceHandler.java and write the following code. makeServiceCall() method should be called to make http calls.

package info.androidhive.spinnermysql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class ServiceHandler {

	static InputStream is = null;
	static String response = null;
	public final static int GET = 1;
	public final static int POST = 2;

	public ServiceHandler() {

	}

	/**
	 * Making service call
	 * @url - url to make request
	 * @method - http request method
	 * */
	public String makeServiceCall(String url, int method) {
		return this.makeServiceCall(url, method, null);
	}

	/**
	 * Making service call
	 * @url - url to make request
	 * @method - http request method
	 * @params - http request params
	 * */
	public String makeServiceCall(String url, int method,
			List<NameValuePair> params) {
		try {
			// http client
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpEntity httpEntity = null;
			HttpResponse httpResponse = null;
			
			// Checking http request method type
			if (method == POST) {
				HttpPost httpPost = new HttpPost(url);
				// adding post params
				if (params != null) {
					httpPost.setEntity(new UrlEncodedFormEntity(params));
				}

				httpResponse = httpClient.execute(httpPost);

			} else if (method == GET) {
				// appending params to url
				if (params != null) {
					String paramString = URLEncodedUtils
							.format(params, "utf-8");
					url += "?" + paramString;
				}
				HttpGet httpGet = new HttpGet(url);

				httpResponse = httpClient.execute(httpGet);

			}
			httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			response = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error: " + e.toString());
		}

		return response;

	}
}

5. Now design the interface for your main activity. I have created simple layout to insert new category and a spinner to show the categories fetched from MySQL database. Open activity_main.xml file and insert the following code.

<LinearLayout 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:orientation="vertical"
    android:padding="10dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New food category" />
    
    <EditText android:id="@+id/txtCategory"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
    <Button android:id="@+id/btnAddNewCategory"
        android:text="Create"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"/>
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select food category"/>
    
    <Spinner android:id="@+id/spinFood"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

The above xml produces following UI

android spinner inserting into mysql

6. Open your MainActivity.java file add the basic code like declaring required variables, button click event, spinner listener etc.,

URL_NEW_CATEGORY – Url to create new category
URL_CATEGORIES – Url to get list of categories

public class MainActivity extends Activity implements OnItemSelectedListener {

	private Button btnAddNewCategory;
	private TextView txtCategory;
	private Spinner spinnerFood;
	// array list for spinner adapter
	private ArrayList<Category> categoriesList;
	ProgressDialog pDialog;

	// API urls
	// Url to create new category
	private String URL_NEW_CATEGORY = "http://10.0.2.2/food_api/new_category.php";
	// Url to get all categories
	private String URL_CATEGORIES = "http://10.0.2.2/food_api/get_categories.php";

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

		btnAddNewCategory = (Button) findViewById(R.id.btnAddNewCategory);
		spinnerFood = (Spinner) findViewById(R.id.spinFood);
		txtCategory = (TextView) findViewById(R.id.txtCategory);
		
		categoriesList = new ArrayList<Category>();

		// spinner item select listener
		spinnerFood.setOnItemSelectedListener(this);

		// Add new category click event
		btnAddNewCategory.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (txtCategory.getText().toString().trim().length() > 0) {
					
					// new category name
					String newCategory = txtCategory.getText().toString();

					// Call Async task to create new category
					new AddNewCategory().execute(newCategory);
				} else {
					Toast.makeText(getApplicationContext(),
							"Please enter category name", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

		new GetCategories().execute();		
	}
}

Getting list of categories and showing them in Spinner

7. I defined an Async method to fetch list of categories from MySQL and showing them in spinner. Add the following code after onCreate block in MainActivity.java. I also added another method populateSpinner() to takes care of loading the data into spinner. This async method should be called in onCreate method like new GetCategories().execute()

	/**
	 * Async task to get all food categories
	 * */
	private class GetCategories extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Fetching food categories..");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			ServiceHandler jsonParser = new ServiceHandler();
			String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);

			Log.e("Response: ", "> " + json);

			if (json != null) {
				try {
					JSONObject jsonObj = new JSONObject(json);
					if (jsonObj != null) {
						JSONArray categories = jsonObj
								.getJSONArray("categories");						

						for (int i = 0; i < categories.length(); i++) {
							JSONObject catObj = (JSONObject) categories.get(i);
							Category cat = new Category(catObj.getInt("id"),
									catObj.getString("name"));
							categoriesList.add(cat);
						}
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else {
				Log.e("JSON Data", "Didn't receive any data from server!");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (pDialog.isShowing())
				pDialog.dismiss();
			//populateSpinner();
		}

	}

	/**
	 * Adding spinner data
	 * */
	private void populateSpinner() {
		List<String> lables = new ArrayList<String>();
		
		txtCategory.setText("");

		for (int i = 0; i < categoriesList.size(); i++) {
			lables.add(categoriesList.get(i).getName());
		}

		// Creating adapter for spinner
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, lables);

		// Drop down layout style - list view with radio button
		spinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// attaching data adapter to spinner
		spinnerFood.setAdapter(spinnerAdapter);
	}

If you run the project now, you should see the mysql data loaded into spinner. Use LogCat to debug the errors.

android populating spinner data from mysql database

Inserting a new food category into MySQL

8. I added another async method to insert a new food category into MySQL database. This method is called in create new button click event using new AddNewCategory().execute(newCategory)

/**
	 * Async task to create a new food category
	 * */
	private class AddNewCategory extends AsyncTask<String, Void, Void> {

		boolean isNewCategoryCreated = false;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Creating new category..");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(String... arg) {

			String newCategory = arg[0];

			// Preparing post params
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("name", newCategory));

			ServiceHandler serviceClient = new ServiceHandler();

			String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
					ServiceHandler.POST, params);

			Log.d("Create Response: ", "> " + json);

			if (json != null) {
				try {
					JSONObject jsonObj = new JSONObject(json);
					boolean error = jsonObj.getBoolean("error");
					// checking for error node in json
					if (!error) {	
						// new category created successfully
						isNewCategoryCreated = true;
					} else {
						Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else {
				Log.e("JSON Data", "Didn't receive any data from server!");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (pDialog.isShowing())
				pDialog.dismiss();
			if (isNewCategoryCreated) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// fetching all categories
						new GetCategories().execute();
					}
				});
			}
		}

	}

Run and the test the app again to check insertion.

Complete Code

Following is the complete code of MainActivity.java

package info.androidhive.spinnermysql;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemSelectedListener {

	private Button btnAddNewCategory;
	private TextView txtCategory;
	private Spinner spinnerFood;
	// array list for spinner adapter
	private ArrayList<Category> categoriesList;
	ProgressDialog pDialog;

	// API urls
	// Url to create new category
	private String URL_NEW_CATEGORY = "http://10.0.2.2/food_api/new_category.php";
	// Url to get all categories
	private String URL_CATEGORIES = "http://10.0.2.2/food_api/get_categories.php";

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

		btnAddNewCategory = (Button) findViewById(R.id.btnAddNewCategory);
		spinnerFood = (Spinner) findViewById(R.id.spinFood);
		txtCategory = (TextView) findViewById(R.id.txtCategory);
		
		categoriesList = new ArrayList<Category>();

		// spinner item select listener
		spinnerFood.setOnItemSelectedListener(this);

		// Add new category click event
		btnAddNewCategory.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (txtCategory.getText().toString().trim().length() > 0) {
					
					// new category name
					String newCategory = txtCategory.getText().toString();

					// Call Async task to create new category
					new AddNewCategory().execute(newCategory);
				} else {
					Toast.makeText(getApplicationContext(),
							"Please enter category name", Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

		new GetCategories().execute();

	}

	/**
	 * Adding spinner data
	 * */
	private void populateSpinner() {
		List<String> lables = new ArrayList<String>();
		
		txtCategory.setText("");

		for (int i = 0; i < categoriesList.size(); i++) {
			lables.add(categoriesList.get(i).getName());
		}

		// Creating adapter for spinner
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, lables);

		// Drop down layout style - list view with radio button
		spinnerAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// attaching data adapter to spinner
		spinnerFood.setAdapter(spinnerAdapter);
	}

	/**
	 * Async task to get all food categories
	 * */
	private class GetCategories extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Fetching food categories..");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			ServiceHandler jsonParser = new ServiceHandler();
			String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);

			Log.e("Response: ", "> " + json);

			if (json != null) {
				try {
					JSONObject jsonObj = new JSONObject(json);
					if (jsonObj != null) {
						JSONArray categories = jsonObj
								.getJSONArray("categories");						

						for (int i = 0; i < categories.length(); i++) {
							JSONObject catObj = (JSONObject) categories.get(i);
							Category cat = new Category(catObj.getInt("id"),
									catObj.getString("name"));
							categoriesList.add(cat);
						}
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else {
				Log.e("JSON Data", "Didn't receive any data from server!");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (pDialog.isShowing())
				pDialog.dismiss();
			//populateSpinner();
		}

	}

	/**
	 * Async task to create a new food category
	 * */
	private class AddNewCategory extends AsyncTask<String, Void, Void> {

		boolean isNewCategoryCreated = false;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Creating new category..");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(String... arg) {

			String newCategory = arg[0];

			// Preparing post params
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("name", newCategory));

			ServiceHandler serviceClient = new ServiceHandler();

			String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
					ServiceHandler.POST, params);

			Log.d("Create Response: ", "> " + json);

			if (json != null) {
				try {
					JSONObject jsonObj = new JSONObject(json);
					boolean error = jsonObj.getBoolean("error");
					// checking for error node in json
					if (!error) {	
						// new category created successfully
						isNewCategoryCreated = true;
					} else {
						Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else {
				Log.e("JSON Data", "Didn't receive any data from server!");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (pDialog.isShowing())
				pDialog.dismiss();
			if (isNewCategoryCreated) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// fetching all categories
						new GetCategories().execute();
					}
				});
			}
		}

	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		Toast.makeText(
				getApplicationContext(),
						parent.getItemAtPosition(position).toString() + " Selected" ,
				Toast.LENGTH_LONG).show();

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {		
	}
}
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
  • Raja

    nice tutorial

  • Max

    Thanks Ravi !

    This is great tutorial.

    I’m a newbie with json. And know I should not post question outside of it. But I really need some help from expert like you.
    I did some search, and studied this is kind of JSON object nested object
    The problem is I cannot parse it. Please help!

    This is my JSON data look like:
    {
    count: 2,
    user: {
    1: {
    id: 1,
    username: “usernameA”

    },
    2: {
    id: 2,
    username: “usernameB”
    }
    }
    }

    • Hi Max,

      First of all this is not valid JSON. The correct format should be

      {
      “count”: 2,
      “user”: [
      {
      “id”: 1,
      “username”: “usernameA”
      },
      {
      “id”: 2,
      “username”: “usernameB”
      }
      ]
      }

      1. You user node should be an array. It should have [ not {
      2. Inside user array all the child elements should be objects, which means they should be kept in { }. Here you don’t have to keep numbers like 1, 2…
      3. All the node names should be inside double quotes like “count” : 2, not count:2

      • Max

        Thank you! I really appreciate your reply.
        By the way, I found out a solution for this stupid json response 😀

  • Nice Tutorial..

  • Nice Tutorial

  • Thomas Kioko

    Hi Ravi,
    Thanks for the tutorials you have been posting. I need some help. Could you create a tutorial that Loads a list of data from a MySQL Database then stores it in SQLite DB. Kind of what Twitter does. So that you can view the Data “Tweets” as you fetch new Data from the MySQL DB or could you give me pointers.

  • rajeshvari

    Hi Ravi,
    Thanks for the tutorials you have been posting. I need some help.

    i am creating an application for GPS tracking and I want to continuously run that application in background for delay of some specific time.

    Can you please help me with this.

  • Amit Asthana

    The download buutton says

    Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (111)

    • Server seems crashed. I can fix it by tonight only, once I go home 🙁

  • funnyanddev

    nIce Tut but source code not working
    http://androidgreeve.blogspot.in/

  • Back Packer

    Thank you !

  • sodd

    thnks for tutorial, btw do you have tutorial for sync data sqlite & mysql???

  • nouman

    i am getting this error

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:wampwwwNewindex.php on line 13

    • nouman

      here is my php code

      function getinfo(){

      $db = new DB_Connect();

      // array for json response

      $response = array();

      $response[“user”] = array();

      // Mysql select query

      $result = mysql_query(“SELECT * FROM user”);

      while($row = mysql_fetch_array($result)){

      // temporary array to create single category

      $tmp = array();

      $tmp[“user”] = $row[“username”];

      $tmp[“pass”] = $row[“password”];

      // push category to final json array

      array_push($response[“user”], $tmp);

      }

      // keeping response header to json

      header(‘Content-Type: application/json’);

      // echoing json result

      echo ($response);

      echo json_encode($response);

      }

      getinfo();

      • i think so ur query doesnt works or it’s wrong ! chechk ur query twice !

      • Use this line mysql_query(“SELECT * FROM user”) or die(mysql_error());
        to verify whether your query is executing correctly or not.

  • Tonyoh87

    Hi, very nice tutorial but no DB Connect php file explained so I struggle to have the application working properly. Would you be nice enough to provide a download link of the android project ? So far I wasted 5h for this tutorial while it should have taken 1/2h. 🙁

    Thank you and best regards ^^

    • helldawg13

      hey man could you provide what is the code inside DBConnect.php????

    • Ravi Tamada

      Hey Tony, download code button already there at the beginning of the article.

      • Tonyoh87

        Ha alright thank you very much!
        By the way would you have a clue on how to combine a public class extending listactivity with this homefragment extends fragment ?

  • Jeeten Parmar

    Hello,
    Can you tell me how to populate Spinner Data from SQL Database and using Asp.NET webservice. I am using SOAP method to connect android with SQL DB.

  • andrea

    Hi, i tried to run the app on AVD and it worked well but when i try to run the app on my Nexus 4 it doesn’t work….it seems like a port problem…i tried 80, 8080, 3306 but nothing happened. Please help me

    • weethomas

      You probably ran AVD on the same machine as the WAMP server. Open the port to the server in windows firewall and ensure your phone and server are on the same network.

    • Shubham Singh

      did you changed the ip correctly

  • prithiviraj

    can I run this code on any other local server (PPRSERVER-PC)?

  • bakke2ooo

    ravi, my man, you did it again. many thanks.

  • chandru

    02-11 09:20:28.219: E/Buffer Error(1120): Error: java.lang.NullPointerException: lock == null

    02-11 09:20:28.219: D/Create Response:(1120): > null

    02-11 09:20:28.229: E/JSON Data(1120): Didn’t receive any data from server!

    how to solve this problem.

    • Muhammad Usman Ghani

      Hi chandru! i got the same problem as you got how to solve this problem did you get the answer for this problem?

    • carissa

      i got this same error :/

  • Unknownimous

    can you include filtering using where clause? how should we do it?

  • M.J

    Thanks really for your great explanation! But please I wanna to inquire about the validity of access wamp server file by given PC-name rather that IP address? If you have any idea please about that? Thank In advance!

  • This is a great tutorial and a great addition to your previous one which uses sqlite.

    When the server is unavailable say because of no network connectivity and then you can’t update the mysql database. How would you sync locally (using sqlite) then when the network is available again then attempt to sync the server?

  • Ahmad Al-karaki

    thank’s
    if i want print in the Toast the id of the name selected , how can make that?

    • pragadees

      use These code:-
      public void onItemSelected(AdapterView parent, View view, int position,
      long id) {
      Toast.makeText(
      getApplicationContext(),
      parent.getItemAtPosition(position).toString() + ” Selected” ,
      Toast.LENGTH_LONG).show();
      int b=categoriesList.get(position).getId();
      String d=String.valueOf(b);
      Toast.makeText(getApplicationContext(), d,Toast.LENGTH_LONG).show();

      }

  • pop

    great tutoria but iwant to know how can item from spinner excute order or change value

  • ideasgate

    when am test this app i can add food type in table in food database but nothing appear in spinner drop down list android app cannot fetch food categories from database table ,, why that?!

  • Nguyen Quang Minh

    I have same proplem,in spinner drop down nothing show up .

  • Uğur Öztürk

    WTF is the DbConnect php ? what is the code in there -.-

  • Virendra

    Hi Ravi….

    I am not getting any data in sppiner but when I am adding then it will properly,
    So can u send me the code for this tutorial…
    My Email ID viru.singh440@gmail.com

    • youming2007

      Have you notified this line of code: //populateSpinner(); in the GetCategories class 🙂

  • Ngọc Anh Lê

    i dont find DbConnect.php

    • Jr

      create your own connection to the database instead.

      here is mine

      CONNECTION TO DATABASE

      connect();

      }

      function __destruct(){

      $this->close();

      }

      function connect(){
      $hostname_localhost =”127.0.0.1″;
      $database_localhost =”db_mine”;
      $username_localhost =”root”;
      $password_localhost =”pass”;
      $con = mysql_connect($hostname_localhost,$username_localhost,$password_localhost) or die (mysql_error());
      $db = mysql_select_db($database_localhost) or die(mysql_error()) or die (mysql_error());
      return $con;

      }

      function close(){

      mysql_close();

      }

      }

      ?>

      THE get_CATEGORIES.PHP

      • Ngọc Anh Lê

        tks you very much

  • JohnGar

    I downloaded the project and I can create a new category perfectly, but I can’t see anything inside Spinner.

    LogCat:

    07-31 16:02:23.966: W/System.err(334): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
    07-31 16:02:23.976: W/System.err(334): at org.json.JSON.typeMismatch(JSON.java:107)
    07-31 16:02:23.976: W/System.err(334): at org.json.JSONObject.(JSONObject.java:158)
    07-31 16:02:23.976: W/System.err(334): at org.json.JSONObject.(JSONObject.java:171)
    07-31 16:02:23.976: W/System.err(334): at info.androidhive.spinnermysql.MainActivity$AddNewCategory.doInBackground(MainActivity.java:196)
    07-31 16:02:23.976: W/System.err(334): at info.androidhive.spinnermysql.MainActivity$AddNewCategory.doInBackground(MainActivity.java:1)
    07-31 16:02:23.976: W/System.err(334): at android.os.AsyncTask$2.call(AsyncTask.java:185)
    07-31 16:02:23.976: W/System.err(334): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
    07-31 16:02:23.976: W/System.err(334): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    07-31 16:02:23.996: W/System.err(334): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
    07-31 16:02:23.996: W/System.err(334): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
    07-31 16:02:23.996: W/System.err(334): at java.lang.Thread.run(Thread.java:1019)
    07-31 16:02:31.080: W/KeyCharacterMap(334): No keyboard for id 0
    07-31 16:02:31.080: W/KeyCharacterMap(334): Using default keymap: /system/usr/keychars/qwerty.kcm.bin

    • JohnGar

      I forget the first two lines of the error:

      07-31 16:02:23.966: W/System.err(334): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
      07-31 16:02:23.976: W/System.err(334): at org.json.JSON.typeMismatch(JSON.java:107)

    • Jr

      inside the GetCategories class uncomment the populateSpinner() method

      protected void onPostExecute(Void result) {

      super.onPostExecute(result);

      if (pDialog.isShowing())

      pDialog.dismiss();

      populateSpinner();

      }

  • Pragadees

    ok nice tutorial but how we get Id when On Item Selected

  • pragadees

    how to set a default name in spinner

  • archish thakkar

    please help me out!!!!!

    i am not able to fetch the categories!!

    i want to run this sample code plzz plzz

    08-15
    07:28:50.400: W/IInputConnectionWrapper(1429): showStatusIcon on inactive
    InputConnection

    08-15
    07:29:02.680: W/ActivityThread(1496): Application info.androidhive.spinnermysql
    is waiting for the debugger on port 8100…

    08-15
    07:29:02.760: I/System.out(1496): Sending WAIT chunk

    08-15
    07:29:02.770: I/dalvikvm(1496): Debugger is active

    08-15
    07:29:02.790: I/System.out(1496): Debugger has connected

    08-15
    07:29:02.790: I/System.out(1496): waiting for debugger to settle…

    08-15
    07:29:02.990: I/System.out(1496): waiting for debugger to settle…

    08-15
    07:29:03.190: I/System.out(1496): waiting for debugger to settle…

    08-15
    07:29:03.440: I/System.out(1496): waiting for debugger to settle…

    08-15
    07:29:03.640: I/System.out(1496): waiting for debugger to settle…

    08-15
    07:29:03.850: I/System.out(1496): waiting for debugger to settle…

    08-15
    07:29:04.050: I/System.out(1496): waiting for debugger to settle…

    08-15
    07:29:04.250: I/System.out(1496): waiting for debugger to settle…

    08-15 07:29:04.460:
    I/System.out(1496): waiting for debugger to settle…

    08-15
    07:29:04.650: I/System.out(1496): debugger has settled (1359)

    08-15
    07:29:08.020: D/dalvikvm(1496): GC_FOR_ALLOC freed 107K, 6% free 2943K/3128K,
    paused 73ms, total 91ms

    08-15 07:29:08.980:
    D/(1496): HostConnection::get() New Host Connection established 0xb8c6c4f0, tid
    1496

    08-15
    07:29:09.080: W/EGL_emulation(1496): eglSurfaceAttrib not implemented

    08-15
    07:29:09.090: D/OpenGLRenderer(1496): Enabling debug mode 0

    08-15
    07:29:09.490: W/EGL_emulation(1496): eglSurfaceAttrib not implemented

    08-15
    07:29:09.570: I/Choreographer(1496): Skipped 48 frames! The application may be doing too much work on
    its main thread.

    08-15
    07:29:10.170: I/Choreographer(1496): Skipped 33 frames! The application may be doing too much work on
    its main thread.

    08-15
    07:29:48.360: D/dalvikvm(1496): GC_FOR_ALLOC freed 92K, 5% free 3363K/3528K,
    paused 42ms, total 43ms

    08-15
    07:30:14.370: E/Response:(1496): >

    08-15
    07:30:14.370: E/Response:(1496):

    08-15
    07:30:14.370: E/Response:(1496): ( ! ) Deprecated:
    mysql_connect(): The mysql extension is deprecated and will be removed in the
    future: use mysqli or PDO instead in C:wampwwwfood_apiDbConnect.php on line
    35

    08-15
    07:30:14.370: E/Response:(1496): Call Stack

    08-15
    07:30:14.370: E/Response:(1496): #TimeMemoryFunctionLocation

    08-15
    07:30:14.370: E/Response:(1496): 10.0005133448{main}(
    )..get_categories.php:0

    08-15
    07:30:14.370: E/Response:(1496): 20.0008139320getCategories(
    )..get_categories.php:30

    08-15
    07:30:14.370: E/Response:(1496): 30.0008139440DbConnect->__construct( )..get_categories.php:5

    08-15
    07:30:14.370: E/Response:(1496): 40.0008139504DbConnect->connect(
    )..DbConnect.php:18

    08-15
    07:30:14.370: E/Response:(1496): 50.0010140016mysql_connect

    08-15
    07:30:14.370: E/Response:(1496): (
    )..DbConnect.php:35

    08-15
    07:30:14.370: E/Response:(1496):

    08-15
    07:30:14.370: E/Response:(1496):
    {“categories”:[{“id”:”1″,”name”:”Beverages”},{“id”:”2″,”name”:”Bread”},{“id”:”3″,”name”:”Cereals”},{“id”:”4″,”name”:”Cheese”},{“id”:”5″,”name”:”Citrus
    Fruits”},{“id”:”11″,”name”:”duid”}]}

    08-15
    07:30:14.770: W/System.err(1496): org.json.JSONException: Value <br of type
    java.lang.String cannot be converted to JSONObject

    08-15
    07:30:14.770: W/System.err(1496): at
    org.json.JSON.typeMismatch(JSON.java:111)

    08-15
    07:30:14.780: W/System.err(1496): at
    org.json.JSONObject.(JSONObject.java:159)

    08-15
    07:30:14.800: W/System.err(1496): at
    org.json.JSONObject.(JSONObject.java:172)

    08-15
    07:30:14.800: W/System.err(1496): at
    info.androidhive.spinnermysql.MainActivity$GetCategories.doInBackground(MainActivity.java:127)

    08-15
    07:30:15.150: W/System.err(1496): at
    info.androidhive.spinnermysql.MainActivity$GetCategories.doInBackground(MainActivity.java:1)

    08-15
    07:30:15.150: W/System.err(1496): at
    android.os.AsyncTask$2.call(AsyncTask.java:288)

    08-15
    07:30:15.460: W/System.err(1496): at
    java.util.concurrent.FutureTask.run(FutureTask.java:237)

    08-15
    07:30:15.740: W/System.err(1496): at
    android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

    08-15
    07:30:15.830: W/System.err(1496): at
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

    08-15
    07:30:15.830: W/System.err(1496): at
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

    08-15
    07:30:16.180: W/System.err(1496): at
    java.lang.Thread.run(Thread.java:841)

  • Miguel Haber

    i was able to get a response from the server but the data isnt appearing on the spinner. here’s the logcat error

    09-01 07:02:39.574: E/Response:(4027): {“categories”:[{“product_id”:”4″,”category”:”asdsad”},{“product_id”:”5″,”category”:”Burgers”}]}

    09-01 07:02:48.433: W/EGL_emulation(4027): eglSurfaceAttrib not implemented

    09-01 07:02:48.433: W/CanvasContext(4027): Failed to set EGL_SWAP_BEHAVIOR on surface 0xb8647730, error=EGL_SUCCESS

    09-01 07:04:34.274: W/InputEventReceiver(4027): Attempted to finish an input event but the input event receiver has already been disposed.

    • I have the same problem, is there a way to fix this ? thanks before ^_^

    • ekin idris

      me too . how to solve this

  • Rose Caz

    what if

    // Mysql select query
    $result = mysql_query(“SELECT * FROM categories WHERE ID = $ID”) ??? hows that?;

  • Rajasekar G

    Nice Tutorial, Its very useful to me, But I need to select multiple categorizes using multiple selection option.. please help me from back end side I’m not much familiar in php and MySQL, thanks in advance

  • siddharth

    why is createNewCategory(); function called at the end the new_category.php file .. same has been done in the case of get_category.php

  • abha

    Buffer Error-Error converting result java.lang.null.PointerException what can i do .??

  • nuh

    What I need to do if I have two spinners and i want to make selection in one spinner and based on that selection populate the next spinner.

  • Kel

    Hi Ravi,

    Thanks for the great tutorial! May I know how to post the selected item into the database? In other words, instead of pulling the data from the database, could it be possible to post data from the spinner into the database?

    Thank you!

  • Kel

    Hi Ravi,

    Thanks for the great tutorial! May I know how to post the selected item into the database? In other words, instead of pulling the data from the database, could it be possible to post data from the spinner into the database?

    Thanks!

  • Harshada Sabale

    HI,
    Thanks for the great tutorial.I creating the same project as yours but the data is not loaded on the spinner,but it displaying in logcat response…….why it so??
    please suggest me how to show it……..

    • ekin idris

      me too . how to solve this ?

  • folo

    hi guys i try this tutorial but when i add a new category i’m not getting anything in my msql database and i have no error can i have help please

  • Ramir

    Hi, thanks for the tutorial. And what about multiply Spinner? I want to use two or more Spinner. What must be done?

  • Rajat

    Hello Ravi, I tried your code but it is showing the following error in the Logcat…please help me… i m not able to do this from the last two days….is it because of proxy in wifi connection or any other problem…?

    Logcat :
    02-19 16:00:43.091 24909-24926/spinnerdatabase.spinnerdatabase E/Response:﹕ >
    Error Message

    A {
    FONT-WEIGHT: bold; FONT-SIZE: 10pt; COLOR: #005a80; FONT-FAMILY: tahoma
    }
    A:hover {
    FONT-WEIGHT: bold; FONT-SIZE: 10pt; COLOR: #0d3372; FONT-FAMILY: tahoma
    }
    TD {
    FONT-SIZE: 8pt; FONT-FAMILY: tahoma
    }
    TD.titleBorder {
    BORDER-RIGHT: #955319 1px solid; BORDER-TOP: #955319 1px solid; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 12pt; VERTICAL-ALIGN: middle; BORDER-LEFT: #955319 0px solid; COLOR: #955319; BORDER-BOTTOM: #955319 1px solid; FONT-FAMILY: tahoma; HEIGHT: 35px; BACKGROUND-COLOR: #d2b87a; TEXT-ALIGN: left
    }
    TD.titleBorderx {
    BORDER-RIGHT: #955319 0px solid; BORDER-TOP: #955319 1px solid; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 12pt; VERTICAL-ALIGN: middle; BORDER-LEFT: #955319 1px solid; COLOR: #978c79; BORDER-BOTTOM: #955319 1px solid; FONT-FAMILY: tahoma; HEIGHT: 35px; BACKGROUND-COLOR: #d2b87a; TEXT-ALIGN: left
    }
    .TitleDescription {
    FONT-WEIGHT: bold; FONT-SIZE: 12pt; COLOR: black; FONT-FAMILY: tahoma
    }
    SPAN.explain {
    FONT-WEIGHT: normal; FONT-SIZE: 10pt; COLOR: #934225
    }
    SPAN.TryThings {
    FONT-WEIGHT: normal; FONT-SIZE: 10pt; COLOR: #934225
    }
    .TryList {
    MARGIN-TOP: 5px; FONT-WEIGHT: normal; FONT-SIZE: 8pt; COLOR: black; FONT-FAMILY: tahoma
    }
    .X {
    BORDER-RIGHT: #955319 1px solid; BORDER-TOP: #955319 1px solid; FONT-WEIGHT: normal; FONT-SIZE: 12pt; BORDER-LEFT: #955319 1px solid; COLOR: #7b3807; BORDER-BOTTOM: #955319 1px solid; FONT-FAMILY: verdana; BACKGROUND-COLOR: #d1c2b4
    }
    .adminList {
    MARGIN-TOP: 2px
    }

    X

    Network Access Message: The page cannot be displayed

    Explanation: The request timed out before the page could be retrieved.
    Try the following:

    Refresh page: Search for the page again by clicking the Refresh button. The timeout may have occurred due to Internet congestion.
    Check spelling: Check that you typed the Web page address correctly. The address may have been mistyped.
    Contact website: You may want to contact the website administrator to make sure the Web page still exists. You can do this by using the e-mail address or phone number listed on the website home page.

    If you are still not able to view the requested page, try contacting your administrator or Helpdesk.

    Technical Information (for support personnel)

    Error Code 10060: Connection timeout
    Background: The gateway could not receive a timely response from the website you are trying to access. This might indicate that the network is congested, or that the website is experiencing technical difficulties.
    Date: 2/19/2015 10:32:58 AM [GMT]
    Server: SRMUNIV-TMG01
    Source: Firewall
    </UL
    02-19 16:00:43.092 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
    02-19 16:00:43.093 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
    02-19 16:00:43.093 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at org.json.JSONObject.(JSONObject.java:158)
    02-19 16:00:43.093 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at org.json.JSONObject.(JSONObject.java:171)
    02-19 16:00:43.093 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at spinnerdatabase.spinnerdatabase.MainActivity$GetCategories.doInBackground(MainActivity.java:127)
    02-19 16:00:43.093 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at spinnerdatabase.spinnerdatabase.MainActivity$GetCategories.doInBackground(MainActivity.java:106)
    02-19 16:00:43.094 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
    02-19 16:00:43.094 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
    02-19 16:00:43.094 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    02-19 16:00:43.094 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    02-19 16:00:43.094 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    02-19 16:00:43.094 24909-24926/spinnerdatabase.spinnerdatabase W/System.err﹕ at java.lang.Thread.run(Thread.java:838)

    • zd913

      i been messing with this also and i came up with this quckfix:

      JSONObject jsonObj = new JSONObject(json.substring(json.indexOf(“{“”)));

      • Kh Fasi

        I am getting this as a result

        ( ! ) Warning: mysqli_query() expects at least 2 parameters, 1 given in D:xampphtdocsMobileAppindex.php on line 18
        Call Stack
        #TimeMemoryFunctionLocation
        10.0015134480{main}( )…index.php:0
        20.0034141920getUserName( )…index.php:38
        30.0034142272mysqli_query
        ( )…index.php:18

        ( ! ) Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in D:xampphtdocsMobileAppindex.php on line 20
        Call Stack
        #TimeMemoryFunctionLocation
        10.0015134480{main}( )…index.php:0
        20.0034141920getUserName( )…index.php:38
        30.0050142240mysqli_fetch_array
        ( )…index.php:20

        {“users”:[]}

  • Ali

    hey, i want to pass parameters with POST method , how i can ?
    Regards

  • Ilies Belabbas

    how to insert in gategory (database ) ? please i need help :'( :'(

  • sathya kumar

    hi ravi, how we get the category id while we select an item in spinner?

  • sathya kumar

    hi ravi, i got the solution thanks for your coding.

  • Ghaliah

    hi mr.ravi
    if i need to do the opposite, adding a selected option of spinner to mysql database. how we gonna do it?

  • Raven

    Solution for spinner drop down not showing anything :
    add the following code in serviceHandler.java after line 93

    while ((line = reader.readLine()) != null) {
    if(!line.startsWith(“<", 0)){
    if(!line.startsWith("(", 0)){
    sb.append(line + "n");
    }
    }
    }

    • Cillín Lyons

      Worked for me. Cheers dude!

    • ekin idris

      why i copy this code but it give me error ?

  • Miguel Lemos

    Hello Ravi Tamada thank you for article, my question is as you can see in first video after you create new category, when you press the spinner duplicate all other category(only in the spinner) + new category, how fix the duplicated?
    Thank you

  • ari

    the new category display an error message like this:

    {“error”: true, “message”: “Category name is missing!”}

    please help

    • Andrew Nyago

      that could be because of the line:
      include_once dirname(__FILE__) . ‘./Config.php’;

      in the conect() function in DbConnect.php

      Please change it to:
      include_once dirname(__FILE__) . ‘/Config.php’;

  • Chee Phang Lee

    I have one question… when click add the spinner list just keep add the labels below but not refresh the list.

  • Jimmy Best

    Hello i can’t download the tutorial , please give a link for this, thanks

  • Nidhin Kumar

    Hi Ravi,
    How to do the same concept in ms sql database

  • jeanpier echevarria

    Hello as I can put one spinner as key data mysql, I only managed to put text on the spinner but not return me select the data corresponding to that id

  • ekin idris

    hai . why my spinner just display one data ? not as a whole ?

  • hi

    i want choise and upload image file into database and retrieve it

    please help me ,thankyou

  • Poovizhi Chelladurai

    hi. I have error in android prompt

  • Poovizhi Chelladurai

    android:prompt=”@string/prompt” in xml coding coding

    Choose an item – in res- value

    but it doesn’t work so pls someone send correct coding

  • Ashok

    This is not display in mobile running but data display on emulator ,please someone send correct coding

    • Kevin Dias

      did u change the url from localhos(10.0.2.2)t to your ipv4?
      change it to your ipv4, check it on ipconfig on cmd !!
      cheers

  • Aayvid Rekala

    Hi Ravi

    I need a default text for a spinner where values in the spinner are from database

    fetching all details from database into spinner by using arrayadapter,but im not able to apply default text like Select Size for it. i saw many posts ,but i didnt find one which has same requirement,

    Can you help me please 🙁 Here is the code

    String siz =feedObj.getString(“P_Size”);
    Size=(Spinner)findViewById(R.id.size);
    if(siz!= null && !siz.isEmpty())
    {
    String[] seperatedsize = siz.split(“, “);
    // String[] seperatedsize1 = new String[] {“One”} ;
    // ArrayAdapter spinnersize11 = new //ArrayAdapter(this,android.R.layout.simple_spinner_item,seperatedsize1);
    // spinnersize11.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Size.setAdapter(spinnersize11);

    ArrayAdapter spinnersize = new ArrayAdapter(this,android.R.layout.simple_spinner_item,seperatedsize);
    spinnersize.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Size.setAdapter(spinnersize);
    // spinnersize.add(“select”);
    // spinnersize.setPrompt(“Select your Size!”);
    }
    else
    {
    layoutsize.setVisibility(View.GONE);
    Size.setVisibility(View.GONE);
    // TextView spinnersizetext = (TextView)findViewById(R.id.tsize);
    // spinnersizetext.setVisibility(View.GONE);
    }

  • emre

    Hello Ravi ,

    I think you forget to add DbConnect.php in tutorial.

    Here is code for other users to add that file.

    connect();

    }

    function __destruct() {

    $this->close();

    }

    function connect() {

    require_once __DIR__ . ‘/Config.php’;

    $con = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());

    $db = mysql_select_db(DB_NAME) or die(mysql_error()) or die(mysql_error());

    return $con;

    }

    function close() {

    mysql_close();

    }

    }

    ?>

  • zatt

    public final static int GET = 1;

    public final static int POST = 2;
    What is this mean ?

  • Algerian Psycho

    Hey, is there a way to send a record from a spinner to MySQL?

  • Yohanes Adhitiya

    LOVE U FULL

  • $|R_MYK3

    i love this tutorial nice it very helpful but i still wish you can add more feature to it, like when a category have been selected it will display the contents in that category like if cereals it selected it will show all the all categories of cereals and so on

    ok for an example running an E-commerce website / app like an OLX ( like what am trying to compile with all your tutorial ) if some select Games or Mobile Phone or even Sport items it will show contents of all the post belonging to it

    Thanks but so far most of the tutorial and codes i see here is helpful thanks alot

  • suresh

    hi ravi………………
    i have 2 spinners ………2nd spinner value is depends on 1st spinner………but both are dynamic……………

    package com.pivotalsoft.lbce.faculty;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.Toast;

    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

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

    import com.pivotalsoft.lbce.AdminHomeActivity1;
    import com.pivotalsoft.lbce.items.Category;
    import com.pivotalsoft.lbce.items.Person;
    import com.pivotalsoft.lbce.JSONParser;

    import com.pivotalsoft.lbce.R;
    import com.pivotalsoft.lbce.Baseurl.RestUrlActivity;
    import com.pivotalsoft.lbce.subject.Course;
    import com.pivotalsoft.lbce.subject.ServiceHandler;

    //http://www.json-generator.com/api/json/get/cfJpTogNmG?indent=2

    public class AddFacultyActivity extends AppCompatActivity implements View.OnClickListener {

    String fullName;
    String qualification;
    String deptCode;
    String email;
    String password;
    String address;
    int sectionId;
    String category;

    static String coursecode;
    String sectionCode;
    Spinner spinnerOne,spinnerTwo;
    Activity activity;

    private ArrayList categoriesList;
    ProgressDialog pDialog;

    ArrayAdapter spinnerAdapter1;

    //URL Link for get Json Array
    private String URL_COURSES = RestUrlActivity.ipaddres+”rest/admin/deptsList/”;
    // private String URL_COURSES1 = RestUrlActivity.ipaddres+”rest/admin/sectionsList/”;
    private String URL_COURSES1 = RestUrlActivity.ipaddres+”rest/admin/section/ECE”;
    private static String url2 = RestUrlActivity.ipaddres+”rest/admin/newFaculty/”;
    private ArrayList courselist;
    // List param = new ArrayList();

    JSONParser jsonParser = new JSONParser();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addfaculty);
    ((Button)findViewById(R.id.buttonchgpass)).setOnClickListener(this);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(“Add Faculty”);

    new GetCoursesFac().execute();

    courselist = new ArrayList();
    categoriesList=new ArrayList();
    spinnerOne=(Spinner)findViewById(R.id.deptspinner);
    spinnerTwo=(Spinner)findViewById(R.id.sectionSpinner);
    new GetCategories().execute();
    }

    @Override
    public void onClick(View v) {
    // DBHelper dbHelper = new DBHelper(this);
    fullName = ((EditText)findViewById(R.id.newpassvalue)).getText().toString();
    qualification = ((EditText)findViewById(R.id.password)).getText().toString();
    email = ((EditText)findViewById(R.id.emailfield)).getText().toString();
    password = ((EditText)findViewById(R.id.passwordfield)).getText().toString();
    address = ((EditText)findViewById(R.id.address)).getText().toString();

    String courseName = spinnerOne.getItemAtPosition(spinnerOne.getSelectedItemPosition()).toString();
    for (Course course : courselist) {
    if(course.getName().equalsIgnoreCase(courseName)) {
    deptCode = course.getCode();
    break;
    }
    }

    String sectionName=spinnerTwo.getItemAtPosition(spinnerTwo.getSelectedItemPosition()).toString();
    for (Category category :categoriesList){
    if (category.getName().equalsIgnoreCase(sectionName)){
    sectionCode=(category.getName());
    break;
    }

    }

    new HttpAsyncTask().execute(RestUrlActivity.ipaddres + “rest/admin/newFaculty/”);

    /* if(dbHelper.addFaculty(name,qualification,subjects,email,password)){
    Toast.makeText(this,”Faculty Added”,Toast.LENGTH_LONG).show();
    Intent intent = new Intent(this,FacultyListActivity.class);
    intent.putExtra(“type”,1);
    startActivity(intent);
    } else {
    Toast.makeText(this,”failed to fab_add faculty”,Toast.LENGTH_LONG).show();
    }*/
    }

    private class GetCoursesFac extends AsyncTask {
    ArrayList list;
    protected void onPreExecute(){
    super.onPreExecute();

    }
    protected Void doInBackground(Void…params){
    com.pivotalsoft.lbce.subject.ServiceHandler jsonParser = new com.pivotalsoft.lbce.subject.ServiceHandler();
    String json = jsonParser.makeServiceCall(URL_COURSES, com.pivotalsoft.lbce.subject.ServiceHandler.GET);

    Log.e(“Response: “, “> ” + json);

    if (json != null) {
    try {
    JSONObject jsonObj = new JSONObject(json);
    if (jsonObj != null) {
    JSONArray categories = jsonObj
    .getJSONArray(“deptsList”);

    for (int i = 0; i < categories.length(); i++) {
    JSONObject catObj = (JSONObject) categories.get(i);
    com.pivotalsoft.lbce.subject.Course cat = new com.pivotalsoft.lbce.subject.Course(catObj.getString("code"),
    catObj.getString("name"));
    courselist.add(cat);
    }
    }

    } catch (JSONException e) {
    e.printStackTrace();
    }

    } else {
    Log.e("JSON Data", "Didn't receive any data from server!");
    }

    return null;
    }
    protected void onPostExecute(Void result){
    Log.d("spinner","date");
    populateSpinner();
    }
    }
    private void populateSpinner() {
    List lables = new ArrayList();

    for (int i = 0; i < courselist.size(); i++) {
    lables.add(courselist.get(i).getName());
    }

    // Creating adapter for spinner
    final ArrayAdapter spinnerAdapter = new ArrayAdapter(this,
    android.R.layout.simple_spinner_item, lables);

    // Drop down layout style – list view with radio button
    spinnerAdapter
    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinnerOne.setAdapter(spinnerAdapter);

    /*spinnerOne.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView adapterView, View view, int position, long l) {

    new GetCategories().execute();

    }

    @Override
    public void onNothingSelected(AdapterView adapterView) {

    }
    });*/
    }

    private class GetCategories extends AsyncTask {

    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(AddFacultyActivity.this);
    pDialog.setMessage(“Fetching ….”);
    pDialog.setCancelable(false);
    pDialog.show();

    }

    @Override
    protected Void doInBackground(Void… arg0) {
    ServiceHandler jsonParser = new ServiceHandler();
    String json = jsonParser.makeServiceCall(URL_COURSES1, ServiceHandler.GET);

    Log.e(“Response: “, “> ” + json);

    if (json != null) {
    try {
    JSONObject jsonObj = new JSONObject(json);
    if (jsonObj != null) {
    JSONArray categories = jsonObj
    .getJSONArray(“Section”);

    for (int i = 0; i < categories.length(); i++) {
    JSONObject catObj = (JSONObject) categories.get(i);
    Category cat = new Category(catObj.getInt("sectionId"),
    catObj.getString("sectionName"));
    categoriesList.add(cat);
    }
    }

    } catch (JSONException e) {
    e.printStackTrace();
    }

    } else {
    Log.e("JSON Data", "Didn't receive any data from server!");
    }

    return null;
    }

    @Override
    protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    if (pDialog.isShowing())
    pDialog.dismiss();
    populateSpinnertwo();

    }

    }

    /**
    * Adding spinner data
    * */
    private void populateSpinnertwo() {
    List lables = new ArrayList();

    //txtCategory.setText(“”);

    for (int i = 0; i < categoriesList.size(); i++) {
    lables.add(categoriesList.get(i).getName());
    }

    // Creating adapter for spinner
    spinnerAdapter1 = new ArrayAdapter(this,
    android.R.layout.simple_spinner_item, lables);

    // Drop down layout style – list view with radio button
    spinnerAdapter1
    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinnerTwo.setAdapter(spinnerAdapter1);
    /*spinnerTwo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView parentView, View view, int position, long l) {

    sectionId=position;
    sectionCode=parentView.getSelectedItem().toString().trim();

    // Toast.makeText(AddFacultyActivity.this, “sectionId: “+category.getId()+”, sectionName : “+category.getName(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView adapterView) {

    }
    });*/

    }

    public static String POST(String url2, Person person){
    InputStream inputStream = null;
    String result = “”;
    try {

    // 1. create HttpClient
    HttpClient httpclient = new DefaultHttpClient();

    // 2. make POST request to the given URL
    HttpPost httpPost = new HttpPost(RestUrlActivity.ipaddres+”rest/admin/newFaculty/”);

    String json = “”;

    // 3. build jsonObject
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate(“fullName”, person.getFullName());
    jsonObject.accumulate(“qualification”, person.getQualification());
    jsonObject.accumulate(“deptCode”, person.getDeptCode());
    jsonObject.accumulate(“email”, person.getEmail());
    jsonObject.accumulate(“password”, person.getPassword());
    jsonObject.accumulate(“sectionId”,person.getSectionId());
    jsonObject.accumulate(“address”, person.getAddress());

    // 4. convert JSONObject to JSON to String
    json = jsonObject.toString();

    // ** Alternative way to convert Person object to JSON string usin Jackson Lib
    // ObjectMapper mapper = new ObjectMapper();
    // json = mapper.writeValueAsString(person);

    // 5. set json to StringEntity
    StringEntity se = new StringEntity(json);

    // 6. set httpPost Entity
    httpPost.setEntity(se);

    // 7. Set some headers to inform server about the type of the content
    httpPost.setHeader(“Accept”, “application/json”);
    httpPost.setHeader(“Content-type”, “application/json”);

    // 8. Execute POST request to the given URL
    HttpResponse httpResponse = httpclient.execute(httpPost);

    // 9. receive response as inputStream
    inputStream = httpResponse.getEntity().getContent();

    // 10. convert inputstream to string
    if(inputStream != null)
    result = convertInputStreamToString(inputStream);
    else
    result = “Did not work!”;

    } catch (Exception e) {
    Log.d(“InputStream”, e.getLocalizedMessage());
    }

    // 11. return result
    return result;
    }

    private class HttpAsyncTask extends AsyncTask {
    @Override
    protected String doInBackground(String… urls) {

    Person person = new Person();
    person.setFullName(fullName);
    person.setQualification(qualification);
    person.setDeptCode(deptCode);
    person.setEmail(email);
    person.setPassword(password);
    person.setSectionId(sectionId);
    person.setAddress(address);

    return POST(urls[0],person);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
    Toast.makeText(getBaseContext(), “Data Sent!”, Toast.LENGTH_SHORT).show();

    Log.e(“data”, result);

    Toast.makeText(getApplication(), result, Toast.LENGTH_SHORT).show();

    startActivity(new Intent(AddFacultyActivity.this, AdminHomeActivity1.class));
    }
    }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = “”;
    String result = “”;
    while((line = bufferedReader.readLine()) != null)
    result += line;

    inputStream.close();
    return result;

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
    onBackPressed();
    return true;
    default:
    return super.onOptionsItemSelected(item);
    }
    }

    }

  • cabrel

    please how can i use my ip address 192.168.1.103 in this code? please help me

    • Ronel Calinisan

      “http://192.168.1.103/”yourfolder”/new_category.php”;

  • Ronel Calinisan

    Here’s DbConnect.php. 🙂

    connect();
    }

    // destructor
    function __destruct() {
    // closing db connection
    $this->close();
    }

    /**
    * Establishing database connection
    * @return database handler
    */
    function connect() {
    include_once dirname(__FILE__) . ‘./Config.php’;

    // Connecting to mysql database
    $this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die(mysql_error());

    // Selecting database
    mysql_select_db(DB_NAME) or die(mysql_error());

    // returing connection resource
    return $this->conn;
    }

    /**
    * Closing database connection
    */
    function close() {
    // closing db connection
    mysql_close($this->conn);
    }

    }

    ?>

    • Ronel Calinisan

      🙂

      • Pasindu Ranasinghe

        Code have some err pls fix it

  • vinod

    sir, how to refresh my sql spinner????

  • Mass Wahid

    sir, I just only need to display spinner only. not for edit categories. so how to do that….?

  • Faisal Qayyum

    Kindly share your json result it will help us to match it with our result. As now there are some few changes made in the code by the framework so the final result may differs

    But thanks for this great tutorial

  • Kalai Vanan

    How to getId for selected Item in the list

  • Viral Patel

    I want multiple Spinner. Example : Select country => Select State => Select City
    By using JSON MySQL in Android
    Along with PHP file.

    • Damion

      Me as well. If anyone knows how to do this please respond

  • Sicnarf Omsare

    Hi Ravi, thanks again for this wonderful tutorial, But after running the app, I got stuck into this problem..
    09-11 23:35:35.424: E/Response:(31471): >
    09-11 23:35:35.424: E/Response:(31471):
    09-11 23:35:35.424: E/Response:(31471): 403 Forbidden
    09-11 23:35:35.424: E/Response:(31471):
    09-11 23:35:35.424: E/Response:(31471): Forbidden
    09-11 23:35:35.424: E/Response:(31471): You don’t have permission to access /food_api/get_categories.php
    09-11 23:35:35.424: E/Response:(31471): on this server.
    09-11 23:35:35.424: E/Response:(31471):
    09-11 23:35:35.424: E/Response:(31471):
    09-11 23:35:35.424: E/Response:(31471): Apache/2.4.23 (Win64) PHP/5.6.25 Server at 192.168.43.193 Port 80
    09-11 23:35:35.424: E/Response:(31471):
    09-11 23:35:35.444: E/ViewRootImpl(31471): sendUserActionEvent() mView == null

    can you help me on this one, thanks and Godbless

    • It seems the problem is with MAMP configuration. Access the same url via browser or postman. You need to solve MAMP 403 access denied problem.

  • Damion

    I need to set the first item of the spinner to a specific item in the database table. Not simply the item listed as id 1, which the spinner does automatically. I used the code in the link below to do this. Please help me manipulate this code to choose which item is displayed first in the spinner.

  • கவிதா பார்த்திபன்

    hai, when i press the add button it shows the database data as twice. i want the correct code please. thanks