Spinner

คอมโบบ็อก โดยดึงข้อมูลมาจากฐานข้อมูล

activity_main.xml

<?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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.phaisarn.jackapplication.MainActivity">

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">

        <EditText android:id="@+id/edittext_newcategory" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="New Category" />

        <Button android:id="@+id/button_category" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add" />

    </LinearLayout>

    <Spinner android:id="@+id/spinner_categories" android:layout_width="fill_parent" android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

package com.phaisarn.jackapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 DataBaseHelper db;
    private Spinner spinnerCategories;
    private EditText editTextNewCategory;
    private Button buttonCategory;

    private List<String> listCategories = new ArrayList<>();
    private ArrayAdapter<String> adapter;

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

        // connect database
        db = new DataBaseHelper(this);
        if (db == null)
            db = new DataBaseHelper(this);

        spinnerCategories = (Spinner) findViewById(R.id.spinner_categories);
        editTextNewCategory = (EditText) findViewById(R.id.edittext_newcategory);
        buttonCategory = (Button) findViewById(R.id.button_category);
        buttonCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String newCategory = editTextNewCategory.getText().toString();
                if (newCategory .equalsIgnoreCase("")) {
                    Toast.makeText(getApplicationContext(), "Please Enter New Category", Toast.LENGTH_SHORT).show();
                } else {
                    db.addCategory(new Category(newCategory ));
                    prepareData();
                    editTextNewCategory.setText("");
                    //Toast.makeText(MainActivity.this, "New Category was Successfully added to Database", Toast.LENGTH_SHORT).show();
                }
            }
        });

        prepareData();
    }

    public void prepareData() {
        listCategories = db.getAllCategories();
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, android.R.id.text1, listCategories);
        spinnerCategories.setAdapter(adapter);
    }
}

Category.java

package com.phaisarn.jackapplication;

/**
 * Created by jack on 2/9/2017.
 */

public class Category {
    int id;
    String name;

    public Category(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

DataBaseHelper.java

package com.phaisarn.jackapplication;

/**
 * Created by jack on 2/9/2017.
 */

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;

public class DataBaseHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "categories";
    private static final String TABLE_NAME = "category";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";

    private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY,"
            + COLUMN_NAME + " TEXT" + ")";
    private static final String CREATE_UNIQUE_INDEX = "CREATE UNIQUE INDEX IF NOT EXISTS "
            + COLUMN_NAME + " ON "
            + TABLE_NAME + "(" + COLUMN_NAME + ")";

    public DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
        db.execSQL(CREATE_UNIQUE_INDEX);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Drop table if exists
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        //create the table again
        onCreate(db);
    }

    public void addCategory(Category category) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_NAME, category.getName());
        db.insert(TABLE_NAME, null, cv);
        db.close();
    }

    public List<String> getAllCategories() {
        List<String> list = new ArrayList<>();

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT " + COLUMN_NAME + " FROM " + TABLE_NAME, null);
        if (cursor.moveToFirst()) {
            do {
                list.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return list;
    }
}