Android:如何在sqlite数据库中搜索数据并将其显示在listview中

时间:2015-03-27 02:59:26

标签: android android-listview android-sqlite

如何通过使用EditText搜索或者过滤它,从我的数据库中显示ListView中的数据。你能告诉我需要做什么代码吗我想我错过了什么因为我的代码不搜索它只是将我的数据显示为ListView。任何帮助将不胜感激。

以下是我的代码:

DBListHelper

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;

class DBlistHelper extends SQLiteOpenHelper {


private static final String DATABASE_PATH = "/data/data/com.example.searching/databases/";
private static final String DATABASE_NAME = "LPG.db";
private static final int SCHEMA_VERSION = 1;
private static final String TABLE_NAME = "Recipes";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_RECIPE = "Recipe";
public static final String COLUMN_INGRIDIENTS = "Ingredients";
//public static final String COLUMN_PROCEDURE = "procedure";



public SQLiteDatabase dbSqlite;

private final Context myContext;

public DBlistHelper(Context context){
    super(context, DATABASE_NAME, null, SCHEMA_VERSION );
    this.myContext= context;

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public void createDatabase() {

    createDB();

}

public void createDB(){

    boolean dbExist = DBExists();

    if(!dbExist){

        this.getReadableDatabase();

        copyDBFromResource();

    }

}



private boolean DBExists() {

    SQLiteDatabase db = null;

    try{
        String databasePath = DATABASE_PATH + DATABASE_NAME;
        db = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);
        db.setVersion(1);

    } catch (SQLiteException e) {

        Log.e("SqlHelper", "database not found");
    }

    if (db != null){

        db.close();
    }

    return db != null ? true : false;

}



private void copyDBFromResource(){

    InputStream inputStream = null;
    OutputStream outStream = null;
    String dbFilePath =  DATABASE_PATH + DATABASE_NAME;

    try{

        inputStream = myContext.getAssets().open(DATABASE_NAME);

        outStream = new FileOutputStream(dbFilePath);

        byte [] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0){
            outStream.write(buffer, 0, length);

        }

        outStream.flush();
        outStream.close();
        inputStream.close();

    } catch (IOException e){

        throw new Error("Problem copying database from resource file.");
    }

}


public void openDatabase () throws SQLException {

    String myPath = DATABASE_PATH + DATABASE_NAME;
    dbSqlite = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}

@Override
public synchronized void close () {

    if (dbSqlite !=null){

        dbSqlite.close();
    }

    super.close();

}

public Cursor getCursor() {

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder ();

    queryBuilder.setTables(TABLE_NAME);

    String [] asColumnsToReturn = new String [] { COLUMN_ID, COLUMN_RECIPE, COLUMN_INGRIDIENTS};

    Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null, null, null, null, "Recipe ASC");

    return mCursor;
}

public String getName (Cursor c){
    return(c.getString(1));


}

}

Main.java

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;


public class Main extends Activity {

private DBlistHelper dbrecipelistHelper = null;
private Cursor ourCursor = null;
private recipeAdapter adapter = null;

EditText inputSearch = null;


@Override
protected void onCreate(Bundle savedInstanceState) {    
    try
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    inputSearch = (EditText) findViewById(R.id.inputSearch);

    ListView myListView = (ListView) findViewById(R.id.listView);


    dbrecipelistHelper = new DBlistHelper(this);

    dbrecipelistHelper.createDatabase();

    dbrecipelistHelper.openDatabase();

    ourCursor=dbrecipelistHelper.getCursor();

    startManagingCursor(ourCursor);

    adapter = new recipeAdapter(ourCursor);

    myListView.setAdapter(adapter);


    //myListView.setOnItemClickListener(onListClick);

    }
    catch (Exception e)
    {

        Log.e("ERROR", "ERROR IN CODE: " + e.toString());   

        e.printStackTrace();

    }



    inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            Main.this.adapter.getFilter().filter(cs);   
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub                          
        }
    });




}


class recipeAdapter extends CursorAdapter {

    recipeAdapter(Cursor c){
        super(Main.this, c);
    }

    @Override
    public  void bindView (View row, Context ctxt, Cursor c)
    {
        recipeHolder holder = (recipeHolder)row.getTag();
        holder.populateFrom(c, dbrecipelistHelper);
    }
    @Override
    public  View newView(Context ctxt, Cursor c, ViewGroup parent)
    {
        LayoutInflater inflater = getLayoutInflater();
        View row=inflater.inflate(R.layout.list, parent, false);
        recipeHolder holder = new recipeHolder(row);
        row.setTag(holder);
        return(row);
    }


}

static class recipeHolder {
    private TextView name=null;

    recipeHolder(View row){
        name=(TextView)row.findViewById(R.id.recipeText);
    }

    void populateFrom(Cursor c, DBlistHelper r){
        name.setText(r.getName(c));
    }

}
}

2 个答案:

答案 0 :(得分:1)

要搜索值定义编辑文本并在数据库中实现文本观察器,请输入如下所示的查询:

 editText.addTextChangedListener(new TextWatcher(){ 

Cursor cusror;

cursor=db.rawQuery("SELECT * FROM "+ DB_NAME + " WHERE " 
                + DB_NAME.id + " = " + DB_NAME.Id + " AND " + DB_NAME.Title +
                 " LIKE  '"+search.getText()+"%'");

检查值,如果获得正确的值,则返回光标。 希望能帮助到你。

答案 1 :(得分:0)

由于游标从正在搜索的数据库中返回行数,因此您可以在游标对象上使用.getCount()来检查是否找到了数据。

这将是我的方法。

public Cursor fetchData(String arg1){


        SQLiteDatabase database = getReadableDatabase();

        Cursor cursor = database.query(TABLE_NAME, new String[]{COL1,COL2},COL1 + "=?",new String[]{arg1},null,null,null );
        return cursor;
    }

并在MainActivity类

MyDatabase myDatabase = new MyDatabase(getApplicationContext());
Cursor cursor = myDatabase.fetchData("FRANCE");

if(cursor.getCount()>0)
            Toast.makeText(this, "Not Found", Toast.LENGTH_SHORT).show();