在AutoCompleteTextView中获取空指针异常错误

时间:2016-12-17 13:41:22

标签: android android-fragments nullpointerexception

在空指针异常的AutoComplete TextView中获取错误。

当我延长Activity然后它可以工作,但是当我扩展片段时,它不会显示AutocompleteTextView中的选项。

得到如下错误: -

  E/Fail 3: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

这里有完整的代码: -

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        // don't look at this layout it's just a listView to show how to handle the keyboard
        View view = inflater.inflate(R.layout.activity_add__visit, container, false);
        session = new SessionManager(getActivity());
        HashMap<String, String> user = session.getUserDetails();
        uid = user.get(SessionManager.KEY_ID);

        longi = (TextView)view. findViewById(R.id.longitude);
        lat= (TextView)view. findViewById(R.id.latitude);

        ac=(AutoCompleteTextView)view.findViewById(R.id.autoCompleteTextView1);
        remarks = (EditText)view.findViewById(R.id.remarks);
        submit=(Button)view.findViewById(R.id.submit);
        new DownloadJSON().execute();
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                remark_detail = remarks.getText().toString();
                id = ac.getText().toString();
                latitude12=lat.getText().toString();
                longitude12=longi.getText().toString();

                if (id.equals(null) || id.equals(""))
                {
                    Toast.makeText(getActivity(), "Please Select Party Name", Toast.LENGTH_LONG).show();

                } else
                {
                   GetCurrentGPSLocation gps = new GetCurrentGPSLocation(getActivity());

                    // check if GPS enabled
                    if (gps.canGetLocation()) {
                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();
                        // \n is for new line
                        lat.setText( ""+latitude);
                        longi.setText("" +longitude);
                        latitude12=lat.getText().toString();
                        longitude12=longi.getText().toString();
                        Toast.makeText(getActivity(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();

                        longi.setVisibility(View.INVISIBLE);
                        lat.setVisibility(View.INVISIBLE);
                    } else {
                        // can't get location
                        // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings
                        gps.showSettingsAlert();
                    }

                    addvisitor();
                    //FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                    //fragmentTransaction.replace(R.id.containerView,new Home()).commit();
                }





            }
        });
                    return view;
    }

      private class DownloadJSON extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setTitle("Please Wait");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();

        }

        @Override
        protected Void doInBackground(Void... voids) {

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.wealinfotech.com/portal/autocomplete.php");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.e("Pass 1", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 1", e.toString());
                Toast.makeText(getActivity(), "Invalid IP Address", Toast.LENGTH_LONG).show();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                Log.e("Pass 2", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 2", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            try {
                JSONArray JA = new JSONArray(result);
                JSONObject json = null;
                final String[] str1 = new String[JA.length()];
                final String[] str2 = new String[JA.length()];


                for (int i = 0; i < JA.length(); i++) {
                    json = JA.getJSONObject(i);
                    str1[i] = json.getString("cl_pname");
                    str2[i] = json.getString("cl_wodcode");
                }
                final AutoCompleteTextView text = (AutoCompleteTextView)view. findViewById(R.id.autoCompleteTextView1);
                final List<String> list = new ArrayList<String>();
                for (int i = 0; i < str1.length; i++) {
                    list.add(str1[i]);
                }

                Collections.sort(list);
                final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), R.layout.my_list_item, list);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
                text.setThreshold(1);
                text.setAdapter(dataAdapter);
                text.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String selected_cl_pname = (String) parent.getItemAtPosition(position);
                        int index = Arrays.asList(str1).indexOf(selected_cl_pname);
                        String selected_cl_wodcode = str2[index];
                        wv1 = (WebView)view. findViewById(R.id.webView);
                        wv1.setWebViewClient(new MyBrowser());
                        wv1.loadUrl("http://www.wealinfotech.com/portal/on_target.php?cl_wodcode=" + selected_cl_wodcode);
                        wv1.getSettings().setLoadsImagesAutomatically(true);
                        wv1.getSettings().setJavaScriptEnabled(true);
                        wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
                        Toast.makeText(getActivity(), (CharSequence) parent.getItemAtPosition(position), Toast.LENGTH_LONG).show();

                        Log.d("wt_wod_code", selected_cl_wodcode);
                        Log.d("wt_wod_sascode", str2[index]);

//                        Toast.makeText(getApplicationContext(), (CharSequence) parent.getItemAtPosition(position), Toast.LENGTH_LONG).show();

                        wt_wod_code1 = text.getText().toString();
                        wt_party1 = text.getText().toString();

                    }
                });
            } catch (Exception e) {
                Log.e("Fail 3", e.toString());
                mProgressDialog.dismiss();
            }
        }

2 个答案:

答案 0 :(得分:0)

覆盖片段内的OnViewCreated和那里的查找ids

 @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

      longi = (TextView)view.findViewById(R.id.longitude);
      lat= (TextView)view.findViewById(R.id.latitude);
      ac=(AutoCompleteTextView)view.findViewById(R.id.autoCompleteTextView1);
    remarks = (EditText)view.findViewById(R.id.remarks);
    submit=(Button)view.findViewById(R.id.submit);


    }

答案 1 :(得分:0)

尝试替换:

final AutoCompleteTextView text = (AutoCompleteTextView) view.findViewById(R.id.autoCompleteTextView1);

使用:

final AutoCompleteTextView text = (AutoCompleteTextView) getView().findViewById(R.id.autoCompleteTextView1);

同样地:

wv1 = (WebView) view.findViewById(R.id.webView);

使用:

wv1 = (WebView) getView().findViewById(R.id.webView);

您可能正在使用实例变量view(在问题和示例粘贴代码中没有提及),在您尝试使用它时未初始化。

修改

强烈建议您在new DownloadJSON().execute();而不是onViewCreated()中致电onCreatView()。此解决方案可以正常工作,但只有在从服务器获取响应之前创建View时,如果网络太快而设备由于某种原因而变慢,则无法正常工作。