I have got one table with two column (id,name). Toast should show the "name" details from sqlite while choosing the id from spinner.
Ex: Sqlite table 1,899,Chris and 2,890,David.
Whenever i select value 899 from spinner then Toast should display Chris and if i select spinner 890 then Toast should display David. Suggestion needed.
Code: SpinnerEx4Activity.Java
package com.bar.example.androidspinnerexample;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleCursorAdapter;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.content.Intent;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnClickListener;
import android.util.Log;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.EditText;
import java.util.LinkedList;
import android.view.inputmethod.InputMethodManager;
public class SpinnerEx4Activity extends Activity implements
AdapterView.OnItemSelectedListener {
Spinner s1,s2;
Button btnAdd;
EditText inputLabel;
DatabaseHandler dbhndlr; //<<<<< Single instance for Database handler
Cursor spinner1csr;
Cursor spinner2csr; //<<<<< Cursor for spinner (close in onDestroy)
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_ex4);
s1 = (Spinner)findViewById(R.id.spinner1);
s2 = (Spinner)findViewById(R.id.spinner2);
btnAdd = (Button) findViewById(R.id.btn_add);
s1.setOnItemSelectedListener(this);
dbhndlr = new DatabaseHandler(this); //<<<< Instantiate Databasehandler
//loadSpinnerData(); //<<<< commented out
altLoadSpinnerData();
altLoadSpinnerData1();//<<<< Load via cursor
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler commeneted out, use dbhndlr instance instead
// inserting new label into database
dbhndlr.insertLabel(label);
// making input filed text to blank
inputLabel.setText("");
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
// loading spinner with newly added data
//loadSpinnerData(); //<<<< commeneted out
altLoadSpinnerData();
altLoadSpinnerData1();
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
// New method to utilise Cursor adapter
private void altLoadSpinnerData() {
spinner1csr = dbhndlr.getAllLabelsAsCursor();
SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, // Layout to show 2 items
spinner1csr, // Cursor
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},// Views into which data is shown
0
);
s1.setAdapter(sca);
}
private void altLoadSpinnerData1 () {
// get the cursor
spinner2csr = dbhndlr.getAllLabelsAsCursor();
// Instantiaie Simple Cursor Adapter
SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, // Layout to show 2 items
spinner2csr, // Cursor
new String[]{DatabaseHandler.KEY_ID}, // Source data
new int[]{android.R.id.text2}, // Views into which data is shown
0
);
s2.setAdapter(sca);
s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"You Selected: " + id + " " +
spinner2csr.getString(
spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
Toast.LENGTH_SHORT
).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}}
And Databasehandler.java
package com.bar.example.androidspinnerexample;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "spinnerExample";
// Labels table name
private static final String TABLE_LABELS = "labels";
// Labels Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
// Inserting Row
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
/**
* Getting all labels
* returns list of labels
* */
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}
And activity_spinner_ex4.xml is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dip"
android:text="@string/lblAcc" />
<!-- Spinner Dropdown -->
<Spinner
android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
android:layout_marginTop="10dip"
/>
<!-- Select Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dip"
android:text="@string/lblSubAcc" />
<!-- Spinner Dropdown -->
<Spinner
android:id="@+id/spinner2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
/>
<EditText android:id="@+id/input_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"/>
<!-- Add Button -->
<Button android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Label"
android:layout_marginLeft="8dip"
android:layout_marginTop="8dip"/>
</LinearLayout>
Inserting the spinner and checkbox value into another table. i am able to insert all data. but all checkbox text is saving instead of selected one.could you assist.
main activity.
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//String label = inputLabel.getText().toString();
String SaveString="No";
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
String message1= ((Cursor) s1.getSelectedItem()).getString(2);
String message2= ((Cursor) s2.getSelectedItem()).getString(1);
String message = inputLabel.getText().toString();
// String message1 = s1.getSelectedItem().toString();
// String message2 = s2.getSelectedItem().toString();
String message10 = s3.getSelectedItem().toString();
String message4 = ck1.getText().toString();
String message5 = ck2.getText().toString();
String message6 = ck3.getText().toString();
String message7 = ck4.getText().toString();
String message9 = ck6.getText().toString();
String message3 = ck7.getText().toString();
String message8 = ck8.getText().toString();
db.insertLabel(message1,message2,message5,message6,message7,message9,message3,message4,message8,message10);
if (ck1.isChecked())
{ SaveString="Yes";
}
else
{ SaveString="No";
}
if (ck2.isChecked())
{ SaveString="Yes";
}
else
{ SaveString="No";
}
if (message.trim().length() > 0) {
// database handler commeneted out, use dbhndlr instance instead
// inserting new label into database
// making input filed text to blank
inputLabel.setText("");
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
// loading spinner with newly added data
spinner1csr = dbhndlr.getAllLabelsAsCursor();
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca.swapCursor(spinner1csr);
sca2.swapCursor(spinner2csr);
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
Database .
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_3,message3);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}