I am filling my ListView with data which I am getting from the database I created. I want to get the name of the item in ListView which is being long clicked.
I have tried using following method:
- parent.getItemAtPosition(position).toString();
- myListView.getItemAtPosition(position).toString();
- myListView.getSeletedItem(position).toString();
These three statements work well but as I am filling up the LisView by getting data from my database so I am getting the following value returned:
09-20 13:01:22.370: I/System.out(5351): android.database.sqlite.SQLiteCursor#426925b0
whereas the Item's name, which I am clicking, is 'Home'..
Please help me. How can I convert android.database.sqlite.SQLiteCursor#426925b0 into Home?
MY ADAPTER:
mCursor = mDB.fetchData();
String[] columns = new String[] { AreaDatabase.KEY_AREA };
int[] to = new int[] { R.id.tvArea };
mAdapter = new SimpleCursorAdapter(this, R.layout.lvarea, mCursor,
columns, to);
lvArea.setAdapter(mAdapter);
fetchData() function:
public Cursor fetchAreaData() {
Cursor mCursor = ourDatabase.query(AREA_TABLE_NAME, new String[] {
KEY_ROWID, KEY_AREA }, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Cursor has method getString(int columnIndex). You can use that to get String value from Cursor from specified column index.
> Cursor currentCur = myListView.getItemAtPosition(position);
> String name = currentCur.getString(1); //It will return KEY_AREA (column index 1) value from Cursor
do like this :
parent.getItemAtPosition(position).toString();
Related
Cursor getting first value as this
But returning last value as this.
Code for getting from cursor
BillInfo getContact(String date) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor query
Cursor cursor = db.query(TABLE_ID, new String[] { KEY_ID,
KEY_NAME, KEY_PRICE, KEY_DATE }, KEY_DATE + "=?",
new String[] { String.valueOf(date) }, null, null, null, null);
BillInfo contact = null ;
Array bill type
BillInfo bill[]=null;
int i=0;
Cursor code
if ( cursor.moveToFirst() ) {
bill=new BillInfo[cursor.getCount()];
do {
//Since both are in different classes
contact = new BillInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
bill[i]=contact;
}while(cursor.moveToNext());
}
return bill[i];
}
Code for loading the values on click
public void Load1(View v){
date1=date.getText().toString();
Doubleme d=new Doubleme(this);
BillInfo s;
Returning the value from get contact
s= d.getContact(date1);
info.append( s.toString());
}
Looks like, the value of i is fixed:
int i=0;
But inside of the cursor iteration loop you each time override the bill[i] with a new BillInfo reference. No wonder why the line:
return bill[i];
fetches the last row instead of the first one. I suggest getting rid of the while loop if you only need the first row.
02-23 20:16:17.499: E/AndroidRuntime(25817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.makkosarka/com.example.makkosarka.Table.Table}:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.makkosarka/
com.example.makkosarka.Table.Liga1}: java.lang.IllegalArgumentException: column '_id' does not exist
and here are the methods that are trying to select records from this table and than display
in listview
private void populateListFromDB(){
Cursor cursor = myDB.getAllRows("1");
startManagingCursor(cursor);
String[] columnFromTable = new String[]
{DBadapter.KEY_HOSTID, DBadapter.GUESTID, DBadapter.KEY_HSCORE , DBadapter.KEY_GSCORE };
int[] toLayoutFild = new int[] {R.id.txtview_name, R.id.txtview_gameno, R.id.txtview_won, R.id.txtview_lost, };
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, R.layout.rowlayout,
cursor, columnFromTable, toLayoutFild);
ListView mylistview = (ListView) findViewById(R.id.listview_table);
mylistview.setAdapter(myCursorAdapter);
}
This is in the Adapter class and i'm not even selecting the "_id"(KEY_ROWID) column
public static final String[] ALL_COLUMNS = new String[] {KEY_HOSTID, KEY_GUESTID,
KEY_HSCORE, KEY_GSCORE};
public Cursor getAllRows(String league) {
Cursor c = db.query(true, DUELS_TABLE, ALL_COLUMNS,
null, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
What does that error mean is it possible that the table is not created at all?
I have two tables and I`m using the same method to select records for the other one it works perfectly but for this it shows this error listed on the top of this question
This is in the Adapter class and i'm not even selecting the "_id"(KEY_ROWID) column
CursorAdapter and its subclasses require that the Cursor have a column named _id. Use your own if you have one, or else switch to rawQuery() so you can include ROWID AS _id in your list of columns to return.
I am working on Android and my intention is to filter out my cursor. The cursor is coming from database and it has some rows. Now I want to skip some rows from cursor by using id column and pass the remaining rows to the listview adapter as cursor.
My code is like checking that the row id is equal to the filtercursor row id then have to skip the row from the presentcursor.
The code:
Cursor c = getActivity().getContentResolver().query(
Provider.CONTENT_URI_DINERS, null,
DinerColumns.COL_RESERVATION_FROM , null, null);
c.moveToFirst();
do{
String dinerId = c.getString(c.getColumnIndex(DinerColumns.COL_DIN_ID));
if(isSeatedDiner(dinerId)){
}
}while(c.moveToNext());
private boolean isSeatedDiner(String dinerID){
Cursor cursor = getActivity().getContentResolver().query(
Provider.CONTENT_URI_SEATED,
new String[] {"COUNT(*)" },SeatedDinerColumns.COL_DINE_ID +"="+dinerID , null,
null);
if(cursor.moveToFirst()){
do
{
String newId = cursor.getString(cursor.getColumnIndex(SeatedDinerColumns.COL_DINE_ID));
if(Integer.parseInt(dinerID)==Integer.parseInt(newId))
{
return true;
}
}while(cursor.moveToNext());
}
return false;
}
You can filter the data while querying the database.
Or - Filter rows from Cursor so they don't show up in ListView
I have a table called tbl_homework. There are 3 columns called "_id", "hw" and "hwdate".
Now I like to read out "hw" AND "hwdate". So I like it on the same line in this listview.
I have to say that it is working without crash or error. It just don't show the date...
Following picture will tell you what I mean:
Here are the code snippets to tell you how I tried this:
private Button.OnClickListener add_hw = new Button.OnClickListener(){
public void onClick(View arg0) {
mDbHelper.open_database_rw();
String txt_insert_hw = insert_hw.getText().toString();
if(txt_insert_hw.equals("")){
doMessage("Keine Eingabe!");
}else{
String date_picker_message= date_pick.getDayOfMonth() + "/" + (date_pick.getMonth()+1) + "/" + date_pick.getYear();
final String INSERT_HW = "INSERT INTO tbl_homework ('hw', 'hwdate') VALUES ('"+txt_insert_hw+"', '"+date_picker_message+"')";
db.execSQL(INSERT_HW);
insert_hw.setText("");
fillData();
}
}
};
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
int[] to = new int[] {R.id.txt_notes_row};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
And in mDbHelper:
public Cursor fetchAllNotes() {
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_DATE}, null, null, null, null, null);
}
Soulution of this problem: (Received from Jury)
String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
int[] to = new int[] {R.id.txt_notes_row, R.id.txt_notes_row2};
I had to add a new TextView. dbHelper.KEY_TITLE AND dbHelper.KEY_DATE coudn't be handle by one TextView. So I had to add a new TextView to handle the second part of my String "from".
I think the problem is that you try to match two columns (from) to only one container (to) here:
String[] from = new String[] { dbHelper.KEY_TITLE, dbHelper.KEY_DATE};
int[] to = new int[] {R.id.txt_notes_row};
You should specify two fields in the list row where you store your values. I.e. your R.id.txt_notes_row should contain two widgets (for instance, R.id.txtview1 and R.id.txtview2) where you can store your values from db.
I'm new in android. I'm facing a problem creating a listview using data from sqlite database.
I found this code below to create a listview from contact data
public class Test extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a cursor with all people
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_list_item_1,
// Give the cursor to the list adatper
c,
// Map the NAME column in the people database to...
new String[] {Contacts.DISPLAY_NAME},
// The "text1" view defined in the XML template
new int[] {android.R.id.text1});
setListAdapter(adapter);
}
private static final String[] CONTACT_PROJECTION = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME
};
}
Now I use this code to pull data from database
SQLiteDatabase myDB= null;
String TableName = "myTable";
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
// Get a cursor with all people
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
Now How can I combine these two codes so I can show data pulled from a database in this list.
Thanks in advance.
If you want to list the data from both sources (contact and DB), I think only option you have is construct an array with return values from both sources.
List finalList = new ArrayList();
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
c.moveToFirst();
Iterate this cursor and populate the String value to finalList
SQLiteDatabase myDB= null;
String TableName = "myTable";
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
// Get a cursor with all people
Cursor c2 = myDB.rawQuery("SELECT * FROM " + TableName , null);
startManagingCursor(c2);
c2.moveToFirst();
Iterate c2 cursor and add values to finalList.
Convert finalList to array by Iterating finalList
String[] ipArray = new String[finalList.size()];
loop through list and populate the values to ipArray.
I don't have IDE handy, so I have typed the flow.
If suppose you already have data in your cursor, you can follow code in the following tutorial
http://chetanandroidarora.wordpress.com/2011/12/18/customcursoradapter/