SupportPlaceAutocompleteFragment null异常

时间:2016-10-02 19:54:37

标签: android android-viewpager fragment android-support-library

我正在我的应用中集成SupportPlaceAutocompleteFragment。 下面的片段在ViewPager里面..第一次一切正常......但是当我第二次进入片段时,我的应用程序崩溃了......我收到以下错误:

FATAL EXCEPTION: main


Process: rollwithme.com.rollwithme, PID: 14946

 java.lang.NullPointerException: Attempt to invoke virtual method 
'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference



at com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment.setText(Unknown Source)
at com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment$2.onClick(Unknown Source)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

这是我的代码:

/**
 * A simple {@link Fragment} subclass.
 */
public class PlanFragment extends Fragment implements View.OnClickListener {

    private static final int PERMISSION_ACCESS_COARSE_LOCATION = 10102;
    private static final String TAG = "PlanFragment";
    Calendar myCalendar = Calendar.getInstance();
    private View fragmentLayout;
    private ImageButton startCurrent;
    private Button routeButton;
    private EditText dateEditText, timeEditText;
    private EditText startEditText1, endEditText1;


    GPSTracker gps;
    private SupportPlaceAutocompleteFragment startEditText, endEditText;
    private com.google.android.gms.maps.model.LatLng startLatLng;
    private com.google.android.gms.maps.model.LatLng endLatLng;
    private DateTime journeyDate = new DateTime();

    public PlanFragment() {
        // Required empty public constructor
    }

    public static PlanFragment newInstance() {
        PlanFragment fragment = new PlanFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (startEditText != null) {
            startEditText.onCreate(savedInstanceState);
        }
        if (endEditText != null) {
            endEditText.onCreate(savedInstanceState);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        if(fragmentLayout != null){
            View oldParent = (View) container.getParent();
            if(oldParent != container){
                ((ViewGroup)oldParent).removeView(fragmentLayout);
            }
            //return fragmentLayout;
        }else {
            fragmentLayout = (ViewGroup) inflater.inflate(R.layout.fragment_plan, container, false);
        }

        if(startEditText == null){
            startEditText = (SupportPlaceAutocompleteFragment) getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
            ((ImageButton) startEditText.getView().findViewById(R.id.place_autocomplete_search_button)).setImageResource(R.drawable.ic_search_white_24dp);
            startEditText1 = (EditText) fragmentLayout.findViewById(R.id.place_autocomplete_search_input);
            ((EditText) startEditText.getView().findViewById(R.id.place_autocomplete_search_input)).setTextColor(Utils.getColor(getActivity(), R.color.white));
            ((EditText) startEditText.getView().findViewById(R.id.place_autocomplete_search_input)).setHintTextColor(Utils.getColor(getActivity(), R.color.white));
            startEditText.setHint("Starting");

        }

        if(endEditText == null){

            endEditText = (SupportPlaceAutocompleteFragment) getChildFragmentManager().findFragmentById(R.id.endEditText_place_autocomplete_fragment);
            ((ImageButton) endEditText.getView().findViewById(R.id.place_autocomplete_search_button)).setImageResource(R.drawable.ic_search_white_24dp);
            endEditText1 = (EditText) fragmentLayout.findViewById(R.id.place_autocomplete_search_input);
            ((EditText) endEditText.getView().findViewById(R.id.place_autocomplete_search_input)).setTextColor(Utils.getColor(getActivity(), R.color.white));
            ((EditText) endEditText.getView().findViewById(R.id.place_autocomplete_search_input)).setHintTextColor(Utils.getColor(getActivity(), R.color.white));
            endEditText.setHint("Ending");

            endEditText.setOnPlaceSelectedListener(new PlaceSelectionListener() {
                @Override
                public void onPlaceSelected(Place place) {
                    // TODO: Get info about the selected place.
                    Log.i(TAG, "Place: " + place.getName());
                    endLatLng = place.getLatLng();
                }

                @Override
                public void onError(Status status) {
                    // TODO: Handle the error.
                    Log.i(TAG, "An error occurred: " + status);
                }
            });
        }




        if(startEditText == null){
//            startEditText = (SupportPlaceAutocompleteFragment) SupportPlaceAutocompleteFragment.instantiate(getActivity(), "com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment");
            startEditText.setOnPlaceSelectedListener(new PlaceSelectionListener() {
                @Override
                public void onPlaceSelected(Place place) {
                    // TODO: Get info about the selected place.
                    Log.i(TAG, "Place: " + place.getName());
                    startLatLng = place.getLatLng();
                }

                @Override
                public void onError(Status status) {
                    // TODO: Handle the error.
                    Log.i(TAG, "An error occurred: " + status);
                }
            });
        }

        return fragmentLayout;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        checkPermission();

        startCurrent = (ImageButton) fragmentLayout.findViewById(R.id.startCurrent);
        routeButton = (Button) fragmentLayout.findViewById(R.id.takeMeBtn);


        dateEditText = (EditText) fragmentLayout.findViewById(R.id.date);
        timeEditText = (EditText) fragmentLayout.findViewById(R.id.time);


        dateEditText.setInputType(InputType.TYPE_NULL);
        dateEditText.setOnClickListener(this);
        (fragmentLayout.findViewById(R.id.dateView)).setOnClickListener(this);

        timeEditText.setInputType(InputType.TYPE_NULL);
        timeEditText.setOnClickListener(this);
        (fragmentLayout.findViewById(R.id.timeView)).setOnClickListener(this);

        startCurrent.setOnClickListener(this);
        routeButton.setOnClickListener(this);



    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.timeView:
            case R.id.time:
                new TimePickerDialog(getActivity(), timeSetListener, myCalendar
                        .get(Calendar.HOUR_OF_DAY), myCalendar.get(Calendar.MINUTE), true).show();
                break;
            case R.id.dateView:
            case R.id.date:
                new DatePickerDialog(getActivity(), date, myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                break;
            case R.id.startCurrent:
                checkPermission();
                break;
            case R.id.takeMeBtn:
                if (!((EditText) startEditText.getView().findViewById(R.id.place_autocomplete_search_input)).getText().toString().trim().isEmpty() && !((EditText) endEditText.getView().findViewById(R.id.place_autocomplete_search_input)).getText().toString().trim().isEmpty() && !dateEditText.getText().toString().trim().isEmpty() && !timeEditText.getText().toString().trim().isEmpty()) {
                    Intent routeIntent = new Intent(getActivity(), RouteActivity.class);
                    Routes route = new Routes();
                    route.setStartLocation(((EditText) startEditText.getView().findViewById(R.id.place_autocomplete_search_input)).getText().toString().trim());
                    route.setEndLocation( ((EditText) endEditText.getView().findViewById(R.id.place_autocomplete_search_input)).getText().toString().trim());
                    route.setStartLatLng(startLatLng);
                    route.setEndLatLng(endLatLng);
                    Toast.makeText(getActivity(), journeyDate.toString(), Toast.LENGTH_LONG).show();
                    CustomLog.printVerbose(TAG, journeyDate.toString());
                    route.setJourneyTime(journeyDate);
                    RouteSingleTon.getInstance().setRoutes(route);

                    startActivity(routeIntent);
                } else {
                    Utils.showAlertDialog(getActivity(), "All field are required");
                }
                break;
            default:
                break;
        }
    }

    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            journeyDate = new DateTime(year, monthOfYear + 1, dayOfMonth, journeyDate.getHourOfDay(), journeyDate.getMinuteOfHour());
//            Toast.makeText(getActivity(), journeyDate.toString(), Toast.LENGTH_LONG).show();
            updateDate();
        }

    };

    final TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int i, int i1) {
            timeEditText.setText(i + ":" + i1);
            journeyDate = new DateTime(journeyDate.getYear(), journeyDate.getMonthOfYear(), journeyDate.getDayOfMonth(), i, i1);
//            Toast.makeText(getActivity(), journeyDate.toString(), Toast.LENGTH_LONG).show();
        }
    };

    private void updateDate() {
        String myFormat = "MM/dd/yy"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

        dateEditText.setText(sdf.format(myCalendar.getTime()));
    }

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


    void checkPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_ACCESS_COARSE_LOCATION);

        } else {

            new GpsCall().execute("");
//            gps = new GPSTracker(getActivity(), getActivity());

//            // Check if GPS enabled
//            if (gps.canGetLocation()) {
//
//                double latitude = gps.getLatitude();
//                double longitude = gps.getLongitude();
//
//                // \n is for new line
//                GeoApiContext context = new GeoApiContext().setApiKey(Constants.API_KEY_GMAP);
//                try {
//                    GeocodingResult coding[] = GeocodingApi.newRequest(context).latlng(new LatLng(gps.getLatitude(), gps.getLongitude())).await();
//                    if (startEditText != null)
//                        startEditText.setText(coding[0].formattedAddress + "");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            } else {
//                // Can't get location.
//                // GPS or network is not enabled.
//                // Ask user to enable GPS/network in settings.
//                gps.showSettingsAlert();
//            }
        }
//        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
//                != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(getActivity(), new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
//                    PERMISSION_ACCESS_COARSE_LOCATION);
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_ACCESS_COARSE_LOCATION:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the

                    // contacts-related task you need to do.

                    new GpsCall().execute("");

//                    gps = new GPSTracker(getActivity(), getActivity());
//
//                    // Check if GPS enabled
//                    if (gps.canGetLocation()) {
//
//                        double latitude = gps.getLatitude();
//                        double longitude = gps.getLongitude();
//
//                        // \n is for new line
//                        //Toast.makeText(getActivity(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
//                        GeoApiContext context = new GeoApiContext().setApiKey(Constants.API_KEY_GMAP);
//                        try {
//                            GeocodingResult coding[] = GeocodingApi.newRequest(context).latlng(new LatLng(gps.getLatitude(), gps.getLongitude())).await();
//                            if (startEditText != null)
//                                startEditText.setText(coding[0].formattedAddress + "");
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    } else {
//                        // Can't get location.
//                        // GPS or network is not enabled.
//                        // Ask user to enable GPS/network in settings.
//                        gps.showSettingsAlert();
//                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                    Toast.makeText(getActivity(), "You need to grant permission", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }


    private class GpsCall extends AsyncTask<String, Long, String> {
        @Override
        protected String doInBackground(String... params) {
            gps = new GPSTracker(getActivity(), getActivity());
            if (gps.canGetLocation()) {

//                double latitude = gps.getLatitude();
//                double longitude = gps.getLongitude();

                GeoApiContext context = new GeoApiContext().setApiKey(Constants.API_KEY_GMAP);
                try {
//                            GeocodingResult coding[] = GeocodingApi.newRequest(context).latlng(new com.google.maps.model.LatLng(gps.getLatitude(), gps.getLongitude())).await();
                    GeocodingResult coding[] = GeocodingApi.newRequest(context).latlng(new LatLng(gps.getLatitude(), gps.getLongitude())).await();
                    if (coding.length > 0) {
                        RouteSingleTon.getInstance().getRoutes().setStartLatLng(new com.google.android.gms.maps.model.LatLng(gps.getLatitude(), gps.getLongitude()));
                        return coding[0].formattedAddress + "";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // Can't get location.
                // GPS or network is not enabled.
                // Ask user to enable GPS/network in settings.
                gps.showSettingsAlert();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            Log.v("msg", "gps response");
            if (response != null) {
                if (startEditText != null)
                    startEditText.setText(response + "");

            }
            //setTextToTextView(jsonArray);


        }
    }

    private void getCurrentLocation() {
        CustomLocationManager.getCustomLocationManager().getCurrentLocation(getActivity(), locationValue);
    }

    public LocationValue locationValue = new LocationValue() {
        @Override
        public void getCurrentLocation(Location location) {
            // You will get location here if the GPS is enabled
            if (location != null) {
                Log.d("LOCATION", location.getLatitude() + ", " + location.getLongitude());
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (startEditText != null)
            startEditText.onResume();
        if (endEditText != null)
            endEditText.onResume();

    }
//


    @Override
    public void onPause() {
        super.onPause();
        if (startEditText != null)
            startEditText.onPause();
        if (endEditText != null)
            endEditText.onPause();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (startEditText != null)
            startEditText.onDestroy();
        if (endEditText != null)
            endEditText.onDestroy();
//        getChildFragmentManager().beginTransaction().remove(startEditText).commit();
//        getChildFragmentManager().beginTransaction().remove(endEditText).commit();
    }
}

1 个答案:

答案 0 :(得分:0)

这是我在通过SupportPlaceAutocompleteFragment.class代码后修复它以查看按钮文本如何与所选位置一起设置的方法。

我注意到它从Edittext获取文本(R.id.place_autocomplete_search_input)

所以这就是我所做的。

初始化位置

location = (SupportPlaceAutocompleteFragment)
                getChildFragmentManager()
                        .findFragmentById(R.id.place_autocomplete_fragment);


placetxt=(EditText)editprofileview.findViewById(R.id.place_autocomplete_search_input);

这就是我用try / catch

设置文本的方法
try {
        location.setText("Accra,Ghana");
    }catch (Exception e){
        Log.e(TAG," "+e);
        placetxt.setText("Accra,Ghana");
    }

假设:按钮文本使用edittext中的文本设置。