-2

I want to add search view on action bar using listview. I added search view on action bar but it isn't search listview. I got null pointer error.

MainActivity

protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            actionBar = getActionBar();
            list = new ArrayList<Personinfo>();
            databaseHelper = new DatabaseHelper(this);

            csvToSqlite();
            listView = (ListView) findViewById(R.id.listview);
            getlistData();
            adapterfilter = new AdapterFilter(this, R.layout.child_listview, list);
            listView.setAdapter(adapterfilter);
            listView.setTextFilterEnabled(true);
            synchronized (listView) {
                listView.notify();
                // }
            }

        }

        public void getlistData() {
            // TODO Auto-generated method stub
            Cursor cursor = databaseHelper.getData();
            cursor.moveToFirst();
            do {
                String name = cursor.getString(cursor.getColumnIndex("Name"));
                String phoneNo = cursor.getString(cursor.getColumnIndex("PhoneNo"));
                Personinfo personinfo = new Personinfo(name, phoneNo);
                list.add(personinfo);
            } while (cursor.moveToNext());
            cursor.close();

        }

        public void csvToSqlite() {
            try {
                String reader = "";
                boolean skipheader = true;
                InputStream inputStream = getResources().openRawResource(
                        R.raw.agrawalsurnamedata);
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        inputStream));
                while ((reader = in.readLine()) != null) {
                    // skip header column name from csv
                    if (skipheader) {
                        skipheader = false;
                        continue;
                    }
                    String[] RowData = reader.split(",");
                    if (databaseHelper.insertContact(RowData) == true) {
                        Log.i("inside csvToSqlite()", " data inserted successfully");
                    } else {
                        Log.i("inside csvToSqlite()",
                                " data is not inserted into db");
                    }
                }
                in.close();
            } catch (Exception e) {
                e.getMessage();
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.main, menu);

            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
                    .getActionView();
            searchView.setSearchableInfo(searchManager
                    .getSearchableInfo(getComponentName()));
            SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextChange(String newText) {
                    // this is your adapter that will be filtered
                    adapterfilter.getFilter().filter(newText);
                    System.out.println("on text chnge text: " + newText);
                    return true;
                }

                @Override
                public boolean onQueryTextSubmit(String query) {
                    // this is your adapter that will be filtered
                    adapterfilter.getFilter().filter(query);
                    System.out.println("on query submit: " + query);
                    return true;
                }
            };
            searchView.setOnQueryTextListener(textChangeListener);
            return super.onCreateOptionsMenu(menu);

        }

AdapterFilter.Class
This my adapter filter class which is extends by ArrayAdapter class.

public class AdapterFilter extends ArrayAdapter<Personinfo> {
    ArrayList<Personinfo> list = new ArrayList<Personinfo>();
    Context context;
    LayoutInflater inflater;

    public AdapterFilter(Context context, int resource,
            ArrayList<Personinfo> list) {
        super(context, resource);
        this.list = list;
        this.context = context;
        inflater = LayoutInflater.from(this.context);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Personinfo getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        ViewHolder viewHolder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.child_listview, parent,
                    false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        final Personinfo personinfo = (Personinfo) getItem(position);

        viewHolder.txtName.setText(personinfo.getName());
        viewHolder.txtPhone.setText(personinfo.getPhoneno());
        viewHolder.imageButtonCalling.setOnClickListener(new OnClickListener() {
            // Calling on selected number
            @Override
            public void onClick(View v) {

                // TODO Auto-generated method stub
                Toast.makeText(context, "number button Clicked",
                        Toast.LENGTH_SHORT).show();
                String selectedChildPhone = personinfo.getPhoneno();
                String phoneNo = "tel:" + selectedChildPhone.trim();
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse(phoneNo));
                context.startActivity(intent);
            }
        });
        viewHolder.imageButtonMessage.setOnClickListener(new OnClickListener() {
            // Sending sms to whatsapp
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context, "meesaage button Clicked",
                        Toast.LENGTH_SHORT).show();
                String selectedChildPhone = personinfo.getPhoneno();
                Uri mUri = Uri.parse("smsto:" + selectedChildPhone);
                Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
                mIntent.setPackage("com.whatsapp");
                mIntent.putExtra("sms_body", "The text goes here");
                mIntent.putExtra("chat", true);
                context.startActivity(mIntent);
            }
        });
        return convertView;
    }

    private class ViewHolder {
        TextView txtName, txtPhone;
        ImageButton imageButtonCalling, imageButtonMessage;

        public ViewHolder(View item) {
            txtName = (TextView) item.findViewById(R.id.person_name);
            txtPhone = (TextView) item.findViewById(R.id.phoneno);
            imageButtonCalling = (ImageButton) item
                    .findViewById(R.id.imageButtonCalling);
            imageButtonMessage = (ImageButton) item
                    .findViewById(R.id.imageButtonMessage);
        }
    }
}  

LogCat

08-03 16:32:49.993: E/AndroidRuntime(12722): FATAL EXCEPTION: main
08-03 16:32:49.993: E/AndroidRuntime(12722): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhub4you.searchactionbardemo/com.androidhub4you.searchactionbardemo.SearchActivity}: java.lang.NullPointerException
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2146)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.app.ActivityThread.access$700(ActivityThread.java:140)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.os.Looper.loop(Looper.java:177)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.app.ActivityThread.main(ActivityThread.java:4947)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at java.lang.reflect.Method.invokeNative(Native Method)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at java.lang.reflect.Method.invoke(Method.java:511)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at dalvik.system.NativeStart.main(Native Method)
08-03 16:32:49.993: E/AndroidRuntime(12722): Caused by: java.lang.NullPointerException
08-03 16:32:49.993: E/AndroidRuntime(12722):    at com.androidhub4you.searchactionbardemo.SearchActivity.onCreate(SearchActivity.java:86)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.app.Activity.performCreate(Activity.java:5207)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-03 16:32:49.993: E/AndroidRuntime(12722):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2085)
08-03 16:32:49.993: E/AndroidRuntime(12722):    ... 11 more
abc
  • 67
  • 3
  • 11
  • 1
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Selvin Aug 03 '15 at 11:07
  • It is not duplicate of this link. its explain only NPE but my problem is different. @Selvin – abc Aug 03 '15 at 11:13
  • It is NPE in your code + you didn't even try to understand what and why something is null ... so yeah, it is a duplicate – Selvin Aug 03 '15 at 11:15
  • Can you explain what is my mistake in my implementation. @Selvin – abc Aug 03 '15 at 11:16
  • Just follow the link... – Selvin Aug 03 '15 at 11:20

1 Answers1

0

In your Activity do something like this and call the filter when you type in action bar search

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_contacts, menu);
    invalidateOptionsMenu();
    // Associate searchable configuration with the SearchView
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    SearchView.OnQueryTextListener queryTextWatcher = new SearchView.OnQueryTextListener(){

        @Override
        public boolean onQueryTextSubmit(String query) {
            // TODO Auto-generated method stub
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            // TODO Auto-generated method stub

            objAdapter.filter(newText);
            return true;
        }

    };

    searchView.setOnQueryTextListener(queryTextWatcher);

    return super.onCreateOptionsMenu(menu);
}

In your adapter write the filter method

public void filter(String charText ) {
    // TODO Auto-generated method stub
    charText = charText.toLowerCase(Locale.getDefault());
    //charText = charText.replace(" ", "");
    items.clear();
    if (charText.length() == 0) {
        items.addAll(arraylist);
    } 
    else {

        for (ContactBean ob : arraylist){

            if (ob.getName().toLowerCase(Locale.getDefault()).contains(charText) 
                    || ob.getPhoneNo().toLowerCase(Locale.getDefault()).contains(charText)){

                items.add(ob);
            }
        }
    }
    notifyDataSetChanged();

i used this code in my application tou have to change it with your data.

Srikanth K
  • 190
  • 3
  • 12