Android APP数据库连接

时间:2012-11-11 12:43:53

标签: android database

我想用“openOrCreateDatabase”创建一个SQLLite数据库。问题是,我在创建新表时遇到错误。

11-11 12:36:39.865: E/AndroidRuntime(1520): java.lang.IllegalStateException: 
database not open

这是我的代码:

public class MainActivity extends Activity {

EditText playerName;
Button submitPlayer;
SQLiteDatabase myDB = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    playerName = (EditText)findViewById(R.id.playerName);
    submitPlayer = (Button)findViewById(R.id.submitPlayer);


        myDB = SQLiteDatabase.openOrCreateDatabase("/data/data/com.my.appname/mydb.db",null);           
  try{          

        myDB.execSQL("CREATE TABLE IF NOT EXISTS player (playername VARCHAR)");         
        myDB.execSQL("INSERT INTO player VALUES('test')");

EditText playerName; Button submitPlayer; SQLiteDatabase myDB = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); playerName = (EditText)findViewById(R.id.playerName); submitPlayer = (Button)findViewById(R.id.submitPlayer); myDB = SQLiteDatabase.openOrCreateDatabase("/data/data/com.my.appname/mydb.db",null); try{ myDB.execSQL("CREATE TABLE IF NOT EXISTS player (playername VARCHAR)"); myDB.execSQL("INSERT INTO player VALUES('test')");

我在清单中添加了2行:

< permission-group android:name =“android.permission-group.STORAGE”>

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

怎么了?

非常感谢!

1 个答案:

答案 0 :(得分:2)

您不应该像这样访问您的数据库。而且你不需要/ data / data的存储权限,那就是sdcard。 你应该做的是使用SQLiteOpenHelper来管理你的数据库。这是一个tutorial,可以帮助您入门