Java Android Studio SQL(查询)错误或缺少数据库。没有这样的桌子
我知道这是一个常见的问题,但我在网上找不到解决方案。我正在尝试使用SQLiteOpenHelper类在androidstudio中创建一个简单的数据库。以下是代码:Java Android Studio SQL(查询)错误或缺少数据库。没有这样的桌子,java,android-studio,sqliteopenhelper,Java,Android Studio,Sqliteopenhelper,我知道这是一个常见的问题,但我在网上找不到解决方案。我正在尝试使用SQLiteOpenHelper类在androidstudio中创建一个简单的数据库。以下是代码: public class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context){ super(context, "Data.db", null, 1); } @Override public void o
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context){
super(context, "Data.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase DB){
DB.execSQL("CREATE TABLE IF NOT EXISTS Names(first_name TEXT PRIMARY KEY, last_name TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1){
DB.execSQL("CREATE TABLE IF NOT EXISTS Names(first_name TEXT PRIMARY KEY, last_name TEXT);");
}
public Boolean insert_new_name(String name){
String[] new_name = name.split(" ");
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("first_name", new_name[0]);
contentValues.put("last_name", new_name[1]);
long result = DB.insert("Names", null, contentValues);
if (result==-1){
return false;
}else {
return true;
}
}
}
`
以下是我主要活动的代码:
public class MainActivity extends AppCompatActivity {
EditText name_entry;
List list_of_names = new ArrayList();
ListView list_display;
ListAdapter adapter;
Button add_button;
DBHelper DB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB= new DBHelper(this);
name_entry = findViewById(R.id.name);
list_display = findViewById(R.id.list_display);
adapter = new ArrayAdapter (MainActivity.this, android.R.layout.simple_expandable_list_item_1, list_of_names);
list_display.setAdapter(adapter);
add_button = findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Boolean check_insert = DB.insert_new_name(name_entry.getText().toString());
if (check_insert == true){
Toast.makeText(MainActivity.this, "New Entry Inserted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "New Entry NOT Inserted", Toast.LENGTH_SHORT).show();
}
}
});
}}
无论我做了什么尝试,我总是得到“错误代码:1(SQLITE_错误)
原因:SQL(查询)错误或缺少数据库。
(没有这样的表:名称(代码1):,编译时:插入到名称(名字,姓氏)值(?,)”错误
非常感谢您的帮助