简体   繁体   中英

using SQLiteAssetHelper

MyDatabase class

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class Mydatabase extends SQLiteAssetHelper{

    private static final String DATABASE_NAME = "databases/mydb.db";
    private static final int DATABASE_VERSION = 1;

    public Mydatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public Cursor getEmployees() {

        SQLiteDatabase db = getReadableDatabase();
        SQLiteQueryBuilder  qb = new SQLiteQueryBuilder();

        String [] sqlSelect = {"_id", "name", "email"};
        String sqlTables = "contacts";

        qb.setTables(sqlTables);
        Cursor c = qb.query(db, sqlSelect, null, null,
                null, null, null);

        c.moveToFirst();
        return c;

    }

MainActivity class

public class MainActivity extends ListActivity {

    private Cursor employees;
    private MyDatabase db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        db = new MyDatabase(this);
        employees = db.getEmployees(); // you would not typically call this on the main thread

        ListAdapter adapter = new SimpleCursorAdapter(this, 
                android.R.layout.simple_list_item_1, 
                employees, 
                new String[] {"name"}, 
                new int[] {android.R.id.list});

        getListView().setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        employees.close();
        db.close();
    }

}

I want to connect a database in assets folder I try this example from GitHub but the application is stopped working

the logcate : FATAL EXCEPTION: main java.lang.IllegalStateException: Could not execute method of the activity

      Caused by: java.lang.IllegalArgumentException: File databases/mydb.db contains a path separator

any help please thanks

I have just got my database working but I did not reference the database as

   private static final String DATABASE_NAME = "databases/mydb.db";

I access it as follows:

  private static final String DATABASE_NAME = "mydb.db";

I just tested your way and sure enough it breaks it. So remove the database/ and just have mydb.db and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM