【问题标题】:Filter custom ArrayAdapter or implement search in activity过滤自定义 ArrayAdapter 或在活动中实现搜索
【发布时间】:2014-08-05 20:08:51
【问题描述】:

在使用适配器的教程的帮助下,我已经成功地从 MYSQL 数据库实现了列表视图。现在我需要向显示的列表视图或某种搜索对话框添加过滤器。我对android真的很陌生。我想搜索数据库并在下一个活动中显示结果。非常感谢详细的解释。我知道如何调用搜索对话框,但值得注意的是继续前进。这是由列表视图中的数据库组成的活动:

DBLib.java

    package com.example.test;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class DBLib extends ListActivity implements OnClickListener{

    private ProgressDialog pDialog;

    private Button b_search;
    private EditText et;

    private static final String READ_DB_URL ="http://crshaggy.byethost7.com/webservice/warehouse.php";

    private static final String TAG_TITLE = "title";
    private static final String TAG_POSTS = "posts";
    private static final String TAG_ID = "id";

    private JSONArray mComments = null;

    private ArrayList<HashMap<String, String>> mCommentList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dblib_list);
        b_search=(Button)findViewById(R.id.listsearch);
        b_search.setOnClickListener(this);






    }

    @Override
    public void onClick(View v) {
        onSearchRequested();

    }


        @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // loading the comments via AsyncTask
        new LoadComments().execute();
    }

    public void updateJSONdata() {

    mCommentList = new ArrayList<HashMap<String, String>>();
    JSONParser jParser = new JSONParser();
    JSONObject json = jParser.getJSONFromUrl(READ_DB_URL);

    try{
        mComments = json.getJSONArray(TAG_POSTS);

        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            String title = c.getString(TAG_TITLE);

        HashMap<String, String> map = new HashMap<String, String>();

        map.put(TAG_TITLE, title);

        mCommentList.add(map);
    }
} catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void updateList() {

        ListAdapter adapter = new SimpleAdapter(this, mCommentList, 
        R.layout.post, new String[] { TAG_TITLE, TAG_ID}, 
        new int[] { R.id.title});

        setListAdapter(adapter);

        ListView lv = getListView();    
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                    }
                });
            }

    public class LoadComments extends AsyncTask<Void, Void, Boolean>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(DBLib.this);
            pDialog.setMessage("Loading Warehouse...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            updateJSONdata();
            return null;

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            updateList();
        }
    }




    }

列表布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/customgrey"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.test.DBLib" >

    <Button
        android:id="@+id/listsearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/searchbutton" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/listsearch" >
    </ListView>

</RelativeLayout>

编辑 1 我已经稍微更新了我的代码,我添加了一个 onTextChanged() 方法,但它给出了一个空指针异常。我刚刚更改了我在此处发布的 OnPostCreate() 方法:

@Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            updateList();

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

            inputSearch.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                    // When user changed the Text
                    DBLib.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                          
                }
            });


}

【问题讨论】:

    标签: android mysql listview search adapter


    【解决方案1】:

    SimpleAdapter 已经启用了过滤功能。你只需要调用类似的东西:

    getListAdapter().getFilter().filter("Text to search for");
    

    就是这样。 Android 将处理过滤您的数据并显示与给定字符串匹配的数据。

    更新 - 自定义过滤器

    自定义过滤器搜索的方式要复杂得多。简短的回答是,您需要编写自己的 SimpleAdapter 版本。 AFAIK,Android 提供的适配器都没有为如何自定义过滤逻辑提供简单的解决方案。这就是我建立Advanced-Adapters 的原因,不幸的是我还没有为 SimpleAdapter 编写解决方案。现在都是 ArrayAdapter 和 SparseArray 的替代品。

    您可能会发现很多人和示例都在说扩展 SimpleAdapter 类并覆盖 getFilter() 方法以使其返回由您实现的新过滤器类。然后,您可以使用您的 mCommentList 数组列表来确定如何过滤数据。虽然这在某些情况下会起作用,但这是不正确的方法,并且在各种情况下都会失败。

    正确的解决方案是创建自己的适配器类,其行为类似于 SimpleAdapter,但扩展了 BaseAdapter 类...这基本上意味着从头开始创建自己的适配器。作为 Android 新手,这可能是一项非常艰巨的任务,并且需要学习和了解适配器的工作原理。

    最简单的方法是将 SimpleAdapter source code 复制到您的项目中,然后手动将过滤器代码的逻辑更改为您想要的方式。调整的逻辑具体发生在this for loop 中。请记住,这是在后台线程上的 performFiltering() 方法中!因此所有同步块。

    【讨论】:

    • 请看编辑!
    • 您引用了DBLib.this.adapter,但我看不出您在哪里定义它。假设onPostExecute还在DBLib中,你可以直接调用DBLib.this.getListAdapter()。
    • 非常感谢。它现在起作用了。我现在有另一个问题。当我在edittext中写任何内容进行过滤时,它只会在我输入空格之前过滤第一个单词。如果空格后有内容,则活动变为空白并且列表消失。基本上它只是填写我输入的第一个单词
    • 是的,您可以自定义过滤器的行为方式,但这有点复杂。今晚晚些时候将更新我的答案,了解如何做到这一点。
    • 期待!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 2018-06-08
    • 2011-09-23
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多