Here is the UI after input keyword
您好,我是Android新手,我已阅读了很多教程,但他们从代码中编写了数据库手册。我想在应用程序中创建搜索功能,从sqlite数据库中检索数据。
我使用MainDIY搜索活动。
MainDIY.java
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import timber.log.Timber;
public class MainDIY extends ActionBarActivity implements OnItemClickListener, SearchView.OnQueryTextListener, SearchView.OnCloseListener{
public static final String KEY_ID = "_id";
private static final int INSERT_ID = Menu.FIRST;
private DBAdapter db;
FloatingActionButton fab;
ListView listview;
private MyAdapter defaultAdapter;
private ArrayList<String> daftarData;
//private ArrayList<String> arraylist=new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diy);
Timber.d("line 37, content activity_diy");
db = new DBAdapter(this);
db.open();
//populate list
/**
daftarData = new ArrayList<String>();
nameList.add("Apples");
nameList.add("Oranges");
nameList.add("Grapes");
nameList.add("Pineapples");
nameList.add("Mangoes");
nameList.add("Watermelons");
nameList.add("Strawberries");
nameList.add("Bananas");
nameList.add("Apricots");
nameList.add("Olives");
nameList.add("Peaches");
nameList.add("Jackfruits");
for (int i = 0; i < 6
; i++) {
daftarData.add("Diana" + i);
}
//defaultAdapter = new MyAdapter(MainDIY.this, daftarData);
//listview.setAdapter(defaultAdapter);
defaultAdapter = new MyAdapter(DIY.this, nameList);*/
listview = (ListView) findViewById(R.id.list);
listview.setEmptyView(findViewById(R.id.empty));
listview.setOnItemClickListener(this);
hasilDataTersimpan();
// float button
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainDIY.this, AddDIY.class);
startActivity(intent);
}
});
//List<DataDIY> contacts = db.getAllContact();
// for (DataDIY cn : contacts) {
// String log = "Name: " + cn.getName() ;
// Writing Contacts to log
// Log.d("Name: ", log);
//}
// Create the list of names which will be displayed on search
//for (String id: nameList) {
// mDbAdapter.createContact(DataDIY);}
}
// menampilkan apa yang dicari dan ada di database
private void hasilPencarian(String query) {
/** */
Cursor cursor = db.searchByInputText((query != null ? query : "@@@@"));
String[] from = new String[]
{
DBAdapter.COL_NAME
};
int[] to = new int[]
{
R.id.txtName
};Log.d("MainActivity","mencari dan memakai id list item");
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.list_adapter, cursor, from, to); // atu list
Log.d("MainActivity","mencari dan memakai id list item");
listview.setAdapter(cursorAdapter);
// TODO Auto-generated method stub
//Cursor cur = db.getAllContact();
//listview Click listener
/** listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = (Cursor) listview.getItemAtPosition(position);
String selectedName = cursor.getString(cursor.getColumnIndexOrThrow("name"));
Toast.makeText(DIY.this, selectedName, 0).show();
listview.setAdapter(defaultAdapter);
for (int pos = 0; pos < nameList.size(); pos++) {
if (nameList.get(pos).equals(selectedName)){
position = pos;
break;
}
}
Handler handler = new Handler();
final int finalPosition = position;
handler.post(new Runnable() {
@Override
public void run() {
listview.setSelection(finalPosition);
}
});
searchView.setQuery("",true);
}
}); */
}
// menampilkan data" yang tersimpan
private void hasilDataTersimpan() {
/** Load database setelah mengklik gambar tugu diy*/
// TODO Auto-generated method stub
Cursor cur = db.getAllContact();
String[] from = new String[]
{
DBAdapter.COL_NAME
};
int[] to = new int[]
{
R.id.txtName
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_adapter, cur, from, to);
listview.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()){
hasilPencarian(newText + "*");
Timber.i("text berubah "+newText.toString());
} else {
hasilDataTersimpan();
Timber.i("searchview kosong");
}
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
hasilPencarian(query + "*");
Log.d("MainActivity", "mencari di onQueryTextSubmit " + query.toString());
return false;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
@Override
public void onItemClick(AdapterView<?> arg0, View v, int pos, long id)
{
// TODO Auto-generated method stub
Bundle bundle = new Bundle();
bundle.putLong(KEY_ID, id);
Intent intent = new Intent(MainDIY.this, EditDIY.class);
intent.putExtras(bundle);
db.close();
startActivity(intent);
}
@Override
public boolean onClose() {
Timber.d("onclose");
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
hasilPencarian(query + "*");
Log.d("MainActivity", "mencari di onQueryTextSubmit " + query.toString());
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()){
hasilPencarian(newText + "*");
Timber.i("text berubah "+newText.toString());
} else {
hasilDataTersimpan();
Timber.i("searchview kosong");
}
return false;
}
/** public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()){
hasilPencarian(newText + "*");
Timber.d("onquerytextchange = "+ newText.toString());
} else {
myList.setAdapter(defaultAdapter);
}
return false;
} */
@Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
@Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search
}
}
}
DataDIY.java
public class DataDIY
{
private int id;
private String name;
private String telp;
private String kata;
public DataDIY()
{
// TODO Auto-generated constructor stub
}
public DataDIY(String name, String telp, String kata)
{
super();
this.name = name;
this.telp = telp;
this.kata = kata;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getTelp()
{
return telp;
}
public void setTelp(String telp)
{
this.telp = telp;
}
public String getKata()
{
return kata;
}
public void setKata(String kata)
{
this.kata = kata;
}
}
DBAdapter.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class DBAdapter
{
private static final String DB_NAME = "contact_db";
private static final int DB_VER = 1;
public static final String FTS_VIRTUAL_TABLE = "contact";
public static final String COL_ID = "_id";
public static final String COL_NAME = "name";
public static final String COL_TELP = "telp";
private static final String TAG = "ContactDBAdapter";
private DatabaseHelper dbHelper;
private SQLiteDatabase db;
private static final String DB_CREATE = "create virtual table " + FTS_VIRTUAL_TABLE+
" using fts3 (_id integer primary key, name text not null);";
private final Context context;
private static class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
// TODO Auto-generated constructor stub
super(context, DB_NAME, null, DB_VER);
}
@Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
Log.d(TAG, "upgrade DB");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
}
public DBAdapter(Context context)
{
this.context = context;
// TODO Auto-generated constructor stub
}
public DBAdapter open() throws SQLException
{
dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
dbHelper.close();
}
public void createContact(DataDIY contact)
{
ContentValues val = new ContentValues();
val.put(COL_NAME, contact.getName());
//val.put(COL_TELP, contact.getTelp());
db.insert(FTS_VIRTUAL_TABLE, null, val);
}
public boolean deleteContact(int id)
{
return db.delete(FTS_VIRTUAL_TABLE, COL_ID + "=" + id, null) > 0;
}
public Cursor getAllContact()
{
return db.query(FTS_VIRTUAL_TABLE, new String[]
{
COL_ID, COL_NAME
}, null, null, null, null, null);
}
public Cursor getSingleContact(int id)
{
Cursor cursor = db.query(FTS_VIRTUAL_TABLE, new String[]
{
COL_ID, COL_NAME
}, COL_ID + "=" + id, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
return cursor;
}
public boolean updateContact(DataDIY contact)
{
ContentValues val = new ContentValues();
val.put(COL_NAME, contact.getName());
//val.put(COL_TELP, contact.getTelp());
return db.update(FTS_VIRTUAL_TABLE, val, COL_ID + "=" + contact.getId(), null) > 0;
}
public Cursor searchByInputText(String inputText) throws SQLException {
String query = "SELECT *"
+ " from " + FTS_VIRTUAL_TABLE +
" where " + COL_NAME + " = '" + inputText+"'" ;
Log.d("DBAdapter","mencari di searchbyinputtext " + query.toString());
Cursor mCursor = db.rawQuery(query,null);
List<String[]> list = new ArrayList<String[]>();
if (mCursor != null) {
mCursor.moveToFirst();
}
Log.d("DBAdapter","melewati mCursor rawquery");
return mCursor;
}
}
告诉我我的方法是否错误。 这是另一个java in git
答案 0 :(得分:0)
尝试卸载,然后再次在您的设备中安装该应用。 因为多次在sqlite数据库中更新只会影响第一次在设备中安装应用程序。 希望它有效。
答案 1 :(得分:0)
在您的SQL查询中,您正在寻找完全匹配,但似乎您希望结果包含您键入的内容。
尝试使用LIKE
而不是=
:
public Cursor searchByInputText(String inputText) throws SQLException {
String query = "SELECT * FROM "+ FTS_VIRTUAL_TABLE +
" WHERE" + COL_NAME + " LIKE '%" + inputText + "%'";
我在两端都使用了通配符%
,但您也可以使用_
,或者根本不使用任何内容,具体取决于您所查看的内容。有关详细信息,请参阅https://www.sqlite.org/lang_expr.html。
答案 2 :(得分:0)
它可以显示..它的工作.. 对于新手想要学习CRUD和搜索SQLite本地数据库,请查看my github
谢谢你回答bfr