How to load data to spinner with id and name - android

I have a table Facilities with field FacilityID and field FacilityName. I have a spinner load data to SQLite.
private void loadSpinnerDataHama() {
// database handler
DatabaseSpinner db = new DatabaseSpinner(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
spin2.setAdapter(dataAdapter);
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + Facibilities;
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;
}
I have a Company form for users enter the information of company such as: Company ID, Company Name, Address, Phone, Facility,...and a 'Create' button. In Facility field I use spinner to display FacilityName, when users click on Create button, I want save FacilityID into the table Company

try like this
1) Declare a public String variable 'id' to store selected id;
2) save the ids in a seperate arraylist.
3) Inside the spinner.OnitemSelectedListener->
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
id=ids.get(position);
}
});
3) inside create button onclick method pass the variable named id.

To manage such a data set, what you can do is:
Declare a Faculty class with faculty ID and faculty name.
Query the database and prepare an Arraylist with all the faculty objects, like ArrayList<Faculty>.
You can get the particular faculty data with the index/position of the selected item.

You have to create new Class such as Data with two feild like id and label also the getter and setter for it.
class Data {
private String id;
private String label;
//create getter and setter for above properties.
}
Then do some changes in getAllLabels method such as:
public List<Data> getAllLabels(){
List<Data> lstData = new ArrayList<Data>();
// Select All Query
String selectQuery = "SELECT * FROM " + Facibilities;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
Data data = new Data();
do {
data .setId(add(cursor.getString(1)))
data .setLabel(add(cursor.getString(2)));
lstData.add(data);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning data object with id and labels
return lstData;}
then create one list of String labels and id from returned list:
List <String> labels= new ArrayList<String>();
List <String> ids= new ArrayList<String>();
foreach(data in lstData){
ids.add(data.getId());
labels.add(data.getLabel());
}
and then pass the lables list to the adapter and onSelect of adapter item you will get the id from it from its position:
spin2.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected( AdapterView<?> parent, View view, int pos, long id){
// you will get your id here of selected item and then you can use it //wherever you want
String singleId= id.get(position);
}
public void onNothingSelected( AdapterView<?> parent){
Log.d(TAG,"Nothing selected ");
selectedCurrency=-1;
}
}
);

Related

Loading two SQL columns into a listview but only need to display the first column Android

I am using an sqllite database to store two columns which are phonename and phonenumber. I am using an arrayList to iterate through the data and display the phonename in a listview which is working, but I also need to iterate through the phonenumber column under the same listview as well. I only need the phonename to be showing in the listview.
This is for when the user has selected the item in the listview, it shows the selected phonename and phonenumber, which at the moment it is only currently showing the phonename and showing blank for phonenumber for obvious reasons.
DataDBAdapter
public long insert(String phonename, String phonenumber)
{
ContentValues cv = new ContentValues();
cv.put(COl_MYTABLE_PHONENAME,phonename);
cv.put(COL_MYTABLE_PHONENUMBER,phonenumber);
return mDB.insert(TBL_MYTABLE,null,cv);
}
//---------------------------------------------------------------------------
// Iterating through the database
//---------------------------------------------------------------------------
public ArrayList<String> getAllRowsAsList()
{
Cursor csr = mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
ArrayList<String> rv = new ArrayList<>();
while (csr.moveToNext())
{
rv.add(csr.getString(csr.getColumnIndex(COl_MYTABLE_PHONENAME)));
}
return rv;
}
SelectModemFragment
private void manageListView(Context context)
{
thelist = dbHelper.getAllRowsAsList(); // Extract the list, just the phone names
// Only setup the adapter and the ListView if the adapter hasn't been setup
if(arrayAdapter == null)
{
// Instantiate the adapter
arrayAdapter = new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,thelist); //<<<<<<<<<< list included
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
namedisplay = arrayAdapter.getItem(position);
Toast.makeText(view.getContext(), namedisplay + " Selected for Communication", Toast.LENGTH_SHORT).show();
Toast.makeText(view.getContext(), phoneNo, Toast.LENGTH_SHORT).show();
}
});
}
Issue
using ArrayAdapter only allows a a single item to be passed, thus unless you resort to complicated/messy/inefficient methods ArrayAdapter is only really suitable for a single value.
Fix
You could use an ArrayList where your_object has members for all the required values. i.e phonenumber and phonename. Noting that unless you use a Custom Adapter that you should override the the toString method to extract the data that you want to be displayed, as that is what a standard ArrayAdapter uses.
Alternative (use a CursorAdapter)
An alternative would be to use a Cursor Adapter (e.g. SimpleCursorAdapter), you can then return the Cursor and use it directly. However, a CursorAdapter REQUIRES a column specifically name _id (BaseColumns._ID can be used).
One of the clear advantages of a Cursor adapter is the the 4th paremmter passed to the onItemClick/onItemLongClick is the id of the row (if used correctly) allowing a single value to then get/update/delete/pass the respective selected row.
As such I'd recommend a Cursor Adapter for a ListView and hence the more comprehensive answer.
You may think I don;t have such a column. However, you can use the normally hidden rowid column and dynamically create a column named _id.
You could have a method, in the database helper (DataDBAdapter) such as :-
public Cursor getAllRowsAsCursor()
{
String[] columns = new String[]{"rowid AS " + BaseColumns._ID,"*"}
return = mDB.query(TBL_MYTABLE,null,null,null,null,null,null)
}
The ManageList method could then be :-
private void manageListView(Context context) {
myCursor = dbhelper.getAllRowsAsCursor();
// Only setup the adapter and the ListView if the adapter hasn't been setup
if(arrayAdapter == null)
{
// Instantiate the adapter
arrayAdapter = new SimpleCursorAdapter(context,android.R.layout.simple_list_item_1,myCursor,new String[]{DataAdapter.COl_MYTABLE_PHONENAME},newint[]{android.R.id.text1},0);
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
String phonenumber = myCursor,getString(myCursor.getColumnIndex(DataAdapter.COL_MYTABLE_PHONENUMBER);
Toast.makeText(view.getContext(), namedisplay + " Selected for Communication", Toast.LENGTH_SHORT).show();
Toast.makeText(view.getContext(), phonenumber, Toast.LENGTH_SHORT).show();
}
});
} else {
arrayAdapter.swapCursor(myCursor);
}
Notes
MyCursor would be declared as a class variable e.g. Cursor MyCursor;
Instaed of
ArrayAdapter<String> arrayAdapter; you would have
SimpleCursorAdapter arrayAdapter;
The above is in-principle code and has not been tested, so there may be errors and/or omissions.
Working Example
The following is the code based upon the code from the previous question asked (which this appears to follow on from). It has two ListViews the old and a new one that uses a SimpleCursorAdapter. Clicking an item display phone number and also id. Lon Clicking an Item deletes that item (refreshing both ListViews).
DataDBAdapter.java has two new methods (so add these) :-
//<<<<<<<<<< ADDED
public Cursor getAllRowsAsCursor() {
return mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
}
public int delete(long id) {
String whereclause = COL_MYTABLE_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
return mDB.delete(TBL_MYTABLE,whereclause,whereargs);
}
SelectModemFragment.java is now :-
public class SelectModemFragment extends Fragment {
private SelectModemViewModel mViewModel;
ListView display_contacts1;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> thelist;
DataDBAdapter dbhelper;
//<<<<<<<<<< ADDED
ListView display_contacts2;
SimpleCursorAdapter sca;
Cursor MyCursor;
public static SelectModemFragment newInstance() {
return new SelectModemFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.select_modem_fragment, container, false);
display_contacts1 = view.findViewById(R.id.lv001); //<<<<<<<<<< top listview ArrayAdapter<String>
display_contacts2 = view.findViewById(R.id.lv002);
dbhelper = new DataDBAdapter(view.getContext());
AddSomeData();
manageListView(view.getContext());
manageListView2();
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(SelectModemViewModel.class);
// TODO: Use the ViewModel
}
//Sets up the ListView if not already setup
private void manageListView(Context context) {
thelist = dbhelper.getAllRowsAsList(); //<<<<<<<<<< extract the list (just the phone names) from the database
// Only setup the adapter and the ListView if the adapter hasn't been setup
if (arrayAdapter == null) {
// Instantiate the adapter
arrayAdapter = new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,thelist); //<<<<<<<<<< list included
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
Toast.makeText(view.getContext(),"You clicked the phone named " + name,Toast.LENGTH_SHORT).show();
}
});
} else {
//<<<<<<<<<< MODIFIED to cope with changes (needs to rebuild the array within the adpater)
arrayAdapter.clear();
for (String s: thelist) {
arrayAdapter.add(s);
}
arrayAdapter.notifyDataSetChanged();
}
}
//<<<<<<<<<< ADDED FOR CursorAdapter
private void manageListView2() {
MyCursor = dbhelper.getAllRowsAsCursor();
if (sca == null) {
sca = new SimpleCursorAdapter(
getContext(),
android.R.layout.simple_list_item_1,
MyCursor,
new String[]{DataDBAdapter.COl_MYTABLE_PHONENAME},
new int[]{android.R.id.text1},
0
);
display_contacts2.setAdapter(sca);
display_contacts2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(view.getContext(),
"You Clicked the phone name " +
MyCursor.getString(MyCursor.getColumnIndex(DataDBAdapter.COl_MYTABLE_PHONENAME)) +
". The phonenumber is " +
MyCursor.getString(MyCursor.getColumnIndex(DataDBAdapter.COL_MYTABLE_PHONENUMBER)) +
". The ID (as passed) is " + String.valueOf(id) +
". The ID (from Cursor) is " + String.valueOf(MyCursor.getLong(MyCursor.getColumnIndex(DataDBAdapter.COL_MYTABLE_ID)))
,
Toast.LENGTH_SHORT).show();
}
});
//<<<<<<<<<< EXTRA delete row on long click
display_contacts2.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
dbhelper.delete(id);
manageListView2();
manageListView(getContext());
return true;
}
});
} else {
sca.swapCursor(MyCursor);
}
}
// Add some testing data (only if none already exists)
private void AddSomeData() {
if (DatabaseUtils.queryNumEntries(dbhelper.getWritableDatabase(),DataDBAdapter.TBL_MYTABLE) < 1) {
dbhelper.insert("Phone 1", "0000000000");
dbhelper.insert("Phone 2", "1111111111");
}
}
#Override
public void onResume() {
super.onResume();
manageListView2();
manageListView(getContext());
}
#Override
public void onDetach() {
super.onDetach();
MyCursor.close();
}
}

Get ID from database onClick ListView

I'm using SQLite in my app. I have a listView which is populated with values from the database.
When I click on an item from the listview, I go to another page, and I would like ( with an intent), to transfer the ID FROM THE DATABASE. The problem is that I'm only transfering the ID from the position of my listView, which is wrong. For example, let's say I have :
ID Name
1 David
2 Joseph
My listView will display both names. But if I delete David, the ID i'm getting when i click in Joseph is 1 and not 2 . And that's the problem !
So : I want to retrieve the ID from my database and not from my listView when I click on an item
Here's my method in my helper : UPDATED !
public Cursor getAllCours()
{
String Query = ("select ID as _id, nom from " + TABLE_COURS);
Open();
Cursor cursor = db.rawQuery(Query, null);
return cursor;
}
And how I display it in my Activity :
Cursor cursor = dbhelper.getAllCours();
String[] from = { "nom" }; int[] to = { android.R.id.text1 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to, 0);
lv.setAdapter(adapter);
And finally, my listviewClickListener :
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//I THINK THE ERROR IS HERE !
long itemid= lv.getItemIdAtPosition(i);
int id= (int)itemid;
String a =lv.getItemAtPosition(i).toString();
Intent b = new Intent(AffichageCours.this,AffichageNotes.class);
Bundle args = new Bundle();
args.putString("nom_cours",a);
args.putInt("id",id);
b.putExtras(args);
startActivity(b);
}
});
}
My TABLE_COURS columns:
private static final String TABLE_COURS = "cours";
private static final String COLONNE_IDCOURS = "ID";
private static final String COLONNE_COURS = "nom";
private static final String CREATE_COURS ="CREATE TABLE cours " +
"("+COLONNE_IDCOURS+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLONNE_COURS+" TEXT NOT NULL)";
How i delete with my Context Menu :
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId())
{
case R.id.supprimer:
dbhelper.deleteCours(lv.getItemAtPosition(info.position).toString());
adapter.remove(adapter.getItem(info.position)); //the error is here..
adapter.notifyDataSetChanged();
return true;
Thank you guys !
I think the problem is that you are asking for the Id of the row in the ListView not the actual data that row is holding up. In the onItemClick method change this:
long itemid= lv.getItemIdAtPosition(i);
For this:
String courId = adapter.getItem(i);
The key here is to try to get the data from the ArrayAdapter not directly from the ListView.
You should have use Java Objects so it will be easy for you.
Suppost you have stored Contacts in dataBase(contains fields: Name, Mobile and Address). So create a POJO for that:
class Contacts{
private String name;
private String mobile;
private String address;
//write getters and setters
}
Then, whenever you are accessing database fetch all contacts you want to show and store in ArrayList<Contacts> mContactList;
And then pass this list in your ListView's adapter to show data in listView.
CustomAdapter adapter = new CustomAdapter(context, layoutResource, mContactList);
Then you can retrieve the object on clicking a particular list item on the basis of position;
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Contacts contact = mContactList.get(i);
// now you can do whatever you want;
}
});
Since you are not using a custom adapter, why dont you try this inside onItemClickListener
String idThatYouWant = listeCours.get(i).getId();

How to get list of data from database to spinner

I want to get all username from my user table to be displayed in my spinner for selection but instead of displaying all username from my list it displays only one which is the first user from my database.. how can i get all username?
String q = "SELECT * FROM " + User.TABLE;
Cursor cursor = dbHelper.getReadableDatabase().rawQuery(q, null);
String[] ComRep = new String[0];
if (cursor.moveToFirst()) {
String rep = cursor.getString(cursor.getColumnIndex(User.KEY_username));
do {
ComRep = new String[]{rep};
} while (cursor.moveToNext());
}
cursor.close();
Comrep = (Spinner) findViewById(R.id.spincomrep);
ArrayAdapter<CharSequence> adapterrep = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, ComRep);
adapterrep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Comrep.setAdapter(adapterrep);
Comrep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Comrep.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
thanks in advance..
You're not actually accumulating any values in your array. You're making a new array each time you go through the loop.
ArrayList<String> values = new ArrayList<String>();
while (cursor.moveToNext()) {
String rep = cursor.getString(cursor.getColumnIndex(User.KEY_username));
values.add(rep);
}
cursor.close();
ArrayAdapter<CharSequence> adapterrep = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, values.toArray(new String[values.size]));
You should look at CursorAdapter. You could make an adapter directly from your cursor so you don't need to code the loop.

Display primary key in the SQlite database when selecting item in Spinner

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

Spinner with sqlite database in Android

I have one spinner, one button and a ListView.
I want to choose item from spinner and after clicking button the match of spinner and database content must be show in the ListView. The database values are of string data type.
Please anybody can guide me how I can do it?
For spinner,first create an adapter like:
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.months, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// Here R.array.months are string array created at string.xml file and then open ur database:
if(mydb_expenditure!=null)
{
mydb_expenditure.close();
}
mydb_expenditure=this.openOrCreateDatabase("Database_name", MODE_PRIVATE, null);
if(mydb_expenditure!=null)
{
Cursor cursor = mydb_expenditure.rawQuery("select column name from "+TableName , null);
cursor.moveToFirst();
int column=cursor.getColumnIndex("column name");
if(cursor!=null)
{
do
{
column=cursor.getInt(column);
adapter12.add(column);
}while(.moveToNext());
}
spinner.setAdapter(adapter12);
}
This will add ur ur database column value into the spinner
For example:
setContentView(R.layout.main);
ListView lv=(ListView)findViewById(R.id.listview);
Button b=(Button)findViewById(R.id.button);
Spinner sp=(Spinner)findViewById(R.id.spinner);
final ArrayList<String> options=new ArrayList<String>();
Cursor cursor=dbHelper.getOptions();//method to get all options to be displayed in spinner,coming from your database
if(cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i=0;i<cursor.getCount();i++)
{
options.add(cursor.getString(cursor.getColumnIndex("field_name")));
cursor.moveToNext();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item,options);
sp.setAdapter(adapter);
}
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Cursor c=db_helper.getRelatedItems(spinner.getSelectedItem().toString()); //get related data from database according to the item selected in spinner
if(c.getCount()>0)
{
CustomAdapter ca=new CustomAdapter(context,R.layout.listitem_layout,cursor,new String[]{"field 1","field 2"},new int[]{R.id.textview1,R.id.textview2});
//here you would have to pass your custom layout file containing textviews or other component to display your data using CustomAdapter.class which you had prepared
listview.setAdapter(ca);
ca.notifyDataSetChanged();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//catch onClick on items of listview here
}
});
}
}
});
you can follow this steps assuming spinner is populated with string array:
i) In setOnItemSelectedListener event get position of selected position by
int pos=urspinner.getSelectedItemPosition() and get string by
strsel=arrstr[pos];
ii) on button click listener use strsel to populate listadapter by querying database
DONE!!!!

Categories

Resources