Unable to show data in Gridview in Android ! please help me out - android

I am entering some values in to my SQLlite database and then retrieving them in a gridview.I am getting a Error "column'_id'" does not exist.but I have not used any _id named column in the database. How can I make it work?? I think theres some problem with SimpleCursor Adapter .
GridView gv = (GridView)findViewById(R.id.gridView1);
try
{
db1 = openOrCreateDatabase("record.db", Context.MODE_PRIVATE,null);
db1.execSQL("CREATE TABLE IF NOT EXISTS stu(ID INTEGER primary Key,NAME VARCHAR foriegn key,age VARCHAR);");
db1.execSQL("INSERT INTO stu VALUES (1,'mona','123');");
Cursor c = db1.rawQuery("SELECT * FROM stu", null);
if(c!= null){
if (c.moveToFirst()) {
do {
String[] cols = new String[]{c.getString(c.getColumnIndex("ID")),c.getString(c.getColumnIndex("NAME"))};
int[] views = new int[] {R.id.textView1,R.id.textView2};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
c, cols, views);
gv.setAdapter(adapter);
}while(c.moveToNext());}
}} catch(Exception e){
Toast.makeText(getBaseContext(),"errord"+ e.getMessage(), Toast.LENGTH_LONG).show();
}
}

The documentation for CursorAdapter (which SimpleCursorAdapter extends) states:
The Cursor must include a column named "_id" or this class will not work.

Related

Is that possible Bind Spinner Without _id Column?

public void DatabaseConn() {
DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Driver", null);
startManagingCursor(c);
//create an array to specify which fields we want to display
String[] from = new String[]{"Driver_Name"};
//create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
//create simple cursor adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//get reference to our spinner
Spinner s = (Spinner) findViewById( R.id.DriverSpin);
s.setAdapter(adapter);
db.close();
}
Is that possible Bind Spinner Without _id Column? any idea?
Edited : Except SimpleCursorAdapter, any others adapter able to do this? I mean without _id column
From the android documentation for CursorAdapter which is the superclass of the SimpleCursorAdapter you are using:
The Cursor must include a column named "_id" or this class will not work.
So, no.
Edit:
Actually, there is a way to get around this issue. If you read carefully, it says that the Cursor must have a column named _id, which we can get by changing your query string to:
"SELECT ROWID AS _id, someColumn, anotherColumn FROM Tbl_Driver"
You will have to manually type out all of the columns you want though since doing ROWID AS _id will not work at the same time as using the wildcard *.

Using SimpleCursorAdapter with Spinner?

I have a db with table "mytable" having 2 colums "id","sampletext"
I want to query distinct values of sampletext and feed to a Spinner using SimpleCursorAdapter.
here is what is tried
String[] cols=new String[]{"sampletext"};
int[] lbls=new lbls[]{android.R.id.text1};
mycursor=sdb.query(true,"mytable", cols,null,null,null,null,null,null);
sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, cols,lbls,0);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(sca);
When i run this i get error at line 4 : id does not exist.
when i changed first line to "id" the spinner got populated with id values.
But i need "sampletext", what am i doing wrong?
Appreciate any suggestions
what am i doing wrong
you didnt read documentation ...
there are two arrays of string with columns: first in used in query, second one in Adapter constructor(you used only one array for both)
first one tells sqlite which columns should be taken to Cursor, second tells Adapter which ones should be showed/mapped to Views in single row...
Next CursorAdapter needs Cursor with column named _id
So now it's pretty obvious that we should do smthin like this:
String[] queryCols=new String[]{"_id", "sampletext"};
String[] adapterCols=new String[]{"sampletext"};
int[] adapterRowViews=new int[]{android.R.id.text1};
mycursor=sdb.query(true,"mytable", queryCols,null,null,null,null,null,null);
sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, adapterCols, adapterRowViews,0);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(sca);
Here's an example with raw query. Please note the first ID column returned by the query should be labeled as _id .
MyDatabase.java:
public class MyDatabase extends SQLiteAssetHelper {
...
public Cursor getListNamesForDropDown() {
SQLiteDatabase db = getReadableDatabase();
String sql = "select ID _id, Name from MyTable order by Name ";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
MyActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
....
Cursor cursorTest = db.getListNamesForDropDown();
android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursorTest,
new String[] {"Name"},
new int[] {android.R.id.text1}, 0);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTest.setAdapter(adapter);
android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursor,
new String[] { DBOpenHelper.ACCOUNT_BANK },
new int[] { android.R.id.text1 }, 0);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Android Listview From Database

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/

Simple Cursor Adapter problem

Here is my code for a simple cursor adapter.
public class CursorList extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseAdapter da = new DatabaseAdapter(this, "mydb.sqlite");
da.open();
Cursor cur = da.fetchAllRecords("Doctors", new String[]{"FirstName"});
startManagingCursor(cur);
cur.moveToFirst();
do {
Log.v("Info", cur.getString(cur.getColumnIndex("FirstName")));
} while(cur.moveToNext());
cur.moveToFirst();
String[] from = new String[]{"FirstName"};
int[] to = new int[]{R.id.row};
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);
setListAdapter(sca);
}
}
The data records are displayed correctly in the log, but the code stops working when it reaches the
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);
line.
The error I get is :
ERROR/AndroidRuntime(26746): Uncaught handler: thread main exiting due to uncaught exception
ERROR/AndroidRuntime(26746): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arnab.cursorlist/com.arnab.cursorlist.CursorList}:
java.lang.IllegalArgumentException: column '_id' does not exist
Where am I going wrong?
Why does it give an error that column '_id' doesn't exist? Is it a necessary column which we have to have in our tables?
EDIT:
When I put the cursor related code in a try catch block, something like this:
try {
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.row_item, cur, from, to);
setListAdapter(sca);
}
catch(Exception E) {
Log.v("Error", E.getMessage());
}
I get the message :
VERBOSE/Error(1026): column '_id' does not exist
#Rasel : Here is the fetchAllRecords method
public Cursor fetchAllRecords(String table, String columns[]) {
return mDb.query(table, columns, null, null, null, null, null);
}
Why does it give an error that column '_id' doesn't exist? Is it a necessary column which we have to have in our tables?
Yes, if you want to use your database information in a cursor adapter. The adapter uses it for internal purposes. Your table must have an '_id' column, and you must select it in your query (so it is in the Cursor result set). You do not have to actually display it in your ListView.
Revised for Posterity
Instead of actually adding the '_id' column, you can SELECT your own 'id' column as '_id', and it will work just the same.
Write Cursor related code in try catch block.Your problem will be solved.Check when created table you typed different column rather than '_id'
You need to include the table _id in the projection. the list cursor adapter needs the _id to keep track of the rows. you don't have to actually display it anywhere or use it but the cursor needs to contain that column. also a primary key column named _id is mandatory in every android table.

Android array list from database

I wanna create an array of cities that are stored in the database
Cities Table
CREATE TABLE cities (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);
Querying for City List
// City List
public Cursor cityList() throws SQLException {
return db.query(TABLE_CITIES, new String[] {ID, KEY_NAME}, null, null, null, null, null, null);
}
Trying to Get the content into the Array
Cursor cities = db.cityList();
startManagingCursor(cities);
String[] city_list = new String[] { DBAdapter.KEY_NAME };
Spinner cityList = (Spinner)this.findViewById(R.id.citySpiner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, city_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cityList.setAdapter(adapter);
Am not able to populate the Spinner.. with the database content.
Try SimpleCursorAdapter
String[] from = new String[] { DBAdapter.KEY_NAME };
int[] to = new int[] {android.R.id.text1};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(context, android.R.layout.simple_spinner_dropdown_item , cursor, from, to);
cityList.setAdapter(cursorAdapter);
Edit:
from means the column(s) from the Cursor which will be used to display as text array in Spinner.
to means the id(s) of the view which will hold the value of that column.
It is very interesting that the view at index N will hold the text from column at N.

Categories

Resources