I am using this code , but i ma getting a Runtime exception. I did all the required effort and work to remove this error. But it not work for me . i am using DatabaseHandler. java and AndroidSpinnerFromSQLiteActivity.java class, and my xml is activity_databse_handler.xml.
public class AndroidSpinnerFromSQLiteActivity extends Activity implements OnItemSelectedListener {
// Spinner element
Spinner spinner;
// Add button
utton btnAdd;
// Input text
EditText inputLabel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_handler);
// Spinner element
spinner = (Spinner) findViewById(R.id.spinner);
// add button
btnAdd = (Button) findViewById(R.id.btn_add);
// new label input field
inputLabel = (EditText) findViewById(R.id.input_label);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
/**
* Add new label button click listener
* */
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// inserting new label into database
db.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();
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Function to load the spinner data from SQLite database
* */
public void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
===========================================================================================
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
try {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
catch (Exception e) {
// TODO: handle exception
}
}
// 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
* */
// Database Version
private static int DATABASE_VERSION = 1;
// Database Name
private static String DATABASE_NAME = "spinnerExample";
// Labels table name
private static String TABLE_LABELS = "labels";
// Labels Table Columns names
private static String KEY_ID = "id";
private static String KEY_NAME = "name";
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(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}
===========================================================================================
<!-- Label -->
<!-- Input Text -->
<!-- Add Button -->
<!-- Select Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select Label"
android:padding="8dip" />
<!-- Spinner Dropdown -->
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title"
android:layout_marginTop="20dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
/>
</LinearLayout>
You don't want the application context for the db, you want the activity context, so your call should be:
DatabaseHandler db = new DatabaseHandler(this);
Related
**Good day everyone ...
I badly need your help.
Can I ask on why my listview doesnt display and also my alert dialog?
here is my code
I've already inserted table values in the sqlite database and Im confused on why nothing displays on my listview and dialog.
the listview uses an adapter that i queried in the DBHelper
MainActivity
public class MainActivity extends AppCompatActivity {
private QuestionaireDB commandQuery;
private ListView showQuestion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commandQuery = new QuestionaireDB(this);
ShowTables();
ArrayList getQuestion = commandQuery.getAllQuestions();
ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,getQuestion);
showQuestion = (ListView)findViewById(R.id.viewAll);
showQuestion.setAdapter(arrayAdapter);
}
private void ShowTables(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("You have "+commandQuery.numberOfRows()+"");
alertDialogBuilder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
}
}
QuestionaireDB
public class QuestionaireDB extends SQLiteOpenHelper{
//tblQuestion
public static final String DATABASE_NAME = "QuestionaireDB.db";
public static final String DATABASE_TABLE_tblQuestion = "tblQuestion";
public static final String DATABASE_TABLE_tblChoices = "tblChoices";
public static final String DATABASE_TABLE_tblAnswers = "tblAnswers";
public static final String DATABASE_TABLE_tblCategory = "tblCategory";
public QuestionaireDB(Context context) {
super(context, DATABASE_NAME , null, 3);
}
#Override
public void onCreate(SQLiteDatabase db) {
//tblQuestion
String CreatetblQueston="CREATE TABLE "+DATABASE_TABLE_tblQuestion +
"(questionID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,categoryID INTEGER,
questionName TEXT)";
//tblChoices
String CreatetblChoices="CREATE TABLE "+DATABASE_TABLE_tblChoices +
"(questionID INTEGER NOT NULL, ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
questionChoices TEXT)";
//tblAnswers
String CreatetblAnswers="CREATE TABLE "+DATABASE_TABLE_tblAnswers+
"(questionID INTEGER NOT NULL, questionCorrectAnswer TEXT, ID INTEGER PRIMARY KEY
AUTOINCREMENT NOT NULL)";
//tblCategory
String CreateCategory="CREATE TABLE "+DATABASE_TABLE_tblCategory+
" (categoryID INTEGER NOT NULL,categoryName TEXT, PRIMARY KEY (categoryID ASC))";
db.execSQL(CreatetblQueston);
db.execSQL(CreatetblChoices);
db.execSQL(CreatetblAnswers);
db.execSQL(CreateCategory);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String confirmationQuestion="DROP TABLE IF EXISTS "+DATABASE_TABLE_tblQuestion ;
String confirmationChoices="DROP TABLE IF EXISTS "+DATABASE_TABLE_tblChoices ;
String confirmationAnswers="DROP TABLE IF EXISTS "+DATABASE_TABLE_tblAnswers ;
String confirmationCategory="DROP TABLE IF EXISTS "+DATABASE_TABLE_tblCategory ;
db.execSQL(confirmationQuestion);
db.execSQL(confirmationChoices);
db.execSQL(confirmationAnswers);
db.execSQL(confirmationCategory);
}
public ArrayList<String> getAllQuestions() {
ArrayList<String> array_list = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from tblQuestion", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex("questionName")));
res.moveToNext();
}
return array_list;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, DATABASE_TABLE_tblQuestion);
return numRows;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/viewAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
`
First of all you need to call show() method of dialog like written below,
alertDialogBuilder.show(); //add this line in your ShowTables()
Replace line
ArrayList getQuestion=commandQuery.getAllQuestions();
with
ArrayList<String> getQuestion=commandQuery.getAllQuestions();
And check whether you are getting atleast one data from your database(check list size)
I have a listview that contains some data which I got from the web. Now I can make changes in the list item and once I make changes to the item, I am storing the updated value in the db. When i login in next time to the app, I am downloading the content from net and showing it in the listview with the changes that I have done last time. So my approach here is, I am querying the db for each item in the getview method of the list adapter to check for changes. Is it a good practice to do a db query for each item's getview method of the adapter? If not could you please suggest me some alternative. Thanks.
Never, really, never do that.
If you put your data download code in the getView method of the adapter it will make a network call for each row of the list.
Even worst, it will call it anytime that row appears on the screen, not only one time for row.
You should get all your data first, then use the adapter only to draw it.
You can at anytime call the db to check for changes and, if needed, notify the adapter to redraw the list to show the changes.
Hope this helps.
In Android development, any time you want to show a vertical list of items you will want to use a ListView which is populated using an Adapter to a data source. When we want the data for the list to be sourced directly from a SQLite database query we can use a CursorAdapter.
The CursorAdapter fits in between a Cursor (data source from SQLite query) and the ListView (visual representation) and configures two aspects:
Which layout template to inflate for an item
Which fields of the cursor to bind to views in the template
Creating the View Template
When we want to display a series of items into a list using a custom representation of the items, we need to use our own custom XML layout template for each item. We can simply create an XML layout template in res/layout/item_todo.xml representing a particular cursor row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Defining the Adapter
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return favoriteList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem,null);
}
final TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
nameText.setText("Name : "+favoriteList.get(position).getName());
final TextView ageText = (TextView) convertView.findViewById(R.id.ageText);
ageText.setText("Age : "+favoriteList.get(position).getAge());
final Button edit = (Button) convertView.findViewById(R.id.edit);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.row);
dialog.setTitle("Add Data to Database");
final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText age = (EditText) dialog.findViewById(R.id.age);
Button Add = (Button) dialog.findViewById(R.id.Add);
Add.setText("Add");
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(name.getText().toString() != null && name.getText().toString().length() >0 ){
if(age.getText().toString() != null && age.getText().toString().length() >0 ){
db.updateRow(favoriteList.get(position).getId(), name.getText().toString(), age.getText().toString());
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
dialog.dismiss();
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Age", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Name", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
});
final Button delete = (Button) convertView.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.removeFav(favoriteList.get(position).getId());
notifyDataSetChanged();
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
});
return convertView;
}
}
Create database
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "Test";
//Table Name
private static final String TABLE_TEST = "TestTable";
//Column Name
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Create Table
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_AGE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}
//Insert Value
public void adddata(Context context,String movieId,String songId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, movieId);
values.put(KEY_AGE, songId);
db.insert(TABLE_TEST, null, values);
db.close();
}
//Get Row Count
public int getCount() {
String countQuery = "SELECT * FROM " + TABLE_TEST;
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}
//Delete Query
public void removeFav(int id) {
String countQuery = "DELETE FROM " + TABLE_TEST + " where " + KEY_ID + "= " + id ;
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(countQuery);
}
//Get FavList
public List<FavoriteList> getFavList(){
String selectQuery = "SELECT * FROM " + TABLE_TEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
List<FavoriteList> FavList = new ArrayList<FavoriteList>();
if (cursor.moveToFirst()) {
do {
FavoriteList list = new FavoriteList();
list.setId(Integer.parseInt(cursor.getString(0)));
list.setName(cursor.getString(1));
list.setAge(cursor.getString(2));
FavList.add(list);
} while (cursor.moveToNext());
}
return FavList;
}
}
Enojoys.... :)
It is better to use cursor adapter to bind the list view.You can use Loader to get the list updated even if there is a change in the data base.
onLoadFinished (Loader loader, D data) of the Loader call back would be monitor for changes to the data, and report them to you through new calls. You should not monitor the data yourself.
I have one dropdown when i click dropdown option then it will hit database and retrieve the data to my another dropdown list. For ex i have one drop down list with class names as options when i click on class name it will retrieve that class students names into another dropdown list from database. after send those details to the database when click on submit button?
i used to implement code based on this example for populating spinner based in another spinner selection
http://www.javaknowledge.info/populate-second-spinner-based-on-selection-of-first-spinner/
and for populating spinner from sqlite database i used this sample...please check this link
http://instinctcoder.com/android-studio-spinner-populate-data-sqlite/
my problem is resolved
//DATABASE HANdler.java
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 + " INTEGER PRIMARY KEY," + 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(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}
//In your Main Acticity ,my one is AndroidSpinnerFromSQLiteActivity
public class AndroidSpinnerFromSQLiteActivity extends Activity implements
OnItemSelectedListener {
// Spinner element
Spinner spinner;
// Add button
Button btnAdd;
// Input text
EditText inputLabel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
spinner = (Spinner) findViewById(R.id.spinner);
// add button
btnAdd = (Button) findViewById(R.id.btn_add);
// new label input field
inputLabel = (EditText) findViewById(R.id.input_label);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
/**
* Add new label button click listener
* */
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
// inserting new label into database
db.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();
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
What i am trying to do :: I am trying to populate Spinner from the data obtained through cursor from sqlite database
What i have done:: I am able to fetch the data from the sqlite and store it in ArrayList<HashMap<String,String>>
Question:: How can i load the data from this collection to my spinner
Code::
Spinner CitySpinner;
private HashMap<String, String> objHashCityName;
private ArrayList<HashMap<String, String>> objListCityName=null;
private void setDataForCity() {
DatabaseHandler mHelper;
SQLiteDatabase db = null;
Cursor mCursor = null;
try {
mHelper = new DatabaseHandler(getActivity());
db = mHelper.getReadableDatabase();
mCursor = db.rawQuery("select city_name from "
+ city_mas.TABLE_NAME_CITY_MAS, null);
if(mCursor.moveToFirst()){
do{
objHashCityName = new HashMap<String, String>();
objHashCityName.put("city_name", mCursor.getString(0));
//objHashBufType to array list (One row i each iteration)
objListCityName.add(objHashCityName);
}while(mCursor.moveToNext());
Log.d("", "");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(db!=null){
if(db.isOpen()) db.close();
}
if(mCursor!=null){
if(!mCursor.isClosed())mCursor.close();
}
}
Image source:Androidhive
public class AndroidSpinnerFromSQLiteActivity extends Activity implements
OnItemSelectedListener {
// Spinner element
Spinner spinner;
// Add button
Button btnAdd;
// Input text
EditText inputLabel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
spinner = (Spinner) findViewById(R.id.spinner);
// add button
btnAdd = (Button) findViewById(R.id.btn_add);
// new label input field
inputLabel = (EditText) findViewById(R.id.input_label);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
/**
* Add new label button click listener
* */
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
// inserting new label into database
db.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();
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Full tutorial is Available from androidhive
This is how i resolved this ::
private void setDataForCity() {
DatabaseHandler mHelper;
SQLiteDatabase db = null;
Cursor mCursor = null;
List<String> objCitySpinner;
try {
objCitySpinner=new ArrayList<String>();
mHelper = new DatabaseHandler(getActivity());
db = mHelper.getReadableDatabase();
mCursor = db.rawQuery("select city_name from "
+ city_mas.TABLE_NAME_CITY_MAS, null);
//First city in the spinner must always should be current city
objCitySpinner.add(AppController.currentCity);
if(mCursor.moveToFirst()){
do{
objCitySpinner.add(mCursor.getString(0));
//objHashBufType to list (One row i each iteration)
}while(mCursor.moveToNext());
Log.d("", "");
}
//I am using ArrayAdapter to populate the data to the spinner
ArrayAdapter<String> spinCityAdapt = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item, objCitySpinner);
CitySpinner.setAdapter(spinCityAdapt);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(db!=null){
if(db.isOpen()) db.close();
}
if(mCursor!=null){
if(!mCursor.isClosed())mCursor.close();
}
}
}
I am trying to display the primary key of the item I selected in Spinner.I want to display the primary key in TextView.How will I do this?I already know how to display a field in a table in database.
In my DatabseHandler.java
This is how I insert data in my table criteria
public long insertLabelCriteria(String label, String label2, String label3){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CRI_NAME, label);
values.put(KEY_CRI_PER, label2);
values.put(KEY_CRI_EVPK, label3);
// Inserting Row
long id = db.insert(TABLE_CRITERIA, null, values);
db.close(); // Closing database connection
return id;
}
This is my method in getting labels and returning list of labels
public List<Criteria> getAllLabels( String evpk ){
List<Criteria> labels = new ArrayList<Criteria>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_CRITERIA + " WHERE "
+ KEY_CRI_EVPK + " = " + evpk ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(new Criteria(cursor.getString(1)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
In my MainActivity
I have a method loadSpinnerData and I use this evrytime I add a criteria, it will load the Spinner to view the item I added in database
private void loadSpinnerData() {
// TODO Auto-generated method stub
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<Criteria> lables = db.getAllLabels(evpk.getText().toString());
// Creating adapter for spinner
ArrayAdapter<Criteria> dataAdapter = new ArrayAdapter<Criteria> (this,
android.R.layout.simple_spinner_dropdown_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
criteria_spin.setAdapter(dataAdapter);
criteria_spin.setOnItemSelectedListener(this);
}
Now, on selecting item, how can I display the primary key of the selected item in spinner?
This codes below are just to show and select the item click.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
I also try to add this code ,but the id display is arraylist number, not the primary key
long rowId = id;
String criteriapk = String.valueOf(label);
cripk.setText(criteriapk);
I find it hard, in finding solution with this.What will I do?Help me plss
I also try this method, but the value is cursor.in the TextView, it does not display number.
public Cursor find_id_of_criteria(String label){
SQLiteDatabase db=this.getWritableDatabase();
String selectQuery = "SELECT criteria_id FROM Criteria WHERE criteria_name = "+"'" + label +"'";
Cursor id = db.rawQuery(selectQuery, null);
db.close();
return id;
}
and in loadSpinnerdata I put this
//display id of criteria
Cursor id2 = db.find_id_of_criteria(label);
String cri =(String.valueOf(id2).toString());
cripk.setText(cri);
You have to implement an own adapter extending BaseAdapter or CursorAdapter class and use it instead of ArrayAdapter.
Here is an example using CursorAdapter. I haven't tested it as it is meant to be a start for your own implementation. Of course you can use other layouts as well, with some minor changes to this code.
public class CriteriaCursorAdapter extends CursorAdapter {
private class Holder {
TextView text;
}
private LayoutInflater mInflater;
public CriteriaCursorAdapter(Context context, Cursor c) {
super(context, c);
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(
android.R.layout.simple_spinner_dropdown_item, parent, false);
}
Holder holder = (Holder)convertView.getTag();
if (holder == null) {
holder = new Holder();
holder.text = (TextView)convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
}
Cursor c = (Cursor)getItem(position);
holder.text.setText(c.getString(1));
return convertView;
}
}
Important: If you use CursorAdapter your cursor has to have a column named '_id'. You can achieve this by modifying your SELECT-statement, if your TABLE doesn't contain this column!
SELECT columnPK _id, col1, .... FROM ...
To get the primary-key (column '_id' of cursor) you can use long getItemId(int position); of your CriteriaCursorAdapter.
You will find many examples for extending BaseAdapter or CursorAdapter. One Example
Simple.. You are almost near to answer. Change your getAllLabels as following way.
public List<Criteria> getAllLabels( String evpk ){
List<Criteria> labels = new ArrayList<Criteria>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_CRITERIA + " WHERE "
+ KEY_CRI_EVPK + " = " + evpk ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Criteria ct = new Criteria();
ct.setLabel(cursor.getString(1));
ct.setKey(Integer.parseInt(c.getString(0)));
labels.add(ct);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
Here I changed the do while loop only. In this way create getters and setters for label and key. To get the primary key use the selected Criteria object like ct.getKey; I hope this will help you.
UPDATE
List<String> field_key; //accessible in whole class.
private void loadSpinnerData() {
// TODO Auto-generated method stub
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<Criteria> lables = db.getAllLabels(evpk.getText().toString());
List<String> field_lables = new ArrayList<String>();
field_key = new ArrayList<String>();
// Creating adapter for spinner
for (Criteria ct : lables) {
field_lables.add(ct.getLabel);
field_key.add(ct.getkey);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_dropdown_item, field_lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
criteria_spin.setAdapter(dataAdapter);
criteria_spin.setOnItemSelectedListener(this);
}
&
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
String key = field_key.get(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label+" Your key: " + key,
Toast.LENGTH_LONG).show();
}
Try this way and let me know what happens