无法使用android中的数据库中的现有表实现搜索

时间:2014-07-15 12:37:00

标签: android

我正在尝试对用户输入实施搜索。搜索相关选项后,将显示搜索结果。

我已经使用此方法显示结果

public Cursor getBooksBySearch(String query) {
    // TODO Auto-generated method stub

String[] args={query};

return(getReadableDatabase().rawQuery("SELECT _id,chapter FROM chapters  WHERE chapter LIKE '%" + query + "%", args));
 }

此处查询来自活动SearchResultAcitvity.java

 Intent intent = getIntent();
 if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
  String query = intent.getStringExtra(SearchManager.QUERY);


    ListView myListView = (ListView)findViewById(R.id.txt_query);
    dbBookHelper = new BooklistHelper(this);
    ourCursor = dbBookHelper.getBooksBySearch(query);
    startManagingCursor(ourCursor);
    adapter = new BookAdapter(ourCursor);
    myListView.setAdapter(adapter);
    myListView.setOnItemClickListener(onListClick);
   }  

我想匹配这个即将到来的查询字符串,以从我的章节表中获取结果。 我可以将String query = intent.getStringExtra(SearchManager.QUERY)中的查询字符串与我数据库中的数据进行匹配。 使用列表视图显示。

请帮帮我。 如果您想了解更多信息,请告诉我

提前致谢:)

1 个答案:

答案 0 :(得分:0)

这将按关键字

返回数据搜索列表
    public ArrayList<ObjectType> getSearchData(String keyword)
    {
    ArrayList<ObjectType> objectTypeList = new ArrayList<ObjectType>();
    SQLiteDatabase db = getWritableDatabase();

        String checkEntry="SELECT id,firstname,lastname FROM abc_table  WHERE firstname like  '%"+ keyword +"%'" +" or "+ "p.lastname like  '%"+ keyword +"%'";

        Cursor cursor = db.rawQuery(checkEntry, null);
        try
        {
            //If entry exist then update 
            if (cursor.moveToFirst()) 
            {
                do
                {
                    ObjectType objectType = new  ObjectType();
                    int PID=cursor.getInt(0);
                    String fname = cursor.getString(1);
                    String LastName = cursor.getString(2);


                    objectType.setFirstName(fname);
                    objectType.setLastName(LastName);

                    objectTypeList.add(objectType);

                }
                while(cursor.moveToNext());
            }
        }
        finally
        {
            if(cursor != null)

                cursor.close();
        }

    return objectTypeList;
}

ObjectType是类

    public class ObjectType {

int id;
String firstName;
String lastName;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}

} 希望这会帮助你.. :)