SimpleCursorAdapter不加载外部SQLite数据库:" _id"错误 [英] SimpleCursorAdapter does not load external sqlite database: "_id" error

查看:115
本文介绍了SimpleCursorAdapter不加载外部SQLite数据库:" _id"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误说:列_id不存在但列在数据库中(设置主键),这一个是位于外部SD文件夹。我试图返回包含在对活动的初始加载数据库中的值,但它似乎像光标不返回任何东西。

 公共类ComponentsDbAdapter {  公共静态最后弦乐COLUMN_ID =_id;
  公共静态最后弦乐COLUMN_SUBSTRUCTURE =子;
  公共静态最后弦乐COLUMN_TYPE =类型;
  公共静态最后弦乐COLUMN_ORDERNUM =ORDERNUM;
  公共静态最后弦乐COLUMN_INSTALLATION =安装;
  私有静态最后弦乐TAG =ComponentsDbAdapter;
  私人DatabaseHelper mDbHelper;
  私人SQLiteDatabase MDB;
  私有静态最后弦乐DATABASE_PATH = Environment.getExternalStorageDirectory()getAbsoluteFile()+/ DATABASE_BACKUP / IMPORTED /。
  私有静态最后弦乐DATABASE_NAME =android.db;
  私有静态最后弦乐TABLE_NAME =TAB_WORKSCPE;
  私有静态最终诠释DATABASE_VERSION = 1;
  私人最终上下文mCtx;
  公共ComponentsDbAdapter的open()抛出的SQLException {
    mDbHelper =新DatabaseHelper(mCtx);
    MDB = mDbHelper.getWritableDatabase();
    返回此;
  }  私有静态类DatabaseHelper扩展SQLiteOpenHelper {
    DatabaseHelper(上下文的背景下){
        超(背景下,DATABASE_PATH + DATABASE_NAME,空,DATABASE_VERSION);
    }
    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        db.query(TABLE_NAME,新的String [] {COLUMN_ID,COLUMN_SUBSTRUCTURE,COLUMN_TYPE,COLUMN_ORDERNUM,COLUMN_INSTALLATION},NULL,NULL,NULL,NULL,NULL);
    }
    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        Log.w(TAG,从版本升级数据库+ oldVersion +到+ NEWVERSION +,这将摧毁所有旧数据);
        db.execSQL(DROP TABLE IF EXISTS+ TABLE_NAME);
        的onCreate(DB);
    }
  }  公共ComponentsDbAdapter(上下文CTX){
    this.mCtx = CTX;
  }  公共无效的close(){
    如果(mDbHelper!= NULL){
        mDbHelper.close();
    }
 }  公共光标fetchComponentsByName(字符串inputText的)抛出的SQLException {
    Log.w(TAG,inputText的);
    光标mCursor = NULL;
    如果(inputText的== NULL || inputText.length()== 0){
        mCursor = mDb.query(TABLE_NAME,新的String [] {COLUMN_ID,COLUMN_SUBSTRUCTURE,COLUMN_TYPE,COLUMN_ORDERNUM,COLUMN_INSTALLATION},NULL,NULL,NULL,NULL,NULL);
}其他{
    mCursor = mDb.query(真,TABLE_NAME,新的String [] {COLUMN_ID,COLUMN_SUBSTRUCTURE,COLUMN_TYPE,COLUMN_ORDERNUM,COLUMN_INSTALLATION},COLUMN_TYPE +LIKE'%+的inputText +%',NULL,NULL,NULL,NULL,NULL );
}
    如果(mCursor!= NULL){
        mCursor.moveToFirst();
    }
    返回mCursor;
}公共光标fetchAllComponents(){
    光标mCursor = mDb.query(TABLE_NAME,新的String [] {COLUMN_ID,COLUMN_SUBSTRUCTURE,COLUMN_TYPE,COLUMN_ORDERNUM,COLUMN_INSTALLATION},NULL,NULL,NULL,NULL,NULL);
    如果(mCursor!= NULL){
        mCursor.moveToFirst();
    }
    返回mCursor;
  }
}公共类AndroidListViewCursorAdaptorActivity延伸活动{私人ComponentsDbAdapter dbHelper;
私人SimpleCursorAdapter DataAdapter的;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);    dbHelper =新ComponentsDbAdapter(本);
    dbHelper.open();    //生成SQLite数据库的ListView
    displayListView();
}私人无效displayListView(){
    光标光标= dbHelper.fetchAllComponents();    //所需的列被绑定
    的String [] =列新的String [] {
        ComponentsDbAdapter.COLUMN_SUBSTRUCTURE,
        ComponentsDbAdapter.COLUMN_TYPE,
        ComponentsDbAdapter.COLUMN_ORDERNUM,
        ComponentsDbAdapter.COLUMN_INSTALLATION
    };    //该数据将被绑定到XML定义的视图
    INT []为= INT新[] {
        R.id.inst,
        R.id.subdt,
        R.id.type,
        R.id.ordernum,
    };    //创建使用光标指向所希望的数据的转接器
    //以及布局信息
    DataAdapter的=新SimpleCursorAdapter(
        这个,
        R.layout.country_info,
        光标,
        列,
        至,
        0);    ListView控件的ListView =(ListView控件)findViewById(R.id.listView1);
    //指定适配器的ListView
    listView.setAdapter(DataAdapter的);
    listView.setOnItemClickListener(新OnItemClickListener(){
        @覆盖
        公共无效onItemClick(适配器视图<>的ListView,观景,
            INT位置,长的id){
            //获取光标,定位在相应的行中的结果集
            光标光标=(光标)listView.getItemAtPosition(位置);            //此行中的数据库获得该州的首府。
            串compSubdt = cursor.getString(cursor.getColumnIndexOrThrow(SUBDT));
            Toast.makeText(getApplicationContext(),compSubdt,Toast.LENGTH_SHORT).show();
        }
    });    的EditText myFilter =(EditText上)findViewById(R.id.myFilter);
    myFilter.addTextChangedListener(新TextWatcher(){        公共无效afterTextChanged(编辑S){
        }        公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数后INT){
        }        公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数){
            。dataAdapter.getFilter()过滤(s.toString());
        }
    });    dataAdapter.setFilterQueryProvider(新FilterQueryProvider(){
        公共光标runQuery(CharSequence的约束){
            返回dbHelper.fetchComponentsByName(constraint.toString());
        }
    });
 }
 }


解决方案

好吧,这花了我将近一周很大的压力,但在这里是解决方案。我开始要经过很多的教程,并得到了它在这一个工作:

HTTP://www.mysamplecode.com / 2012/11 / Android的数据库内容provider.html

我从提取的虚拟设备数据库,并手动添加更多的数据。然后复制数据库所需的文件夹在我的设备文件夹(它只是为了确保数据库一致性/列是完全一样的)。然后改变MyDatabaseHelper类,如下所示:

 公共类MyDatabaseHelper扩展SQLiteOpenHelper {    。私有静态最后弦乐DATABASE_PATH = Environment.getExternalStorageDirectory()getAbsoluteFile()+/ MyFolder中/;
    私有静态最后弦乐DATABASE_NAME =TheWorld.db;
    私有静态最终诠释DATABASE_VERSION = 1;    MyDatabaseHelper(上下文的背景下){
        超(背景下,DATABASE_PATH + DATABASE_NAME,空,DATABASE_VERSION);
    }    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        CountriesDb.onCreate(DB);
    }    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        CountriesDb.onUpgrade(DB,oldVersion,静态网页);
    }
}

不要忘了权限添加到您的清单:

 <使用许可权
    机器人:名字=android.permission.WRITE_EXTERNAL_STORAG​​E/>

完成!
如果通过上面的答案职位读取基于Kirks咨询所以读他的推荐链接帮助。我还有更多的测试做以防万一我的数据库结构是错了。

The error says: column _id does not exists but the column is in the database (set as primary key) and this one is located in the external SD folder. I'm trying to return the values contained in the database on the initial load of the activity but it seems like the cursor is not returning anything.

public class ComponentsDbAdapter {

  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_SUBSTRUCTURE = "substructure";
  public static final String COLUMN_TYPE = "type";
  public static final String COLUMN_ORDERNUM = "ordernum";
  public static final String COLUMN_INSTALLATION = "installation";
  private static final String TAG = "ComponentsDbAdapter";
  private DatabaseHelper mDbHelper;
  private SQLiteDatabase mDb;
  private static final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/DATABASE_BACKUP/IMPORTED/";
  private static final String DATABASE_NAME = "android.db";
  private static final String TABLE_NAME = "TAB_WORKSCPE";
  private static final int DATABASE_VERSION = 1; 
  private final Context mCtx;


  public ComponentsDbAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
  }

  private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_PATH+DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null); 
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
  }

  public ComponentsDbAdapter(Context ctx) {
    this.mCtx = ctx;
  }

  public void close() {
    if (mDbHelper != null) {
        mDbHelper.close();
    }
 }

  public Cursor fetchComponentsByName(String inputText) throws SQLException {
    Log.w(TAG, inputText);
    Cursor mCursor = null;
    if (inputText == null  ||  inputText.length () == 0)  {
        mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null); 
} else {
    mCursor = mDb.query(true, TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, COLUMN_TYPE + " like '%" + inputText + "%'", null, null, null, null, null);
}
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor; 
}

public Cursor fetchAllComponents() {
    Cursor mCursor = mDb.query(TABLE_NAME, new String[] {COLUMN_ID, COLUMN_SUBSTRUCTURE, COLUMN_TYPE, COLUMN_ORDERNUM, COLUMN_INSTALLATION}, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
  }
}





public class AndroidListViewCursorAdaptorActivity extends Activity {

private ComponentsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    dbHelper = new ComponentsDbAdapter(this);
    dbHelper.open();

    //Generate ListView from SQLite Database
    displayListView();
}

private void displayListView() {
    Cursor cursor = dbHelper.fetchAllComponents();

    // The desired columns to be bound
    String[] columns = new String[] {
        ComponentsDbAdapter.COLUMN_SUBSTRUCTURE,
        ComponentsDbAdapter.COLUMN_TYPE,
        ComponentsDbAdapter.COLUMN_ORDERNUM,
        ComponentsDbAdapter.COLUMN_INSTALLATION
    };

    // the XML defined views which the data will be bound to
    int[] to = new int[] {
        R.id.inst,
        R.id.subdt,
        R.id.type,
        R.id.ordernum,
    };

    // create the adapter using the cursor pointing to the desired data
    //as well as the layout information
    dataAdapter = new SimpleCursorAdapter(
        this, 
        R.layout.country_info,
        cursor,
        columns,
        to,
        0);

    ListView listView = (ListView) findViewById(R.id.listView1);
    // Assign adapter to ListView
    listView.setAdapter(dataAdapter);


    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> listView, View view,
            int position, long id) {
            // Get the cursor, positioned to the corresponding row in the result set
            Cursor cursor = (Cursor) listView.getItemAtPosition(position);

            // Get the state's capital from this row in the database.
            String compSubdt = cursor.getString(cursor.getColumnIndexOrThrow("subdt"));
            Toast.makeText(getApplicationContext(), compSubdt, Toast.LENGTH_SHORT).show();
        }
    });

    EditText myFilter = (EditText) findViewById(R.id.myFilter);
    myFilter.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start,int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start,int before, int count) {
            dataAdapter.getFilter().filter(s.toString());
        }
    });

    dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return dbHelper.fetchComponentsByName(constraint.toString());
        }
    });
 }
 }

解决方案

Ok, this took me almost week and a lot of stress but here is the solution. I started to go through a lot of tutorials and got it working in this one:

http://www.mysamplecode.com/2012/11/android-database-content-provider.html

I extracted the database from the virtual device and manually added more data. Then copied the database to the desired folder on my device folder (Its just to make sure the database consistency/columns are exactly the same). Then changed MyDatabaseHelper class as follows:

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/MYFOLDER/";
    private static final String DATABASE_NAME = "TheWorld.db";
    private static final int DATABASE_VERSION = 1;

    MyDatabaseHelper(Context context) {
        super(context, DATABASE_PATH+DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        CountriesDb.onCreate(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        CountriesDb.onUpgrade(db, oldVersion, newVersion);
    }
}

Don't forget to add permissions to your manifest:

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Done! If you read through the posts above the answer is based on Kirks advice so reading his recommended link helps. I still have more tests to do just in case my database structure was wrong before.

这篇关于SimpleCursorAdapter不加载外部SQLite数据库:&QUOT; _id&QUOT;错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆