In my application I have a spinner that displays a number of spending periods (weekly, bi-weekly, monthly, etc) and I filled it using a SimpleCursorAdapter because those periods are kept in the database. Here is how I implemented it:
Cursor spendingPeriodCursor = dataSource.getSpendingPeriods();
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, spendingPeriodCursor, fromColumns, toColumns);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpendingSpinner.setAdapter(mAdapter);
The spinner populates, and at the end of the activity I try to get the selected item like this:
// Get spending period description:
String spendingDesc = mSpendingSpinner.getSelectedItem().toString();
But it doesn't return the actual string value. It looks like a get a string representation of part of the cursor:
android.database.sqlite.SQLiteCursor#410dfae8
What do I have to do to get the actual text of the selected item?
Cursor cursor = (Cursor) mSpendingSpinner.getSelectedItem();
String text = cursor.getString(cursor.getColumnIndex("my_column_name"));
1) Well, with will be enough with:
String spendingDesc = mSpendingSpinner.getSelectedItem().toString();
2) but you can try too:
mSpendingSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View arg1,
int pos, long arg3) {
String spendingDesc= parent.getSelectedItem().toString();
}
}
3) or
Cursor cursor = (Cursor) mSpendingSpinner.getSelectedItem();
String text = cursor.getString(cursor.getColumnIndex("COLUN_NAME"));
Related
So I have been looking around for about 4 hours now and maybe I just don't know how to word my search, but I am not finding out what I need.
I am using a custom adapter to setup my listview from items I have stored into an sqlite database. My cursor sends id, name, product_id, data, datetime to my adapter. But my adapter is set to only display the name, data & datetime.
I need to be able to click on the name, but have it go to my next activity and display the information from the product_id that was sent to the adapter. Example I click on Apples, but it would actually be product_id 505 in my database. Unless I set the product_id to a textview, when I click on my item, it does not bring up the correct listing and searches for Apples.
If this is not clear, please let me know and I will to explain it better.
** EDIT **
So my database is like this
_ID | PRODUCT_NAME | PRODUCT_ID | PRODUCT_DATA | DATE
1 Apples 505 Fresh Apples 123456
2 Oranges 506 Fresh Orange 123456
3 Kiwi 507 Fresh kiwi 123456
4 Nuts 508 Fresh Nuts 123456
My ListView shows this:
Apples- FRESH APPLES - DATE
Oranges - FRESH ORANGE - DATE
Kiwi- FRESH KIWI - DATE
Nuts - FRESH NUTS - DATE
When I click on Apples, I want it to return PRODUCT_ID to me, not _ID, so I can pass that product_id onto my next intent.
My Display listing
public void displayListView()
{
DatabaseOperations db = new DatabaseOperations(this);
Cursor cursor = db.getProducts();
dataAdapter = new MainActivityAdapter(
this,
cursor,
0);
ListView listView = (ListView) findViewById(R.id.product_list);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
// listening to single list item on click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long ID)
{
TextView listText = (TextView) view.findViewById(R.id.name);
String product_name = listText.getText().toString();
Intent i = new Intent(MainActivity.this, product_detail.class);
i.putExtra("productName", product_name);
MainActivity.this.startActivity(i);
}
});
db.close();
}
My Adapter
public class MainActivityAdapter extends CursorAdapter
{
private LayoutInflater cursorInflater;
private Context c;
// Default constructor
public MainActivityAdapter(Context context, Cursor cursor, int flags)
{
super(context, cursor, flags);
cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
c = context;
// Log.i("Custom-Adapter", "Starting up");
}
public void bindView(View view, Context context, Cursor list)
{
TextView PN = (TextView) view.findViewById(R.id.product_name);
TextView PI = (TextView) view.findViewById(R.id.product_data);
TextView date = (TextView) view.findViewById(R.id.date);
// SET OUR DATA FROM OUR CURSOR
String pn = list.getString( list.getColumnIndex("pn"));
String pi = list.getString( list.getColumnIndex("pi"));;
// NEED TO RECONVERT DATE THEN SHOW IT
Long millidate = list.getLong(list.getColumnIndex("dateTime"));
Date myDateNew = new Date(millidate);
String Sdate = getDate(millidate);
PN.setText(pn);
PI.setText(pi);
date.setText(Sdate);
}
public static String getDate(long milliSeconds)
{
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(milliSeconds); //here your time in miliseconds
String date = "" + cl.get(Calendar.DAY_OF_MONTH) + ":" + cl.get(Calendar.MONTH) + ":" + cl.get(Calendar.YEAR);
String time = "" + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND);
return date;
}
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
//Log.i("Custom-Adapter", "newView Started");
// R.layout.list_row is your xml layout for each row
return cursorInflater.inflate(R.layout.activity_list, parent, false);
}
I want to get the product_id when I click on the name Apples.
We can achieve it in multiple ways but most common ways are :
Option 1:
Use setTag method for saving id of product with name in TextView :
PN.setText(pn);
PN.setTag((list.getInt(list.getColumnIndex("product_id"))).toString());
Now use getTag method to get clicked product product_id in onItemClick :
String product_name = listText.getText().toString();
int product_id = Integer.parseInt(listText.getTag().toString());
Option 2:
Instead of getting product name from TextView, get clicked row cursor using Adapter in onItemClick :
Cursor cursor = (Cursor) dataAdapter.getItem(position);
String product_name = cursor.getString(cursor.getColumnIndex("pn"));
int product_id = cursor.getInt(cursor.getColumnIndex("product_id"));
....
A good option is to create an array and store product_ids for all the names.
Goto Res->Strings create an array of strings .
then fetch from the array the relevant product_id for the name.
Right now I am almost done writing my app. All I need is a bit help on getting the selected String value from a spinner populated from my database by a simple cursor adapter. I am not sure how I can get the String from my spinner and pass it to a different cursor and use the string in a query, that will populate depending on the first choice of the spinner, and so on with other spinners.
Here is the code I am using for one of my spinners.
vType = (Cursor) DataBaseHelper.getPowersportsType();
this.startManagingCursor(vType);
SimpleCursorAdapter scaType = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vType,
new String [] {DataBaseHelper.POWERSPORTS_TYPE},
new int[] {android.R.id.text1});
scaType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vTypeSpinner = (Spinner) findViewById(R.id.typeSpinner);
vTypeSpinner.setAdapter(scaType);
And this is my query for the next spinner in my xml layout
static String MakeWhere = "POWERSPORTS_TYPE=?";
public static Cursor getPowersportsMake(){
return myDataBase.query(POWERSPORTS_TABLE,
new String [] {POWERSPORTS_ID, POWERSPORTS_MAKE},
MakeWhere,
null,
POWERSPORTS_MAKE,
null,
null);
}
Any comments or suggestions are welcomed.
to get the item selected you need to set the onItemSelectedListener
then in your onItemtSelected all you would do is
String selection = vTypeSpinner.getSelectedItem().toString();
I am new with android programing and I have a problem with list view
In my app I have to read data from database (name,ID,year) and then add them to listview after that user must select one of
the items and in a new activity again I read data from db and list some of the other Items based on user's selection
Ol at this time In my first activity I read data and add them to listview..To select I must define a listener..right?
I define it like this code
enter code here #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_book);
String SDcardPath = Environment.getExternalStorageDirectory().getPath();
String DbPath = SDcardPath + "/Tosca/" + "persian_poem.db";
ListView list = (ListView) findViewById(R.id.list_poet_name);
try {
db = SQLiteDatabase.openDatabase(DbPath,null,SQLiteDatabase.CREATE_IF_NECESSARY);
getData();
db.close();
}
catch (SQLiteException e) {
Toast.makeText(this, e.getMessage(), 1).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
ListView list = (ListView) findViewById(R.id.list_poet_name);
Log.i(TAG, "Listview get Item Pos");
Peot_ID.putString ("Peot_ID", (String) list.getItemAtPosition(position));
Intent Book_list_intent = new Intent (Read.this,Book_list.class);
Book_list_intent.putExtras(Peot_ID);
startActivity(Book_list_intent);
}
});
}
private void getData() {
try {
//txtMsg.append("\n");
// obtain a list of from DB
String TABLE_NAME = "classicpoems__poet_contents";
String COLUMN_ID = "poet_id";
String _ID = "_id";
String COLUMN_NAME = "poet_name";
String COLUMN_CENTURY = "century_start";
String [] columns ={_ID,COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY};
Cursor c = db.query(TABLE_NAME,columns,null, null, null, null, COLUMN_ID);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c,
new String[] {COLUMN_NAME,COLUMN_CENTURY}, new int[] {android.R.id.text1,android.R.id.text2}, 0);
ListView list = (ListView) findViewById(R.id.list_poet_name);
list.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), 1).show();
}
}
But here I have a problem..I want to send data of peot_id (Its deffrent from _id column in db) to next activity..Bt I mentioned that
with this code I can get whole row of selected item and I just want part of it(peot_id ) can you help me how to get just Peot_ID from selected
list item?
and I have another question..
As you see in my code I must refer to one spasial listview several times..each time I defined it by this code
enter code hereListView list = (ListView) findViewById(R.id.list_poet_name);
How can I define this listviwe one time and use it in several places in my code?sth like a public variable or sth like that
Thanks for your help.
As you see in my code I must refer to one spasial listview several
times..each time I defined it by this code
No. Just create one global ListView variable list and simply you can access to it from everywhere in your Activity. There is no need to declaring and initialising ListView again in OnItemClick() method.
I want to send data of peot_id (Its deffrent from _id column in db) to
next activity..Bt I mentioned that with this code I can get whole row
of selected item and I just want part of it(peot_id ) can you help me
how to get just Peot_ID from selected list item?
You are using Android's defined basic layout
android.R.layout.simple_list_item_2
I suggest you to create own XML file for row and then simply get whole View from ListView and from View you can get only ID.
Example:
listrow.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:background="#drawable/addresses_list_selector"
>
<TextView
android:id="#+id/id_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/name_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/id_column"
/>
<TextView
android:id="#+id/century_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/name_column"
/>
</RelativeLayout>
Then an usage with CursorAdapter:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listrow, c,
new String[] {COLUMN_ID, COLUMN_NAME, COLUMN_CENTURY},
new int[] {R.id.id_column, R.id.name_column, R.id.century_column}, 0);
And then for getting ID from row:
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
TextView id = (TextView) v.findViewById(R.id.id_column);
if (id != null) {
String idString = id.getText().toString();
}
}
Note:
If you still want to use android's predefined layout, you need to pass into String[] from ID_COLUMN and then access to ID from row via row.findViewById(<id>);
String[] from = {ID_COLUMN, NAME_COLUMN};
int[] to = {android.R.id.text1, android.R.id.text2};
TextView id = v.findViewById(android.R.id.android.R.id.text1);
String idString = id.getText().toString();
You do query like this to get a Particular column record alone :
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_DESIGNATION}, KEY_ROWID + "=" + yourPrimaryKey, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
I personally prefer to use onListItemclick() method like that
//do not forget to override - very important
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//TODO what you what you have here the vars position - position of the selected item in list
// and also the id so you can easy trace what selection done the user
// you can play with this
}
hay i used the SimpleCursorAdapter from implement the data on the spinner.its going well. also to get data i used following code:
Cursor cursor = (Cursor) (spncomapnayname.getSelectedItem());
if (cursor != null) {
companyselected = cc.getString(cc.getColumnIndex(db.COMPANY_NAME));
}
it is working well.but it is for the getting data from the spinner.but now i want to set particular data on spinner which was inserted by the user for update for normal ArrayAdapter spinner we used:
spinnername.setSelection(adapter1.getPosition(abc));
so i want to know how to set data from the database on spinner.
here is my code:
cursor = db.getProductName();
adapter1 = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { DB_Database.PRODUCT_NAME }, new int[] { android.R.id.text1 });
adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spnproduct.setAdapter(adapter1);
purchaseproduct = purchasebundle.getString("clickedpurchaseproductname");
if(!purchaseproduct.equals("null")|| !purchaseproduct.equals("")) {
System.out.println("purchaseproduct" + purchaseproduct);
String mypurchaseproduct=purchaseproduct;
ArrayAdapter myAdap = (ArrayAdapter) spnproduct.getAdapter();
int spinnerPosition = myAdap.getPosition(mypurchaseproduct); // set the default according to value
spnproduct.setSelection(spinnerPosition);
}
here i get data from bundle.i want to retrive data on Spinner.the data is populated from SimpleCursorAdapter
First Get Selected Value From Cursor and store into mString Variable and then use below code for display this selected value into Spinner.
if (!mString.equals("null") || !mString.equals("")) {
String myString = mString; // the value you want the position for
ArrayAdapter<String> myAdap = (ArrayAdapter<String>) mSpn1.getAdapter(); // cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(myString);
// set the default according to value
mSpn1.setSelection(spinnerPosition);
}
You can do something like this:
Cursor c = (Cursor)parent.getItemAtPosition(pos);
int id = c.getInt(c.getColumnIndexOrThrow("columm_name"));
or to get a String
String name=c.getString(c.getColumnIndexOrThrow("columm_name"));
I want to get id of particular name that i selected in spinner.i did like this but it will print "_id" how can i retrieve id of particular name.
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String sel_name,numbers;
//String[] name=new String[]{arg0.getItemAtPosition(arg2).toString()};
sel_name=arg0.getItemAtPosition(arg2).toString();
String[] p=new String[]{People._ID};
Cursor cur=getContentResolver().query(People.CONTENT_URI, p,People.NAME+"= '"+sel_name+"'" ,null , null);
String r=cur.getString(cur.getColumnIndex(People._ID));
Toast.makeText(arg0.getContext(),r, Toast.LENGTH_LONG).show();
}
You need to add a cursor.moveToFirst(); call before you use the cursor.
If you are refering to sel_name, then this is what you should do to get the view's id:
sel_name = String.valueOf(arg0.getChildAt(arg2).getId());
add following after cursor
while(cur.moveToNext)
{
String r=cur.getString(cur.getColumnIndex(People._ID));
}
by id of perticular name if you mean a string den avoid to do so . alw
ays use id as int only ,because R file have int entries only , so will be easy to handle .
for this i guess in onItemSelected
arg1.getId() will work ........
or try setTag(id) in get view of customAdapter of spinner , then in onItemSelected int id = arg1.getTag();