应用程序崩溃与空对象引用

时间:2016-12-23 09:26:51

标签: android android-fragments nullpointerexception

我在片段中使用AutoCompleteTextView ... 但当我使用刷新AutoCompleteTextView建议的方法时,应用程序崩溃Null Object Reference 这是方法 -

private ArrayList<String> sugs = new ArrayList<String>();

public void refreshSugs() 
{
    ((AutoCompleteTextView) getView().findViewById(R.id.editText1)).setAdapter(new ArrayAdapter(getActivity(), 17367050, this.sugs));
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
{
    //Inflating the Layout 
    View rootView = inflater.inflate(R.layout.home_fragment, container, false); 

    Button buttongo = (Button) rootView.findViewById(R.id.button1);
    EditText et1 = (EditText) rootView.findViewById(R.id.editText1);
    Button buttonsave = (Button) rootView.findViewById(R.id.button2);


    bar = (ProgressWheel) rootView.findViewById(R.id.progressBar1);
    i = (ImageView) rootView.findViewById(R.id.imageView1);
    background2 = (TextView) rootView.findViewById(R.id.textView1);
    background3 = (TextView) rootView.findViewById(R.id.textView2);
    readSugs();
    refreshSugs();

    return rootView;
}

2 个答案:

答案 0 :(得分:2)

Might be your getView() is null.

 private ArrayList<String> sugs = new ArrayList<String>();
private View rootView;
public void refreshSugs() {
         ((AutoCompleteTextView) rootView.findViewById(R.id.editText1)).setAdapter(new ArrayAdapter(getActivity(), 17367050, this.sugs));

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        //Inflating the Layout 
      rootView = inflater.inflate(R.layout.home_fragment, container, false); 

         ..... your code

        return rootView;
}

答案 1 :(得分:1)

 private ArrayList<String> sugs = new ArrayList<String>();
private View rootView;
public void refreshSugs(View rootView) {
         ((AutoCompleteTextView) rootView.findViewById(R.id.editText1)).setAdapter(new ArrayAdapter(getActivity(), 17367050, this.sugs));

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        //Inflating the Layout 
      rootView = inflater.inflate(R.layout.home_fragment, container, false); 

         ..... your code...........
      refreshSugs0(rootView);
        return rootView;
}