搜索过滤器null异常

时间:2013-12-09 09:07:35

标签: android listview search adapter

每个listview列包含5textview -ID,Initial,Date,Location,Ward。

我试图通过初始化来过滤listview。但是,我在第166行遇到了一个空例外。

我假设editText没有按初始过滤,似乎每次调用适配器都会导致错误消息。因此,我认为问题在于适配器。

  package com.example.medilearner;

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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.medilearner.database.patientDbAdapter;

public class PatientDetails extends Activity {

    // Database adapter
    patientDbAdapter patientDB;
    Context myContext;
    // ArrayAdapter
    ArrayAdapter<String> adapter;

    ArrayList<HashMap<String, String>> encouterlist = new ArrayList<HashMap<String, String>>();
    // Various layout
    ListView patientList;

    static String value;
    private EditText filterText = null;

    private static final String TAG_E_ID = "e_id";
    private static final String TAG_E_INITIAL = "entry_initial";
    private static final String TAG_E_DATE = "entry_date";
    private static final String TAG_E_SITELOCATION = "entry_sitelocation";
    private static final String TAG_E_WARDCLINIC = "entry_clinic";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_details);
        encouterlist = new ArrayList<HashMap<String, String>>();
        myContext = this;
        patientDB = new patientDbAdapter(myContext);
        patientDB.open();
        Cursor mCursor = patientDB.retrieveAllPatientEntriesCursor();
        int count = mCursor.getCount();
        if ((mCursor != null) && (mCursor.getCount() > 0)) {
            mCursor.moveToFirst();

            do {
                // Get the data
                // Convert the initial to String

                String ID = mCursor.getString(0);
                String Initial = mCursor.getString(1);
                String Date = mCursor.getString(2);
                String SiteLocation = mCursor.getString(3);
                String WardClinic = mCursor.getString(4);

                // Indicate that it's successful
                Log.i("Successful retrival of", Initial);

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

                map.put(TAG_E_ID, ID);
                map.put(TAG_E_INITIAL, Initial);
                map.put(TAG_E_DATE, "Last Diagnosis: " + Date);
                map.put(TAG_E_SITELOCATION, "Location: " + SiteLocation);
                map.put(TAG_E_WARDCLINIC, "Ward: " + WardClinic);

                // Add it to the array such that i can handle the array
                // afterwhich
                encouterlist.add(map);

            }
            // move to the next row
            while (mCursor.moveToNext());
        }

        filterText = (EditText) findViewById(R.id.patientDetailsSearch);
        filterText.addTextChangedListener(filterTextWatcher);
        // need to link the layout
        patientList = (ListView) findViewById(R.id.PatientDetailslist);




        patientList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                    int position, long id) {
                String str = encouterlist.get(+position).get("e_id");
                String name = encouterlist.get(+position).get("entry_initial");
                patientDB.open();

                patientDB.removeEntry(str);
                patientDB.close();
        //      PatientDetails.this.recreate();

                Toast.makeText(myContext, name + " Deleted", Toast.LENGTH_SHORT).show();

                // TODO Auto-generated method stub
                return true; 
            }

        }
        );

        patientList
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        Toast.makeText(
                                PatientDetails.this,
                                encouterlist.get(+position)
                                        .get("entry_initial") + " Selected",
                                Toast.LENGTH_SHORT).show();
                        Intent localIntent = new Intent(PatientDetails.this,
                                PatientInfo.class);
                        String str = encouterlist.get(+position).get("e_id");
                        localIntent.putExtra("value", str);
                        PatientDetails.this.setResult(-1, localIntent);
                        PatientDetails.this.finish();
                    }


                }

                );
        ListAdapter adapter = new SimpleAdapter(PatientDetails.this,
                encouterlist, R.layout.list_patient, new String[] { TAG_E_ID,
                        TAG_E_INITIAL, TAG_E_DATE, TAG_E_SITELOCATION,
                        TAG_E_WARDCLINIC }, new int[] { R.id.eid,
                        R.id.epatientInitial, R.id.epatientDate,
                        R.id.epatientSiteLocation, R.id.epatientWardClinci });

    this.patientList.setAdapter(adapter);


        };

        private TextWatcher filterTextWatcher = new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                adapter.getFilter().filter(s);
            }

        };


    protected void onDestroy() {
        super.onDestroy();
        filterText.removeTextChangedListener(filterTextWatcher);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.patient_details, menu);
        return true;
    }

}

logcat的

12-09 17:01:07.600: E/AndroidRuntime(25728): FATAL EXCEPTION: main
12-09 17:01:07.600: E/AndroidRuntime(25728): java.lang.NullPointerException
12-09 17:01:07.600: E/AndroidRuntime(25728):    at com.example.medilearner.PatientDetails$1.onTextChanged(PatientDetails.java:166)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.widget.TextView.sendOnTextChanged(TextView.java:7426)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.widget.TextView.handleTextChanged(TextView.java:7488)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:9260)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:962)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:496)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:435)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:30)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:676)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:435)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:333)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.os.Looper.loop(Looper.java:137)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at android.app.ActivityThread.main(ActivityThread.java:4921)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at java.lang.reflect.Method.invokeNative(Native Method)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at java.lang.reflect.Method.invoke(Method.java:511)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
12-09 17:01:07.600: E/AndroidRuntime(25728):    at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

这是因为

public void onTextChanged(CharSequence s, int start, int before,
                int count) {
    adapter.getFilter().filter(s);
}

您的adapter为空。您正在本地创建ListAdapter adapter,这在范围之外没有意义。您可以使用全局的,而不是在本地创建ListAdapter

答案 1 :(得分:0)

您创建列表适配器的本地实例

ListAdapter adapter = new SimpleAdapter(PatientDetails.this ....

在您的文本观察器中,您正在使用memeber adapter

尝试更改为

this.adapter = new SimpleAdapter(PatientDetails.this ....

答案 2 :(得分:0)

嗨,请完成代码示例

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {

    // List view
    private ListView lv;

    // Listview Adapter
    ArrayAdapter<String> adapter;

    // Search EditText
    EditText inputSearch;


    // ArrayList for Listview
    ArrayList<HashMap<String, String>> productList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Listview Data
        String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
                                "iPhone 4S", "Samsung Galaxy Note 800",
                                "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};

        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);

        // Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
        lv.setAdapter(adapter);

        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {

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

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Editext for Search -->
    <EditText android:id="@+id/inputSearch"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Search products.."
        android:inputType="textVisiblePassword"/>

    <!-- List View -->
    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- Single ListItem -->

    <!-- Product Name -->
    <TextView android:id="@+id/product_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold"/>    

</LinearLayout>