_ID does not exist
I'm trying to obtains data from a slide bbdd and show it in a list view, but I have errors.
public class DataBaseHelper extends SQLiteOpenHelper{
private static String DB_PATH = "/data/data/com.rbrlnx.lugares/databases/";
private static final String DATABASE_NAME="db.db";
SQLiteDatabase db;
String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS lugares (" +
" _id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"nombre text," +
"descripcion text,"+
"latitud real," +
"longitud real," +
"foto String);";
/*Primero se crea constructor, funcion onCreate, onUpgrade,Abrir y Cerrar*/
public DataBaseHelper(Context context){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db){
try {
openDataBase();
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
// handle exception
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void close(){
db.close();
}
/*Despues metodos para añadir y obtener datos*/
public long addNombre(String nombre){
ContentValues cv = new ContentValues();
cv.put("nombre", nombre);
return db.insert("lugares", null, cv);
}
public long addDescripcion(String descripcion){
ContentValues cv = new ContentValues();
cv.put("descripcion", descripcion);
return db.insert("lugares", null, cv);
}
public long addLatitud(double latitud){
ContentValues cv = new ContentValues();
cv.put("latitud", latitud);
return db.insert("lugares", null, cv);
}
public long addLongitud(double longitud){
ContentValues cv = new ContentValues();
cv.put("longitud", longitud);
return db.insert("lugares", null, cv);
}
public long addFoto(String foto) {
ContentValues cv = new ContentValues();
cv.put("foto", foto);
return db.insert("lugares", null, cv);
}
public Cursor getNombres(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor respuesta = db.rawQuery("select nombre from lugares", null);
return respuesta;
}
}
and
public class listatab extends ListActivity{
Context context;
ListView listanombres;
DataBaseHelper ayudabbdd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataBaseHelper ayudabbdd = new DataBaseHelper(this);
Cursor nombresC;
nombresC = (Cursor) ayudabbdd.get开发者_运维技巧Nombres();
startManagingCursor(nombresC);
if(nombresC!=null){
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.listatab, nombresC, new String[] { "nombre" }, new int[] { R.id.lista });
this.setListAdapter(adapter);
this.getListView().setTextFilterEnabled(true);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (ayudabbdd != null) {
ayudabbdd.close();
}
}
}
And log cat shows me this errors:
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rbrlnx.lugares/com.rbrlnx.lugares.listatab}: java.lang.IllegalArgumentException: column '_id' does not exist
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1487)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:654)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.widget.TabHost.setCurrentTab(TabHost.java:326)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:132)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:456)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.view.View.performClick(View.java:2485)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.view.View$PerformClick.run(View.java:9080)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.os.Handler.handleCallback(Handler.java:587)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.os.Handler.dispatchMessage(Handler.java:92)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.os.Looper.loop(Looper.java:130)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at java.lang.reflect.Method.invokeNative(Native Method)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at java.lang.reflect.Method.invoke(Method.java:507)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): at dalvik.system.NativeStart.main(Native Method)
10-11 00:55:49.930: ERROR/AndroidRuntime(32392): Caused by: java.lang.IllegalArgumentException: column '_id' does not exist
Your openDataBase()
method is very wrong. You shouldn't supply the path to the database. The database is created for you and passed to you in the onCreate()
method. If you remove the openDataBase()
method and don't call it from onCreate()
, and set this.db = db
in onCreate()
, you might get past this error.
For more help on working with databases in Android, see this Android Database Tutorial. Good Luck!
I think that _id column must be selected too.
Cursor respuesta = db.rawQuery("select _id, nombre from lugares", null);
Without having more information (and I'm no Android expert), I suspect that your table either doesn't exist or it exists but doesn't have that _id
column. You're using CREATE TABLE IF NOT EXISTS
which should result in the create statement not being executed if the table - which might have different columns - already exists.
You're not logging your exceptions, so the statement might actually throw one that is just ignored.
Brad is correct that you have a problem with creating your table. You should have a look at the database tutorial again.
The _id does not exist question occurs because you are not querying the _id column. Use
Cursor respuesta = db.rawQuery("select _id, nombre from lugares", null);
to get you cursor.
The _id column is used to identify and sort the items. If it is not present the CursorAdapter does not know how to put the items from your cursor in the list.
If your table does not have an column named _id but you have something that is maybe called id there is a way to select a column but give it another name in the resulting cursor. I don't know the correct syntax but it looks a little bit like select (id AS _id).
public class DataBaseHelper
{
Context context;
private static final String DATABASE_NAME="lugaresbbdd";
private SQLiteDatabase db; // Referencia al manager.
private final int DB_VERSION = 1; // version
// Nombres para las tablas y campos
private final String TABLE_NAME = "lugares";
private final String TABLE_ROW_ID = "_id";
private final String CNOMBRE = "nombre";
private final String CDESC = "descripcion";
private final String CLAT = "latitud";
private final String CLONG="longitud";
private final String CFOTO="foto";
public DataBaseHelper(Context context)
{
this.context = context;
//Crea o abre la BBDDD
CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
this.db = helper.getWritableDatabase();
}
/*Metodos para añadir datos a la BBDD*/
/**********************************************************************
* Metodos para añadir nombres a la BBDDD
*
* @param nombre valor para nombre
*/
public long addNombre(String nombre){
ContentValues cv = new ContentValues();
cv.put("nombre", nombre);
return db.insert("lugares", null, cv);
}
/**********************************************************************
* Metodos para añadir descrpcipciones a la BBDDD
*
* @param descripcion valor para descripcion
*/
public long addDescripcion(String descripcion){
ContentValues cv = new ContentValues();
cv.put("descripcion", descripcion);
return db.insert("lugares", null, cv);
}
/**********************************************************************
* Metodos para añadir latitudes a la BBDDD
*
* @param latitud valor para campo latitud
*/
public long addLatitud(double latitud){
ContentValues cv = new ContentValues();
cv.put("latitud", latitud);
return db.insert("lugares", null, cv);
}
/**********************************************************************
* Metodos para añadir longitud a la BBDDD
*
* @param longitud valor para campo longitud
*/
public long addLongitud(double longitud){
ContentValues cv = new ContentValues();
cv.put("longitud", longitud);
return db.insert("lugares", null, cv);
}
/**********************************************************************
* Metodos para añadir foto a la BBDDD
*
* @param foto valor para patch de la foto
*/
public long addFoto(String foto) {
ContentValues cv = new ContentValues();
cv.put("foto", foto);
return db.insert("lugares", null, cv);
}
/**********************************************************************
* * Obten todos los nombres
*
*/
public Cursor getNombres(){
Cursor respuesta = db.rawQuery("select "+TABLE_ROW_ID+","+CNOMBRE+" from "+TABLE_NAME, null);
return respuesta;
}
/**********************************************************************
* Borra una fila de la BBDD
*
* @param rowID ID de la BBDD que quiero borrar
*/
public void deleteRow(long rowID)
{
try {db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
/**********************************************************************
* ACTUALIZANDO UN LUGAR DE LA BBDD
* @param rowID EL ID DEL LUGAR QUE QUIERO MODIFICAR
* @param rowNombre nombre nuevo
* @param rowDesc descrpcion nuega
* @param rowLat latitud nueva
* @param rowLong longitud nueva
* @param rowFoto foto nueva
*/
public void updateRow(long rowID, String rowNombre, String rowDesc, Long rowLat, Long rowLong, String rowFoto)
{
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(CNOMBRE, rowNombre);
values.put(CDESC, rowDesc);
values.put(CLAT, rowLat);
values.put(CLONG,rowLong);
values.put(CFOTO,rowFoto);
// ask the database object to update the database row of given rowID
try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
/**
Clase que comprueba si la tabla existe,
Si no existe, se crea
Si existe, se actualiza
Metodo que la cierra al finalizar su uso
*/
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
public CustomSQLiteOpenHelper(Context context)
{
super(context, DATABASE_NAME, null, DB_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
String CREA_TABLA =
"CREATE TABLE " +
TABLE_NAME +
"("+
TABLE_ROW_ID + " integer primary key autoincrement not null," +
CNOMBRE + " TEXT," +
CDESC + " TEXT," +
CLAT + " REAL," +
CLONG + " REAL," +
CFOTO + " STRING" +
");";
db.execSQL(CREA_TABLA);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//NO HAGAS NADA
}
public void close(){
db.close();
}
}
}
public class listatab extends ListActivity{
Context context;
ListView listanombres;
DataBaseHelper ayudabbdd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ayudabbdd = new DataBaseHelper(this);
Cursor nombresC;
nombresC = (Cursor) ayudabbdd.getNombres();
startManagingCursor(nombresC);
if(nombresC!=null){
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.listatab, nombresC, new String[] { "nombre" }, new int[] { R.id.lista });
this.setListAdapter(adapter);
this.getListView().setTextFilterEnabled(true);
}
}
}
精彩评论