我正在android studio中创建SQLite数据库...在数据库中,我有1表3行(int id, varchar nama_obat, varchar deskripsi_obat
)。我想尝试获取特定行(deskripsi_obat)中的数据,另一行(nama_obat
)作为搜索字符串。我不能使用id,因为它需要从字符串中获取数据作为搜索...
问题是我不知道为什么当我尝试运行功能getFromDB()
任何帮助或可能的错误代码时,我的应用为什么会强制关闭吗?
(ps:我正在尝试发布有关数据库SQLite的部分代码,我的整个代码包括Google Vision API,Google Custom Search API等)
MainActivity.java
的代码
public class MainActivity extends AppCompatActivity {
DBHelper mydb;
TextView t1;
TextView t2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.textView2);
t2 = (TextView)findViewById(R.id.textView3);
}
public void getFromDB(){
final String searchString = t1.getText().toString();
mydb = new DBHelper(this);
Cursor rs = mydb.getData(searchString);
if(rs != null){
rs.moveToFirst();
String result = rs.getString(rs.getColumnIndex(DBHelper.OBAT_COLUMN_DESC));
t2.setText(result);
}
else{
Toast.makeText(this, "Ga dapat database!", Toast.LENGTH_SHORT).show();
}
}
DBHelper.java的代码
package com.example.asus.googleocr;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "db_obat";
public static final String OBAT_TABLE_NAME = "tb_obat";
public static final String OBAT_COLUMN_ID = "_id";
public static final String OBAT_COLUMN_NAME = "nama_obat";
public static final String OBAT_COLUMN_DESC = "deskripsi_obat";
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table IF NOT EXISTS "+OBAT_TABLE_NAME+ "(_id integer primary key AUTOINCREMENT, nama_obat VARCHAR (255),deskripsi_obat VARCHAR (255))");
db.execSQL("INSERT INTO " +OBAT_TABLE_NAME+ "(nama_obat, deskripsi_obat) VALUES ('Procold Flu', 'Obat untuk batuk dan pilek')");
db.execSQL("INSERT INTO " +OBAT_TABLE_NAME+ "(nama_obat, deskripsi_obat) VALUES ('BETADINE', 'Obat untuk luka pada kulit')");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS tb_obat");
onCreate(db);
}
public Cursor getData(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from" + OBAT_TABLE_NAME + "where nama_obat="+name+"", null );
return res;
}
}