Friday, December 30, 2016

Android Populating Spinner Data From SQLite Database

In previous tutorial i also created CRUD (Create, Read, Update, Delete) function using database SQLite. On that tutorial there is a condition where the data must be displayed on spinner.

If you are newbie in Android, it my previous tutorial maybe too complicated for you to get which point is actually the spinner function.

To make you easy understand the process, so i creating this tutorial, especially how to populating spinner data from SQLite.

If you need to go through to the CRUD tutorial, you can read here : Android SQLite Database Tutorial

Let's start created this tutorial. As always a provide you a video demo in order you get what the output of this tutorial.

VIDEO DEMO



IMPLEMENTATION

First, create model of your data, in this case i name my model as OwnerModel.java, then paste the following code :

package com.putuguna.dataspinnerfromsqlite;
/**
* Created by putuguna on 30/12/16.
*/
public class OwnerModel {
private int ownerID;
private String ownerName;
public OwnerModel() {
}
public int getOwnerID() {
return ownerID;
}
public void setOwnerID(int ownerID) {
this.ownerID = ownerID;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
@Override
public String toString() {
return ownerName;
}
}
view raw OwnerModel.java hosted with ❤ by GitHub
Second, create java class that called DatabaseHandler.java. Paste the following code :

package com.putuguna.dataspinnerfromsqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by putuguna on 30/12/16.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "database_corporate";
private static final String TABLE_OWNER = "table_owner";
private static final String ID_OWNER = "id";
private static final String OWNER_NAME = "name";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// CREATE THE TABLE
String CREATE_DATABASE = "CREATE TABLE " + TABLE_OWNER + "(" +
ID_OWNER + " INTEGER PRIMARY KEY, " + OWNER_NAME + " TEXT" + ")";
sqLiteDatabase.execSQL(CREATE_DATABASE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//CHECKING TABLE
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_OWNER);
onCreate(sqLiteDatabase);
}
/**
* this method used to insert data to the table owner
* @param owner
*/
public void insertData(OwnerModel owner){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(OWNER_NAME, owner.getOwnerName());
database.insert(TABLE_OWNER, null, values);
database.close();
}
/**
* this method used to get All the data owner
* @return
*/
public List<OwnerModel> getAllOwnerName(){
List<OwnerModel> listOwnerName = new ArrayList<>();
String query = "SELECT * FROM " + TABLE_OWNER;
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(query, null);
if(cursor.moveToFirst()){
do{
OwnerModel owner = new OwnerModel();
owner.setOwnerID(Integer.parseInt(cursor.getString(0)));
owner.setOwnerName(cursor.getString(1));
listOwnerName.add(owner);
}while (cursor.moveToNext());
}
return listOwnerName;
}
/**
* this method used to delete all data from table owner
*/
public void deleteAllDataFromTable(){
SQLiteDatabase database = this.getWritableDatabase();
database.execSQL("DELETE FROM " + TABLE_OWNER);
database.close();
}
}
Attention :
In code above we define all the main function of CRUD, the query, or anything that related with database. I Have explained this class on previous tutorial here : Android SQLite Database Tutorial

Third, create MainActivity's layout. Usually, the name is always activity_main.xml. After that paste the following xml code :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/activity_horizontal_margin"
android:orientation="vertical"
tools:context="com.putuguna.dataspinnerfromsqlite.MainActivity">
<TextView
android:gravity="center"
android:textColor="@android:color/black"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Spinner www.androidbie.com" />
<EditText
android:layout_marginTop="10dp"
android:id="@+id/et_owner_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Owner name"/>
<Button
android:id="@+id/btn_insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert"/>
<TextView
android:layout_marginTop="20dp"
android:text="List Of Owner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="@+id/spinner_owner"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="40dp"></Spinner>
<Button
android:id="@+id/btn_clear_data_spinner"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear Data"/>
</LinearLayout>
Fourth, In your MainActivity.java will do much technical process like, input the data, display data to spinner and clear/delete all data from SQLite database. Paste the following code :

package com.putuguna.dataspinnerfromsqlite;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText etOwnerName;
private Button btnInsert;
private Spinner spinnerOwner;
private Button btnClearData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etOwnerName = (EditText) findViewById(R.id.et_owner_name);
spinnerOwner = (Spinner) findViewById(R.id.spinner_owner);
btnInsert = (Button) findViewById(R.id.btn_insert);
btnClearData = (Button) findViewById(R.id.btn_clear_data_spinner);
final DatabaseHandler handler = new DatabaseHandler(this);
final OwnerModel model = new OwnerModel();
//first launch the app, we have to display the data
getAllData(handler, model);
// input data
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inputDataOwner(handler);
}
});
// clear all data
btnClearData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handler.deleteAllDataFromTable();
getAllData(handler, model);
}
});
}
/**
* this method used to inputdata from edittext to the database
* @param handler
*/
private void inputDataOwner(DatabaseHandler handler){
String ownerName = etOwnerName.getText().toString();
if(TextUtils.isEmpty(ownerName)){
Toast.makeText(this, "Empty field if not allowed", Toast.LENGTH_SHORT).show();
}else{
OwnerModel ownerModel = new OwnerModel();
ownerModel.setOwnerName(ownerName);
handler.insertData(ownerModel);
getAllData(handler,ownerModel);
etOwnerName.setText("");
}
}
/**
* this method used to get all the data of owner and set on spinner
* @param handler
* @param model
*/
private void getAllData(DatabaseHandler handler, OwnerModel model){
List<OwnerModel> ownerModelList = handler.getAllOwnerName();
ArrayAdapter<OwnerModel> arrayAdapter = new ArrayAdapter<OwnerModel>(this, android.R.layout.simple_spinner_item, ownerModelList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinnerOwner.setAdapter(arrayAdapter);
}
}
Run your project, hope it works well. Thank you.

Related Posts


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)