片段类中的 View.findViewById

Posted

技术标签:

【中文标题】片段类中的 View.findViewById【英文标题】:View.findViewById in fragment class 【发布时间】:2016-04-08 01:41:31 【问题描述】:

单击导航抽屉中的片段图标时出现此错误。我的 logcat 输出如下所示。

E/androidRuntime: FATAL EXCEPTION: main

Process: com.example.abdul_majeed.alruthea, PID: 16293 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
             at com.example.abdul_majeed.alruthea.Telephones.onCreateView(Telephones.java:73)
             at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
             at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
             at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
             at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
             at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
             at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
             at android.os.Handler.handleCallback(Handler.java:739)
             at android.os.Handler.dispatchMessage(Handler.java:95)
             at android.os.Looper.loop(Looper.java:135)
             at android.app.ActivityThread.main(ActivityThread.java:5221)
             at java.lang.reflect.Method.invoke(Native Method)
             at java.lang.reflect.Method.invoke(Method.java:372)
             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

这是片段:

public class Telephones extends Fragment 


RequestQueue requestQueue;
private List<tel_list> data = new ArrayList<tel_list>();
private ListView listView;
private TelAdapter adapter;
private EditText telfilter;
private ProgressDialog progressDialog;

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



    listView = (ListView) getView().findViewById(R.id.listview1);
    adapter = new TelAdapter(getActivity(), data);
    listView.setAdapter(adapter);
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("please wait");
    progressDialog.show();
    telfilter = (EditText) getView().findViewById(R.id.myFilter);
    telfilter.addTextChangedListener(new TextWatcher() 
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) 

        

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) 


            List<tel_list> temp = new ArrayList<tel_list>();

            String input = s.toString();

            for (int i = 0; i < data.size(); i++) 
                tel_list item = data.get(i);

                String name = item.getName();
                String number = item.getNumber();

                if (name.contains(input) || number.contains(input)) 
                    temp.add(item);
                
            

            adapter.setTelephones(temp);
            adapter.notifyDataSetChanged();

        


        @Override
        public void afterTextChanged(Editable s) 


        

    );

    requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://abood250.com/alruthea/getphones.php",
            new com.android.volley.Response.Listener<JSONObject>() 

                @Override
                public void onResponse(JSONObject response) 
                    hideprogressDialog();

                    try 

                        JSONArray jsonArray = response.getJSONArray("telephones");
                        for (int i = 0; i < jsonArray.length(); i++) 
                            JSONObject telephones = jsonArray.getJSONObject(i);
                            tel_list tellist = new tel_list();

                            tellist.setName(telephones.getString("name"));
                            tellist.setNumber(telephones.getString("number"));

                            data.add(tellist);

                        
                     catch (JSONException e) 
                        e.printStackTrace();
                    
                    adapter.notifyDataSetChanged();
                
            ,

            new com.android.volley.Response.ErrorListener() 
                @Override
                public void onErrorResponse(VolleyError error) 
                    hideprogressDialog();

                    Log.e("Volley", "Error");
                
            


    );

    requestQueue.add(jsonObjectRequest);
    return inflater.inflate(R.layout.activity_telephones,container,false);


@Override
public void onDestroy() 
    super.onDestroy();
    hideprogressDialog();



private void hideprogressDialog() 

    if (progressDialog != null) 
        progressDialog.dismiss();
        progressDialog = null;
    

 

【问题讨论】:

【参考方案1】:

像这样更改您的代码。用视图替换 getView()。

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

    View view = inflater.inflate(R.layout.activity_telephones,container,false);

    listView = (ListView) getView().findViewById(R.id.listview1);
    adapter = new TelAdapter(getActivity(), data);
    listView.setAdapter(adapter);
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("please wait");
    progressDialog.show();
    telfilter = (EditText) getView().findViewById(R.id.myFilter);
    telfilter.addTextChangedListener(new TextWatcher() 
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) 

        

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) 


            List<tel_list> temp = new ArrayList<tel_list>();

            String input = s.toString();

            for (int i = 0; i < data.size(); i++) 
                tel_list item = data.get(i);

                String name = item.getName();
                String number = item.getNumber();

                if (name.contains(input) || number.contains(input)) 
                    temp.add(item);
                
            

            adapter.setTelephones(temp);
            adapter.notifyDataSetChanged();

        


        @Override
        public void afterTextChanged(Editable s) 


        

    );

    requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://abood250.com/alruthea/getphones.php",
            new com.android.volley.Response.Listener<JSONObject>() 

                @Override
                public void onResponse(JSONObject response) 
                    hideprogressDialog();

                    try 

                        JSONArray jsonArray = response.getJSONArray("telephones");
                        for (int i = 0; i < jsonArray.length(); i++) 
                            JSONObject telephones = jsonArray.getJSONObject(i);
                            tel_list tellist = new tel_list();

                            tellist.setName(telephones.getString("name"));
                            tellist.setNumber(telephones.getString("number"));

                            data.add(tellist);

                        
                     catch (JSONException e) 
                        e.printStackTrace();
                    
                    adapter.notifyDataSetChanged();
                
            ,

            new com.android.volley.Response.ErrorListener() 
                @Override
                public void onErrorResponse(VolleyError error) 
                    hideprogressDialog();

                    Log.e("Volley", "Error");
                
            


    );

    requestQueue.add(jsonObjectRequest);
    return view;
    

【讨论】:

【参考方案2】:

发生这种情况是因为您直接返回膨胀的视图。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    View view = inflater.inflate(R.layout.activity_telephones,container,false);

    listView = (ListView) view.findViewById(R.id.listview1);
    adapter = new TelAdapter(getActivity(), data);
    listView.setAdapter(adapter);
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("please wait");
    progressDialog.show();
    telfilter = (EditText) view.findViewById(R.id.myFilter);
    telfilter.addTextChangedListener(new TextWatcher() 
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) 

        

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) 


            List<tel_list> temp = new ArrayList<tel_list>();

            String input = s.toString();

            for (int i = 0; i < data.size(); i++) 
                tel_list item = data.get(i);

                String name = item.getName();
                String number = item.getNumber();

                if (name.contains(input) || number.contains(input)) 
                    temp.add(item);
                
            

            adapter.setTelephones(temp);
            adapter.notifyDataSetChanged();

        


        @Override
        public void afterTextChanged(Editable s) 


        

    );

    requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://abood250.com/alruthea/getphones.php",
            new com.android.volley.Response.Listener<JSONObject>() 

                @Override
                public void onResponse(JSONObject response) 
                    hideprogressDialog();

                    try 

                        JSONArray jsonArray = response.getJSONArray("telephones");
                        for (int i = 0; i < jsonArray.length(); i++) 
                            JSONObject telephones = jsonArray.getJSONObject(i);
                            tel_list tellist = new tel_list();

                            tellist.setName(telephones.getString("name"));
                            tellist.setNumber(telephones.getString("number"));

                            data.add(tellist);

                        
                     catch (JSONException e) 
                        e.printStackTrace();
                    
                    adapter.notifyDataSetChanged();
                
            ,

            new com.android.volley.Response.ErrorListener() 
                @Override
                public void onErrorResponse(VolleyError error) 
                    hideprogressDialog();

                    Log.e("Volley", "Error");
                
            


    );

    requestQueue.add(jsonObjectRequest);

    return view;

【讨论】:

以上是关于片段类中的 View.findViewById的主要内容,如果未能解决你的问题,请参考以下文章

扩展片段的类中的选项卡

日志片段,类中的Logfactory声明

如何将 View 类中的代码片段移动到 OnAppearing() 方法?

从片段类中的对话框添加项目到recyclerview。

如何禁用在android片段类中按下的后退按钮

在片段java类中使用“this”和getLastSignedInAccount时出现错误[重复]