android - SearchView 将结果从数据库显示到 ListView

标签 android database sqlite listview searchview

我已经成功开发了一个应用程序,可以将数据插入 SQLite 数据库并在具有自定义布局和适配器的 ListView 中查看它。

但是,当我尝试制作一个根据用户输入过滤结果的 SearchView 时,我一无所获。

下面是我的代码,请指出解决方案

数据库助手

public class DbHelper extends SQLiteOpenHelper {

    public static final String DB_NAME = "homeworks.db";
    public static final int DB_VERSION = 1;

    public static final String createTaksTableQuery =
            "CREATE TABLE "+ DbInfo.TasksInfo.TABLE_NAME+"("+DbInfo.TasksInfo.taskId+
             " INTEGER PRIMARY KEY AUTOINCREMENT, "+DbInfo.TasksInfo.taskName+" NVARCHAR(255), "
                    +DbInfo.TasksInfo.taskDate+" DATE, "+DbInfo.TasksInfo.taskTime+" TIME, "+ DbInfo.TasksInfo.taskNotes+" NVARCHAR(255));";

    public static final String createNotesTableQuery =
            "CREATE TABLE "+ DbInfo.NotessInfo.TABLE_NAME+"("+DbInfo.NotessInfo.noteId+
                    " INTEGER PRIMARY KEY AUTOINCREMENT, "+DbInfo.NotessInfo.noteName+" NVARCHAR(255), "
                    +DbInfo.NotessInfo.noteDate+" DATE, "+ DbInfo.NotessInfo.noteContents+" NVARCHAR(255));";


    public DbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        Log.e("Database Operation", "Database Created / Opened...");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(createTaksTableQuery);
        Log.e("Database Operation", "Tasks Table Created ...");
        db.execSQL(createNotesTableQuery);
        Log.e("Database Operation", "Notes Table Created ...");

    }

    public void insertToTasks(String tName, String tDate, String tTime, String taskNote, SQLiteDatabase db) {

        ContentValues contentValues = new ContentValues();

        contentValues.put(DbInfo.TasksInfo.taskName, tName);
        contentValues.put(DbInfo.TasksInfo.taskDate, tDate);
        contentValues.put(DbInfo.TasksInfo.taskTime, tTime);
        contentValues.put(DbInfo.TasksInfo.taskNotes, taskNote);

        db.insert(DbInfo.TasksInfo.TABLE_NAME, null, contentValues);

        Log.e("Insertion OP", "Row inserted into Tasks Databases");
    }

    public void insertToNotes(String nName, String nDate, SQLiteDatabase db) {

        ContentValues contentValues = new ContentValues();

        contentValues.put(DbInfo.NotessInfo.noteName, nName);
        contentValues.put(DbInfo.NotessInfo.noteDate, nDate);

        db.insert(DbInfo.NotessInfo.TABLE_NAME, null, contentValues);

        Log.e("Insertion OP", "Row inserted into Notes Databases");
    }


    public Cursor getTasks(SQLiteDatabase db) {
        Cursor cursor;
        String[] projections = {
            DbInfo.TasksInfo.taskId, DbInfo.TasksInfo.taskName, DbInfo.TasksInfo.taskDate, DbInfo.TasksInfo.taskTime, DbInfo.TasksInfo.taskNotes};


            cursor = db.query(DbInfo.TasksInfo.TABLE_NAME, projections, null, null, null, null, DbInfo.TasksInfo.taskId + " desc");

        return cursor;
    }

    public Cursor searchTasks(SQLiteDatabase db, String searchTxt) {
        Cursor cursor;
        String q = "select * from tasksTable where taskName Like '"+searchTxt+"%'";
        cursor = db.rawQuery(q, null);
        Log.e("Database Op", q);
        return cursor;

    }


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

    }
}

主类

public class TasksFragment extends Fragment {

ListView tasksListView;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
DbHelper dbHelper;

TasksListAdapter adapter;
SearchView searchView;
String searchQuery;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.tasks_layout, container, false);
    searchView = (SearchView) view.findViewById(R.id.searchView);
    tasksListView = (ListView) view.findViewById(R.id.tasksListView);
    adapter = new TasksListAdapter(getContext(), R.layout.tasks_row);

    dbHelper = new DbHelper(view.getContext());
    sqLiteDatabase = dbHelper.getReadableDatabase();


    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {


            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            tasksListView.setVisibility(View.GONE);
            return true;
        }
    });



    tasksListView.setAdapter(adapter);
    cursor = dbHelper.getTasks(sqLiteDatabase);


        if (cursor.moveToFirst()) {
            do {
                String name, date, time, note;
                name = cursor.getString(1);
                date = cursor.getString(2);
                time = cursor.getString(3);
                note = cursor.getString(4);

                DataProvider dataProvider = new DataProvider(name, date, time, note);

                adapter.add(dataProvider);

            } while (cursor.moveToNext());
        }
        adapter.notifyDataSetChanged();



    FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                Intent intent = new Intent(getContext(), AddTask.class);
                startActivity(intent);
        }
    });

    tasksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


        }
    });
    adapter.notifyDataSetChanged();


    return view;
}

}

最佳答案

我已经设法解决了问题... 我必须在 SearchView 上创建 onQueryTextChangedListner ,创建一个新的适配器和一个新的游标,从数据库中获取数据然后放入适配器并将新的适配器设置为 ListView

下面是新的最终代码,包含 、insert 、delete 、search"select"和 Delete ,以及 ListView 和 searchView 方法

DbHelper 类

package ly.edu.cet.www.myhomworks;

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;

/**
 * Created by newton on 11/19/15.
 */
public class DbHelper extends SQLiteOpenHelper {

    public static final String DB_NAME = "homeworks.db";
    public static final int DB_VERSION = 1;

    public static final String createTaksTableQuery =
            "CREATE TABLE "+ DbInfo.TasksInfo.TABLE_NAME+"("+DbInfo.TasksInfo.taskId+
             " INTEGER PRIMARY KEY AUTOINCREMENT, "+DbInfo.TasksInfo.taskName+" NVARCHAR(255), "
                    +DbInfo.TasksInfo.taskDate+" DATE, "+DbInfo.TasksInfo.taskTime+" TIME, "+ DbInfo.TasksInfo.taskNotes+" NVARCHAR(255));";

    public static final String createNotesTableQuery =
            "CREATE TABLE "+ DbInfo.NotessInfo.TABLE_NAME+"("+DbInfo.NotessInfo.noteId+
                    " INTEGER PRIMARY KEY AUTOINCREMENT, "+DbInfo.NotessInfo.noteName+" NVARCHAR(255), "
                    +DbInfo.NotessInfo.noteDate+" DATE, "+ DbInfo.NotessInfo.noteContents+" NVARCHAR(255));";


    public DbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        Log.e("Database Operation", "Database Created / Opened...");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(createTaksTableQuery);
        Log.e("Database Operation", "Tasks Table Created ...");
        db.execSQL(createNotesTableQuery);
        Log.e("Database Operation", "Notes Table Created ...");

    }

    public void insertToTasks(String tName, String tDate, String tTime, String taskNote, SQLiteDatabase db) {

        ContentValues contentValues = new ContentValues();

        contentValues.put(DbInfo.TasksInfo.taskName, tName);
        contentValues.put(DbInfo.TasksInfo.taskDate, tDate);
        contentValues.put(DbInfo.TasksInfo.taskTime, tTime);
        contentValues.put(DbInfo.TasksInfo.taskNotes, taskNote);

        db.insert(DbInfo.TasksInfo.TABLE_NAME, null, contentValues);

        Log.e("Insertion OP", "Row inserted into Tasks Databases");
    }

    public void insertToNotes(String nName, String nDate, SQLiteDatabase db) {

        ContentValues contentValues = new ContentValues();

        contentValues.put(DbInfo.NotessInfo.noteName, nName);
        contentValues.put(DbInfo.NotessInfo.noteDate, nDate);

        db.insert(DbInfo.NotessInfo.TABLE_NAME, null, contentValues);

        Log.e("Insertion OP", "Row inserted into Notes Databases");
    }


    public Cursor getTasks(SQLiteDatabase db) {
        Cursor cursor;
        String[] projections = {
            DbInfo.TasksInfo.taskId, DbInfo.TasksInfo.taskName, DbInfo.TasksInfo.taskDate, DbInfo.TasksInfo.taskTime, DbInfo.TasksInfo.taskNotes};


            cursor = db.query(DbInfo.TasksInfo.TABLE_NAME, projections, null, null, null, null, DbInfo.TasksInfo.taskId + " desc");

        return cursor;
    }

    public Cursor searchTasks(SQLiteDatabase db, String searchTxt) {
        Cursor cursor;

        String[] projections = {
                DbInfo.TasksInfo.taskId, DbInfo.TasksInfo.taskName, DbInfo.TasksInfo.taskDate,
                DbInfo.TasksInfo.taskTime, DbInfo.TasksInfo.taskNotes};

        cursor = db.query(DbInfo.TasksInfo.TABLE_NAME, projections, DbInfo.TasksInfo.taskName+" Like '"+searchTxt+"%'", null, null, null, null);

        return cursor;

    }


    public void updateTasks(SQLiteDatabase db, String id, String tname, String tdate, String ttime, String tnote) {

        ContentValues values = new ContentValues();

        values.put(DbInfo.TasksInfo.taskName, tname);
        values.put(DbInfo.TasksInfo.taskDate, tdate);
        values.put(DbInfo.TasksInfo.taskTime, ttime);
        values.put(DbInfo.TasksInfo.taskNotes, tnote);

        int cursor = db.update(DbInfo.TasksInfo.TABLE_NAME, values, DbInfo.TasksInfo.taskId+" = "+id, null);
    }

    public boolean deleteTasks(SQLiteDatabase db, String id) {

        return  db.delete(DbInfo.TasksInfo.TABLE_NAME, DbInfo.TasksInfo.taskId+" = "+id, null) >0;

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

    }
}

这是我的 TasksFragment,它在 SwipeView 选项卡内的 MainActivity 上被调用

package ly.edu.cet.www.myhomworks;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.support.v4.app.Fragment;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

/**
 * Created by newton on 11/19/15.
 */
public class TasksFragment extends Fragment {

    ListView tasksListView;
    SQLiteDatabase sqLiteDatabase;
    Cursor cursor;
    Cursor scursor;
    DbHelper dbHelper;

    TasksListAdapter adapter;
    SearchView searchView;
    String searchQuery;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.tasks_layout, container, false);
        searchView = (SearchView) view.findViewById(R.id.searchView);
        tasksListView = (ListView) view.findViewById(R.id.tasksListView);
        adapter = new TasksListAdapter(getContext(), R.layout.tasks_row);

        dbHelper = new DbHelper(view.getContext());
        sqLiteDatabase = dbHelper.getReadableDatabase();


        tasksListView.setAdapter(adapter);
        cursor = dbHelper.getTasks(sqLiteDatabase);

        if (cursor.moveToFirst()) {
            do {
                String name, date, time, note;
                name = cursor.getString(1);
                date = cursor.getString(2);
                time = cursor.getString(3);
                note = cursor.getString(4);

                DataProvider dataProvider = new DataProvider(name, date, time, note);

                adapter.add(dataProvider);

            } while (cursor.moveToNext());
        }
        adapter.notifyDataSetChanged();

        tasksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        cursor.moveToPosition(position);
                        String listId = cursor.getString(cursor.getColumnIndex(DbInfo.TasksInfo.taskId));
                        String listName = cursor.getString(cursor.getColumnIndex(DbInfo.TasksInfo.taskName));
                        String listDate = cursor.getString(cursor.getColumnIndex(DbInfo.TasksInfo.taskDate));
                        String listTime = cursor.getString(cursor.getColumnIndex(DbInfo.TasksInfo.taskTime));
                        String listNote = cursor.getString(cursor.getColumnIndex(DbInfo.TasksInfo.taskNotes));

                        Intent updateTasksIntent = new Intent(getContext(), AddTask.class);

                        updateTasksIntent.putExtra("editTask", true);
                        updateTasksIntent.putExtra("taskId", listId);
                        updateTasksIntent.putExtra("taskName", listName);
                        updateTasksIntent.putExtra("taskDate", listDate);
                        updateTasksIntent.putExtra("taskTime", listTime);
                        updateTasksIntent.putExtra("taskNote", listNote);

//                        Toast.makeText(getContext(), "List row " + position + " ID = " + listId, Toast.LENGTH_SHORT).show();

                        startActivity(updateTasksIntent);
                    }
                }

            }
        });


        tasksListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        cursor.moveToPosition(position);
                        String listId = cursor.getString(cursor.getColumnIndex(DbInfo.TasksInfo.taskId));

                        Log.e("Database Op", "List row " + position + " ID = " + listId);

                        dbHelper.deleteTasks(sqLiteDatabase, listId);

                        TasksListAdapter newAdapter = new TasksListAdapter(getContext(), R.layout.tasks_row);

                        cursor = dbHelper.getTasks(sqLiteDatabase);

                        if (cursor.moveToFirst()) {
                            do {
                                String name, date, time, note;
                                name = cursor.getString(1);
                                date = cursor.getString(2);
                                time = cursor.getString(3);
                                note = cursor.getString(4);

                                DataProvider dataProvider = new DataProvider(name, date, time, note);

                                newAdapter.add(dataProvider);

                            } while (cursor.moveToNext());
                        }
                        newAdapter.notifyDataSetChanged();
                        tasksListView.setAdapter(newAdapter);
//                        Toast.makeText(getContext(), "List row " + position + " ID = " + listId, Toast.LENGTH_SHORT).show();

                    }
                }
                return true;
            }
        });

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                TasksListAdapter searchAdapter = new TasksListAdapter(getContext(), R.layout.tasks_row);

                scursor = dbHelper.searchTasks(sqLiteDatabase, newText);

                if (scursor.moveToFirst()) {
                    do {
                        String name, date, time, note;
                        name = scursor.getString(1);
                        date = scursor.getString(2);
                        time = scursor.getString(3);
                        note = scursor.getString(4);

                        DataProvider dataProvider = new DataProvider(name, date, time, note);

                        searchAdapter.add(dataProvider);

                    } while (scursor.moveToNext());
                }
                tasksListView.setAdapter(searchAdapter);
                searchAdapter.notifyDataSetChanged();

                return true;
            }
        });


        FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent addTaskIntent = new Intent(getContext(), AddTask.class);
                addTaskIntent.putExtra("addNewTask", true);
                startActivity(addTaskIntent);
            }
        });

        return view;
    }

}

祝你们好运:) 穆罕默德·格里利

关于android - SearchView 将结果从数据库显示到 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33849446/

相关文章:

android - 刷新 Activity/"performing stop of activity that is not resumed"错误

sql - 如何比较 Oracle 中的复杂集合?

android - onCreate() 不被 getWritableDatabase() 调用

android - 如何从谷歌地图应用中的标记 fragment 获取数据?

android - 如何使用 Volley 将 JSON 对象发送到服务器

java - 如何从 UI 线程以外的线程显示对话框

mysql - 非常大的MySQL数据库,删除一列,数据库大小增加了50%

php - 这5张表的SQL查询怎么写?

database - SQLite - 组连续和不同

android - Android 上的 GreenDAO : Byte Array as Primary Key/Building Query Containing Where Clause on Byte Array Property