string.isEmpty()方法的nullpointerexception

时间:2014-04-14 04:05:58

标签: android listview custom-adapter android-filterable

好吧,我创建了自己的custumadapter类以便在listview中使用,我在第178行得到了一个nullpointerexception,它说“if(inputSearch.getText()。toString()。isEmpty())” 有人可以帮我看看为什么我会这样做吗?

这是我的代码:

package com.example.student_lists;

import java.util.ArrayList;
import java.util.Locale;
import com.resources.student_list.Student;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    EditText inputSearch;
//  static ListView lv;
//  static EditText inputSearch;
    //static MyListAdapter adapter;

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

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }


    private class MyListAdapter extends ArrayAdapter<Student> implements Filterable{

        private final Context context;
        public ArrayList<Student> displayValues;
        public ArrayList<Student> originalValues;

        public MyListAdapter(Context context, int textViewResourceId, ArrayList<Student> values) {
            super(context, textViewResourceId, values);
            this.context = context;
            this.displayValues = values;
            this.originalValues = (ArrayList<Student>) values.clone();
        }

        public int getCount(){
             return this.displayValues.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            //----This method sets each row of the list individually----            
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View itemView = inflater.inflate(R.layout.list_view, parent, false);

            if(displayValues.size() > 0)
            {
                Student student = displayValues.get(position);

//                          //Fill Name
                            TextView name = (TextView) itemView.findViewById(R.id.contactName);
                            name.setText(student.getFirstName() + " " + student.getLastName());

            }           
            return itemView;

        }

        public Filter getFilter() {

            Filter contactFilter = new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                 FilterResults filterResults = new FilterResults();   
                 ArrayList<Student> filteredList = new ArrayList<Student>();

                 //Filter the list
                 if(constraint != null && originalValues !=null) {

                     if(!constraint.toString().isEmpty())
                     {  
                         String constraintLowerCase = constraint.toString().toLowerCase();

                            for(Student c: originalValues)
                            {                           
                                String cName = c.getFirstName().toLowerCase() ;
                                String cLName = c.getLastName().toLowerCase();
                                if(cName.startsWith(constraintLowerCase) || cLName.startsWith(constraintLowerCase)) 
                                {
                                    //Add the row to the list if filtered items
                                    filteredList.add(c);
                                }
                            }                                            

                     }

                   //Important steps to store the filtered list
                    filterResults.values = filteredList;
                    filterResults.count = filteredList.size();
                  }
                  return filterResults;
              }

            @SuppressWarnings("unchecked")
              @Override
              protected void publishResults(CharSequence contraint, FilterResults results) {                                                                                              
                  if (results.count > 0) 
                  {         
                      //Display the filtered list
                      MyListAdapter.this.displayValues = (ArrayList<Student>) results.values;
                      notifyDataSetChanged();
                  }
                  else
                  {
                      if(inputSearch.getText().toString().isEmpty())
                      {                 
                        //Display the original list
                          MyListAdapter.this.displayValues = (ArrayList<Student>) MyListAdapter.this.originalValues.clone();
                      }
                      else
                      {                     
                        //Display an empty list
                          MyListAdapter.this.displayValues.clear();
                      }                 
                    notifyDataSetInvalidated();
                  }
              }
             };

            return contactFilter;

        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";

        public DummySectionFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);

            switch(getArguments().getInt(ARG_SECTION_NUMBER)){
            case 0:

            case 1:

                Student andres = new Student();
                andres.setFirstName("Andres");
                andres.setLastName("Blanco");

                Student ondria = new Student();
                ondria.setFirstName("Ondria");
                ondria.setLastName("Arias");

                ArrayList<Student> studentList = new ArrayList<Student>();
                studentList.add(andres);
                studentList.add(ondria);

                MainActivity mainactivity = new MainActivity();
                ListView lv = (ListView) rootView.findViewById(R.id.list);
                final MyListAdapter adapter = mainactivity.new MyListAdapter(getActivity(), R.layout.list_view, studentList);
                lv.setAdapter(adapter);
                lv.setTextFilterEnabled(true);
                EditText inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
                inputSearch.addTextChangedListener(new TextWatcher() {

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


                return rootView;


            case 2:

            }

            return rootView;
        }
    }

}

2 个答案:

答案 0 :(得分:3)

您需要首先初始化EditText

@Override
protected void onCreate(Bundle savedInstanceState) {
   EditText inputSearch = (EditText) this.findViewById(R.id.inputSearch);
}

然后,而不是:

if (inputSearch.getText().toString().isEmpty())

你应该这样做:

if (inputSearch.getText() != null) {
    // Do something
} else {
   // Do something else
}

答案 1 :(得分:1)

我不知道你在哪里初始化inputSearch。如果您没有初始化它,那么它将是null,当您在其上调用getText()时,您将收到NullPointerException。

修改

你有这一行:

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

这只是一个局部变量,与inputSearch中的变量不同publishResults将此行更改为

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