在使用Android studio尝试进行SQLite有关的查找功能时,我点击查找按钮就会出现闪退的情况,用爬虫逐步运行了按钮单击事件方法,运行到方法末尾也没有出现问题。我把相关代码复制在下面。
这是MainActivity的代码
private Datebase datebase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datebase = new Datebase(MainActivity.this,"dictionary.db",null,1);
final EditText edt_word = (EditText)findViewById(R.id.edt_word);
final ListView lst_trans = (ListView)findViewById(R.id.lst_trans);
Button btn_find = (Button)findViewById(R.id.btn_find);
btn_find.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//插入测试数据
ContentValues values = new ContentValues();
values.put("word","apple");
values.put("translation","苹果");
datebase.getReadableDatabase().insert("dictionary",null,values);
//查询测试数据
String key = edt_word.getText().toString();
Cursor cursor = datebase.getReadableDatabase().query("dictionary",null,"word = ?", new String[]{key},null,null,null);
ArrayList<Map<String, String>> result = new ArrayList<Map<String, String>>();
while(cursor.moveToNext())
{
Map<String,String> map = new HashMap<String, String>();
map.put("word",cursor.getString(1));
map.put("interpret",cursor.getString(2));
result.add(map);
}
if(result == null || result.size() == 0) {
Toast.makeText(MainActivity.this,"没有相关记录",Toast.LENGTH_LONG).show();
}else {
SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, result,
R.layout.activity_main,
new String[]{"word", "interpret"}, new int[]{
R.id.lst_trans});
lst_trans.setAdapter(simpleAdapter);
}
}
});
}
protected void onDestroy() {
super.onDestroy();
if(datebase != null){
datebase.close();
}
}
这是自己创建的SQLiteOpenHelper的子类
public class Datebase extends SQLiteOpenHelper {
final String CREATE_TABLE_SQL = "create table dictionary( id integer primary key autoincrement, word varchar(255), translation varchar(255))";//创建SQL数据表的语句
public Datebase(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_SQL);//创建数据表
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("数据库","版本更新"+oldVersion+"->"+newVersion);
}
}
都是跟着网上自学的,可能有些地方看起来别扭,希望大佬们能指出来