在android中使用现有数据库

时间:2012-10-27 06:24:47

标签: android android-sqlite forceclose

我已经编写了这段代码,用于在android中使用现有的数据库。

我拥有的是:

  • 数据库:测试
  • table:t1

我已将我的数据库保存在asset文件夹中,如果我运行我的项目,则会给我force-close错误。

我哪里错了?

public class BDAdapter extends SQLiteOpenHelper {
     private Context mycontext;
int id=0;
        private String DB_PATH = "data/data/com.example.dd9/databases/";
        private static String DB_NAME = "test.sqlite";
     //   public static final String KEY_ROWID = "_id";
        public static final String KEY_QUOTE = "name";
        private static final String DATABASE_TABLE = "t1";
        private static final String TAG = "BDAdapter";
        private static final String DATABASE_CREATE =
                "create table t1 ( "
                + "name text not null );";

        private SQLiteDatabase db;



        public BDAdapter(Context context) {
            super(context, DB_NAME, null, 1);
            this.mycontext = context;
            boolean dbexist = checkdatabase();
            if (dbexist) {
            } else {
                System.out.println("Database doesn't exist");
                try {
                    createdatabase();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

        public void createdatabase() throws IOException {
            boolean dbexist = checkdatabase();
            if (dbexist) {
            } else {
                this.getReadableDatabase();
                try {
                    copydatabase();
                } catch (IOException e) {
                    throw new Error("Error copying database");
                }
            }
        }

        private boolean checkdatabase() {
            boolean checkdb = false;
            try {
                String myPath = DB_PATH + DB_NAME;
                File dbfile = new File(myPath);
                checkdb = dbfile.exists();
            } catch (SQLiteException e) {
                System.out.println("Database doesn't exist");
            }

            return checkdb;
        }

        private void copydatabase() throws IOException {

            // Open your local db as the input stream
            InputStream myinput = mycontext.getAssets().open(DB_NAME);

            // Path to the just created empty db
            @SuppressWarnings("unused")
            String outfilename = DB_PATH + DB_NAME;

            // Open the empty db as the output stream
            OutputStream myoutput = new FileOutputStream(
                    "data/data/com.example.dd9/databases/test.sqlite");

            // transfer byte to inputfile to outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myinput.read(buffer)) > 0) {
                myoutput.write(buffer, 0, length);
            }

            // Close the streams
            myoutput.flush();
            myoutput.close();
            myinput.close();

        }

        public void open() {
            // Open the database
            String mypath = DB_PATH + DB_NAME;
            myDataBase = SQLiteDatabase.openDatabase(mypath, null,
                    SQLiteDatabase.OPEN_READWRITE);

        }

        public synchronized void close() {
            myDataBase.close();
            super.close();
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(DATABASE_CREATE);

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS t1");
            onCreate(db);


        }

        public long insertQuote(String Quote) 
        {
            ContentValues initialValues = new ContentValues();
            initialValues.put(KEY_QUOTE, Quote);
            return db.insert(DATABASE_TABLE, null, initialValues);
        }

        public int getAllEntries() 
        {
            Cursor cursor = db.rawQuery(
                        "SELECT COUNT(name) FROM t1", null);
                    if(cursor.moveToFirst()) {
                        return cursor.getInt(0);
                    }
                    return cursor.getInt(0);

        }

        public String getRandomEntry() 
        {

            id = getAllEntries();
            Random random = new Random();
            int rand = random.nextInt(getAllEntries());
            if(rand == 0)
                ++rand;
            Cursor cursor = db.rawQuery(
                      "SELECT name FROM t1 ", null);
                    //"SELECT * FROM tblRandomQuotes",null);
                    if(cursor.moveToFirst()) {
                        return cursor.getString(0);

                    }
                    return cursor.getString(0);

        }

        public Cursor getAllTitles() 
        {
            return db.query(DATABASE_TABLE, new String[] {

                    KEY_QUOTE,
                    }, 
                    null, 
                    null, 
                    null, 
                    null, 
                    null);
        }


}



//---------------------------Main class------------------------

public class MainActivity extends Activity
{
    BDAdapter db = new BDAdapter(this);
    EditText name;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Capture our button from layout
        Button setButton = (Button)findViewById(R.id.go);
        Button getButton = (Button)findViewById(R.id.genRan);
        // Register the onClick listener with the implementation above
        setButton.setOnClickListener(mAddListener);
        getButton.setOnClickListener(mAddListener);
    }

    // Create an anonymous implementation of OnClickListener
    private OnClickListener mAddListener = new OnClickListener() 
    {
        public void onClick(View v) 
        {
            switch(v.getId())
            {
            case R.id.go:
                db.open();
                long id = 0;
                // do something when the button is clicked
                try
                {
                    name = (EditText)findViewById(R.id.Quote);
                    db.insertQuote(name.getText().toString());


                    id = db.getAllEntries();

                    Context context = getApplicationContext();
                    CharSequence text = "The quote '" + name.getText() + "' was added successfully!\nQuotes Total = " + id;
                    int duration = Toast.LENGTH_LONG;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                    name.setText("");
                }
                catch (Exception ex)
                {
                    Context context = getApplicationContext();
                    CharSequence text = ex.toString() + "ID = " + id;
                    int duration = Toast.LENGTH_LONG;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }

                db.close();
                break;
            case R.id.genRan:
                db.open();
                //long id1 = 0;
                // do something when the button is clicked
                try
                {
                    //String quote = "";
                    //quote = db.getRandomEntry();
                    //Context context = getApplicationContext();
                    //CharSequence text = quote;
                    //int duration = Toast.LENGTH_LONG;

                    //Toast toast = Toast.makeText(context, text, duration);
                    //toast.show();

                     db.open();
                        Cursor c = db.getAllTitles();
                       if (c.moveToFirst())
                       {
                          do {          
                                DisplayTitle(c);
                            } while (c.moveToNext());
                       }
                        db.close();


                }
                catch (Exception ex)
                {
                    Context context = getApplicationContext();
                    CharSequence text = ex.toString();
                    int duration = Toast.LENGTH_LONG;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }
                db.close();
            }
        }

    };
    public void DisplayTitle(Cursor c)
    {
        Toast.makeText(this, 
                "NAME: " + c.getString(0) + "\n" ,


                Toast.LENGTH_LONG).show();        
    } 


}

1 个答案:

答案 0 :(得分:0)

试试这个:

public class DBHelper extends SQLiteOpenHelper {

private static String TAG = "DBHelper";
private static boolean DEBUG = true;

private static String PKG;
private static final String DB_NAME="C&EN.sqlite";
private Context mContext;

private static DBHelper instance;

public static DBHelper getInstance(Context ctx){
    if(instance == null || !ctx.equals(instance.mContext)){
        instance = new DBHelper(ctx);
    }
    return instance;

}

private DBHelper(Context context) {

    super(context, DB_NAME, null,2);

    mContext = context;

    PKG= context.getPackageName();
    InputStream iStream;
    FileOutputStream fos;
    File file=new File("/data/data/"+PKG+"/databases/"+DB_NAME);
    if(!file.exists()){
        if(DEBUG)Log.i(TAG, "COPYING DATABASE TO PRIVATE FOLDER");
        try {
            iStream=context.getAssets().open(DB_NAME);
            new File("/data/data/"+PKG+"/databases").mkdirs();
            fos=new FileOutputStream(file);

            byte[] bte =new byte[1024];
            while(iStream.read(bte)!=-1){
                fos.write(bte);
            }
            iStream.close();
            fos.close();
        } catch (IOException e) {
            if(DEBUG)Log.i(TAG, "ERROR COPYING THE DATABASE");

        }
        if(DEBUG)Log.i(TAG, "DATABASE SUCCESSFULLY COPIED TO PRIVATE FOLDER");
    }

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

}