gpt4 book ai didi

java - this.getWritableDatabase() 导致我的 Android 应用程序停止

转载 作者:行者123 更新时间:2023-12-02 12:15:37 24 4
gpt4 key购买 nike

我是 Android SQLite 数据库新手,在执行 this.getWritableDatabase() 时我的应用程序停止了。这个问题有什么解决办法吗?我的数据库是关于获取学生信息并将他们的分数保存在数据库中。

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME="Dictionary.db";
public static final String TABLE_NAME="Dictionary_data";
public static final String COL_1="ID";
public static final String COL_2="Name";
public static final String COL_3="SURNAME";
public static final String COL_4="MARKS";

public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE"+ TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
onCreate(db);
}

public boolean insert_data(String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
long result = db.insert(TABLE_NAME,null,contentValues);

if(result==-1)
return false;
else
return true;
}
}

还有我的mainActivity类:

public class MainActivity extends AppCompatActivity {

DatabaseHelper myDB;
EditText editName,editSurname,editMark;
Button btn_add_data;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this.getApplicationContext());

editName = (EditText)findViewById(R.id.namespace);
editSurname = (EditText)findViewById(R.id.surnamespace);
editMark = (EditText)findViewById(R.id.markspace);
btn_add_data = (Button)findViewById(R.id.add_button);
addData();
}

public void addData(){
btn_add_data.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean id_inserted = myDB.insert_data(editName.getText().toString(),editSurname.getText().toString(),editMark.getText().toString());

if(id_inserted)
Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}

最佳答案

创建表时出错

db.execSQL("CREATE TABLE"+ TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");

请在TABLE后添加空格

db.execSQL("CREATE TABLE "+ TABLE_NAME+ " (ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");

还添加 log cat 以获取更多详细信息,我无法发表评论,因为这是我的新帐户。

关于java - this.getWritableDatabase() 导致我的 Android 应用程序停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46200852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com