How to load a spinner with values from SQlite Database in android?

Here is a simple example showing how to load a database values in a spinner in android.

Spinner from SQLite

OK we will start.

This is the layout for the spinner row.
spinner_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation     =      "vertical"
    android:id="@+id/tv"
    android:layout_margin="10dp">   
</TextView>

This is the layout for the interface.

activity_main.xml

<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" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:text="Load DB values into Spinner"
         >
    </TextView>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_below="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</LinearLayout>

Now this is the MainActivity.java file that uses the spinner and the database.

package com.coderzheaven.loadspinnerfromdb;

import   java  .util  .ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	SQLiteDatabase mydb;
	private   static String DBNAME = "PERSONS.db";
	private static String TABLE = "MY_TABLE";

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

		createTable();
		insertIntoTable();

		ArrayList<String> my_array = new ArrayList<String>();
		my_array = getTableValues();

		Spinner My_spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row,
				my_array);
		My_spinner.setAdapter(my_Adapter);
	}

	// CREATE TABLE IF NOT EXISTS
	public void createTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("CREATE TABLE IF  NOT EXISTS " + TABLE
					+ " (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error in creating table",
					Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION INSERTS DATA TO THE DATABASE
	public void insertIntoTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('ANTHONY','USA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SHUING','JAPAN')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('JAMES','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SOORYA','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('MALIK','INDIA')");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error in inserting into table", Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION SHOWS DATA FROM THE DATABASE
	public ArrayList<String> getTableValues() {

		ArrayList<String> my_array = new ArrayList<String>();
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
			System.out.println("COUNT : " + allrows.getCount());

			if (allrows.moveToFirst()) {
				do {

					String ID = allrows.getString(0);
					String NAME = allrows.getString(1);
					String PLACE = allrows.getString(2);
					my_array.add(NAME);

				} while (allrows.moveToNext());
			}
			allrows.close();
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error encountered.",
					Toast.LENGTH_LONG);
		}
		return my_array;
	}

}

Join the Forum discussion on this post

Note : Please remove the “span” tags from the post when you copy it.

Download the complete source code for this example from here.

How to save CheckBox values in SQlite Database and Load it later?

Hello……..

This post is just a simple demonstration to show a way to store a checkbox value in a database and reload it. Here I am storing only a value of a single checkbox and reloading it. But you can make changes in the code to save the id and value of the checkbox in the database and reload the values accordingly.

For the Sqlite functions I am creating a file that has the table and the function for inserting and other manipulations.

package com.coderzheaven.pack;

import java.util.Set;
import java.util.Map.Entry;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class MyTable
{
	 private String TABLE_NAME = "my_table";
	 int DATABASE_VERSION = 1;
	 private String _ID = "id";
	 private String _CHK_VALUES = "checkbox_value";

	public String getTableName(){			return TABLE_NAME;}
	public int getDatabaseVersion()	{		return DATABASE_VERSION;}

	public String getID()		{		return _ID;			}
	public String getScore()	{		return _CHK_VALUES;		}

	public String getDatabaseCreateQuery()
	{
		final String DATABASE_CREATE =
		    "create table IF NOT EXISTS " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, "
		    + _CHK_VALUES + " TEXT NOT NULL)";

		return DATABASE_CREATE;
	}
}

class dbOperation
{
		static String DB_TABLE ;
		static int DB_VERSION = 1;
		static String[] DATABASE_CREATE;
	    private Context context;
	    private DatabaseHelper DBHelper;
	    private SQLiteDatabase db;

	    public dbOperation(Context ctx,String[] query)
	    {
	    	this.context = ctx;
 	        DATABASE_CREATE = query;
 	        DBHelper = new DatabaseHelper(context);
	    }
	    public dbOperation(Context ctx)
	    {
	    	this.context = ctx;
	    	DBHelper = new DatabaseHelper(context);
	    }

	    public dbOperation(String tablename)  //for inner calling
	    {
	    	DB_TABLE = tablename;
	    	DBHelper = new DatabaseHelper(context);
	    }

		public dbOperation open() throws SQLException
	    {
	        db = DBHelper.getWritableDatabase();
	        return this;
	    }
	    public void close()
	    {
	        DBHelper.close();
	    }
	    private static class DatabaseHelper extends SQLiteOpenHelper
	    {
	        DatabaseHelper(Context context)
	        {
	            super(context, "mydb.db", null, DB_VERSION);
	        }
	        public void onCreate(SQLiteDatabase db)
	        {
	            try
	            {
	            	for (String s  : DATABASE_CREATE)
	            	{
	            		db.execSQL(s);
					}
				}
	            catch (Exception e) {
					System.out.println("Error creating items Per screen in the constructor" + e.getMessage());
				}
	        }
	        public void onUpgrade(SQLiteDatabase db, int oldVersion,
	        int newVersion)
	        {
	        	db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
	            onCreate(db);
	        }
	    }

	    public long insertTableData(String tablename,ContentValues values)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	ContentValues initialValues2 = new ContentValues();
	        Set<Entry<String, Object>> s =  values.valueSet();
	        String new_val = "";
	        for (Entry<String, Object> entry : s) {
	            new_val = values.getAsString(entry.getKey());
	            initialValues2.put(entry.getKey(), new_val);
	        }
	        return db.insert(DB_TABLE, null, initialValues2);
	    }
	    public boolean deleteTableData(String tablename,String condition)  throws SQLException
	    {
	    	DB_TABLE = tablename;
	    	return db.delete(DB_TABLE, condition, null) > 0;
	    }
	    public Cursor getAllTableData(String tablename,String[] fields)  throws SQLException
	    {
	    	DB_TABLE = tablename;
				return db.query(DB_TABLE, fields,null, null, null, null, null);
	    }
	    public Cursor getTableRow(String tablename,String[] dbFields, String condition,String order,String limit) throws SQLException
	    {
	    	DB_TABLE = tablename;
	        Cursor mCursor =    db.query(false, DB_TABLE, dbFields,condition,
	                			null,null,null, order, limit);

	        if (mCursor != null) {
	            mCursor.moveToFirst();
	        }
	        return mCursor;
	    }
	    public boolean updateTable(String tablename,ContentValues args,String condition)
	    {
	    	DB_TABLE = tablename;
	    	return db.update(DB_TABLE, args,condition , null) > 0;

	    }
	    public int lastInsertedID(String tablename)
	    {
	    	int retVar=0;
	    	Cursor mCursor = db.rawQuery("select max(id) from "+tablename, null);

			if (mCursor != null) {
				mCursor.moveToFirst();
				retVar =Integer.parseInt(mCursor.getString(0));
			}
			mCursor.close();
			mCursor.deactivate();
			return retVar ;
	    }
}

Noe the main java source code for implementing this.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class SaveCheckBoxDemo extends Activity {

	CheckBox ch;
	Button save, reload;
	int checked = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initializeDB();

        save = (Button)findViewById(R.id.Button01);
        reload = (Button)findViewById(R.id.Button02);

        ch = (CheckBox)findViewById(R.id.CheckBox01);
        ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					checked = 1;
				}else{
					checked = 0;
				}
			}
		});

        save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				updateTable(checked);
				Toast.makeText(getApplicationContext(), "Saved '"+ checked + "' in DB", Toast.LENGTH_SHORT).show();
			}
		});

        reload.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("getData(1) : " + getData(1));
				Toast.makeText(getApplicationContext(), "value from DB : " + getData(1), Toast.LENGTH_SHORT).show();
				if(getData(1).equalsIgnoreCase("0"))
					ch.setChecked(false);
				else
					ch.setChecked(true);
			}
		});
    }


	public  void initializeDB(){
		MyTable user = new MyTable();
	    String[] tableCreateArray = { user.getDatabaseCreateQuery() };
	    dbOperation operation = new dbOperation(this,tableCreateArray);
	    operation.open();
	    operation.close();
	}

	/*** SAVE THE DATA IN DB - GIVE FILENAME AND DATA ***/
	public  void saveData(int data){
			dbOperation operationObj = new dbOperation(this);
	        operationObj.open();
	        MyTable Fields = new MyTable();
	        ContentValues initialValues = new ContentValues();
	        initialValues.put(Fields.getScore(), data);
	        operationObj.insertTableData(Fields.getTableName(),initialValues);
	        operationObj.close();
	}

	/*** GET THE DATA FROM DB ,PARAMS - FILENAME -> GET THE DATA ***/
	public String getData(int id){
		String _data = "";
		dbOperation operationObj = new dbOperation(this);
		operationObj.open();
		MyTable fields = new MyTable();
		String  condition2 = fields.getID() + " ='" + id + "'";
        String[] dbFields4 = {fields.getScore()};
        Cursor cursor2 =  operationObj.getTableRow(fields.getTableName(),dbFields4,condition2,fields.getID() + " ASC ","1");
        if(cursor2.getCount() > 0)
        {
        	 cursor2.moveToFirst();
        	 do{
        		 _data = cursor2.getString(0);
        	 }while(cursor2.moveToNext());
        }else{
        	_data = "error";
        }
        cursor2.close();
        cursor2.deactivate();
        operationObj.close();
        return _data;
	}

	/*** SAVE OR UPDATE DB -> GIVE THE FILENAME AND DATA ***/
	public void updateTable(int updt_data){
		 	dbOperation operationObj = new dbOperation(this);
	        operationObj.open();
	        MyTable Fields = new MyTable();
	        //check for the value to update if no value then insert.
	        String file_ = getData(1);
	        if(file_.equals("error")){
	        	saveData(updt_data);
	        }else{
		        String  condition = Fields.getID() +" = '1'";
		        ContentValues initialValues = new ContentValues();
		        initialValues.put(Fields.getScore(), updt_data);
		        operationObj.updateTable(Fields.getTableName(),initialValues,condition);
	        }
	        operationObj.close();
	}
}

Now the xml file main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Saving CheckBox Value in database and reloading it."
	    />
	<CheckBox
		android:text="Coderzheaven"
		android:id="@+id/CheckBox01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</CheckBox>
	<Button
		android:text="Save CheckBox Value in DB"
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
	<Button
		android:text="Load CheckBox Value from DB"
		android:id="@+id/Button02"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</Button>
</LinearLayout>

OK Done. Here what I have done is simply saving ’1′ if the checkbox is checked and ’0′ if not checked.

Evi more intelligent than Siri and Iris

Ever Since the launch of Siri in iOS smartphones has become more user friendly and funny for people.
After that Iris was launched a rival for Siri, this too was a big hit.

A little bit about Siri
The application uses a natural language user interface to answer questions, make recommendations, and perform actions by delegating requests to a set of web services. Apple claims that the software adapts to the user’s individual preferences over time and personalizes results, and performing tasks such as finding recommendations for nearby restaurants, or getting directions

A little about Iris.

Iris is a personal assistant application for Android. The application uses natural language processing to answer questions based on user voice request. Iris currently supports Call, Text, Contact Lookup, and Web Search actions including playing videos, looking for: lyrics, movies reviews, recipes, news, weather, places and others. It was developed in 8 hours by Narayan Babu and his team at Dexetra Software Solutions Private Limited, a Kochi (India) based firm.

Now about Evi

Evi was launched by True Knowledge Ltd. company in Cambridge, England.
Evi was launched on January 19th 2012
Evi is a cloud based Artificial Intelligence (AI) which builds upon the core semantic search technology first used on www.trueknowledge.com While she has an app for both Android and iPhone, these are merely portals through which users can communicate with her. Users can ask questions by speaking or by using text input.
The app is free for download on Android, but has a nominal charge of $1 (£0.69) on iPhone to cover the cost of the voice recognition service, Nuance, which is not needed on the Android OS.
Evi is able to provide users with information via different means:
A direct answer derived from her database of (at time of writing) nearly a billion facts
Calling a number of APIs for specialist services and dynamic information which include TV listings, train times, restaurant bookings and more
Referring the user to websites which are directly related to the specific question
Checking Q&A sites to see if the question has been asked previously
Performing a web search and presenting the top results within the app.
Evi also includes a built in browser which allows the user to make use of the information presented, booking restaurants and making online purchases within the app itself.

Working with SQLite databases through command Line in android.

Hello all,
In todays tutorial I will show you how to work with sqlite databases in android through command line.

Advantages
1. You can browse any number of databases.
2. You can write any queries and execute.

First go through these tutorials to get a glance of how to work with sqlite databases in android.
1. http://coderzheaven.com/2011/04/sqlitemanager-plugin-for-eclipse/
2. http://coderzheaven.com/2011/04/using-sqlite-in-android-a-really-simple-example/
3. http://coderzheaven.com/2011/02/working-with-sqlite-database-in-android/

After going through these tutorials you will get to know these.
1. How to create an SQLite database.?
2. Where to locate the database file in your device or emulator?
3. How to browse the database using the plugin I provided in this example(http://coderzheaven.com/2011/04/sqlitemanager-plugin-for-eclipse/
)?

I am using the sqlite database that I created using this example
http://coderzheaven.com/2012/01/how-to-save-score-in-android-cocos2d/

Now open the command prompt or terminal and type

adb -s emulator-5554 shell

now type the path of your sqlite database like this.

sqlite3 /data/data/com.coderzheaven.pack/databases/mytest.db

check the screenshot for example

Now look at the screenshot for how am I navigating through the tables and selecting and inserting values to the table creating new tables etc.
Click and enlarge the image to see it.


You can exit the shell by typing ‘ ctrl+d’ twice.

This is the path of my database file
/data/data/com.coderzheaven.pack/databases/mytest.db

Which you can see by opening the file explorer from the window menu and expanding your package folder.(check this example for a screenshot of how to see the database http://coderzheaven.com/2012/01/how-to-save-score-in-android-cocos2d/)

Now about the SQLite database file.
Here I have three tables my_table, temp_table and test_table.
I am executing different commands to manipulate these tables.
The results are appearing just after the command

Please leave your valuable comments on this post.
Also +1 this post to share it to others if you liked it.

SQLiteManager plugin for eclipse

When you are working on an Android application that stores data in a SQLite database.There arise many questions like
where does this database file get stored on the filesystem ?
How can we access the database?

I will give solution to all these problems. I created the database from my previous post
about Using SQLite in ANDROID

You can see the sqlite database in eclipse by opening File Explorer .Then

/data/data/package_name/databases

But here we cannot see the tables and table data.
For viewing the table details Eclipse has a plugin. You can download the jar from below.

Download the jar from the sqlite manager from here.

Now put the jar in the folder


eclipse/dropins/


and restart the eclipse and now you can see the sqlitemanager plugin on the top right of the File Explorer window

SQLite

By clicking the icon, sqliteManager Window comes and here we can see the table structure.

SQLite

and then the Browse Data tab shows the whole data
SQLite

Hopefully i think you cleared all doubts about SqliteManager Plugin

Note : If you’re using a plug-in for which no Update Site is available, you can use the “dropins” folder in your Eclipse installation directory.

Plug-ins are typically distributed as .jar files. To add a plug-in to your Eclipse installation, put the plug-in .jar file into the Eclipse “dropins” folder and restart Eclipse. Eclipse should detect the new plug-in and install it for you.

Note : if your SQLiteManager Plugin is not enabled, then check your sqlite db file extension. It should be a “.db” extension.

Please check my another ANDROID BLOG FOR MORE ANDROID CODES AND SAMPLES.