无法打开数据库android Sqlite

时间:2014-02-07 09:02:04

标签: android android-sqlite

您好我开始学习android我试过这段代码。它显示无法打开数据库,如果我的创建错误,我的路径是否正确。请任何人都可以帮忙

            public class Sql3Activity extends Activity 
                {


    public static final String TAG = "DatabaseHelper";

    public static final String DATABASE_NAME = "mydb";
    public static final String TRACKS_TABLE = "tracks";
    public static final String TRACK_INFO_TABLE = "track_info";

    public final String TRACKS_TABLE_CREATE = "create table " + TRACKS_TABLE
            + " (_id integer primary key autoincrement, title text not null, description text null, created_at date not null);";

    public static final String TRACK_INFO_TABLE_CREATE = "create table "
            + TRACK_INFO_TABLE
            + " (_id integer primary key autoincrement, track_id integer not null, latitude real not null, longitude real not null, altitude real not null, created_at date not null);";


    public SQLiteDatabase database;



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

     final String DATABASE_FILE_PATH = Environment.getExternalStorageDirectory()+"/test";

    Toast.makeText(Sql3Activity .this,DATABASE_FILE_PATH,Toast.LENGTH_LONG).show();
     try{
     database = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH + File.separator + DATABASE_NAME, null, SQLiteDatabase.OPEN_READWRITE);
     Toast.makeText(Sql3Activity .this,"Database Open",Toast.LENGTH_LONG).show();
     }catch(Exception e)
     {
         Toast.makeText(Sql3Activity .this,"ERROR"+e,Toast.LENGTH_LONG).show(); 
     }

2 个答案:

答案 0 :(得分:0)

要在外部存储上读取或写入文件,您的应用必须获得READ_EXTERNAL_STORAGEWRITE_EXTERNAL_STORAGE系统权限。

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

答案 1 :(得分:0)

这段代码很有用 首先,create class扩展了SQLiteOpenHelper并更改了db文件路径

class test extends SQLiteOpenHelper {

    public test(Context context) {
        super(context, "/sdcard/Download/123.db", null, SQLite.DATABASE_VERSION);
    }

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

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

并使用Cursor获取数据

test t = new test(this);
    Cursor cur = t.getWritableDatabase().rawQuery("SELECT * FROM COMPANY", null);
    while (cur.moveToNext()) {
        Log.i("chauster", ""+cur.getString(1));
    }
cur.close();
t.close();