1

私はSupportPlaceAutocompleteFragmentを私のアプリケーションに統合しています。 次の断片がViewPager内..です私のアプリがクラッシュしたすべてが初めて正常に動作します...しかし、私は二度目のフラグメントに入るとき..私は、次のエラーを取得しています:SupportPlaceAutocompleteFragment null例外

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(); 
    } 
} 

答えて

0

これは私がボタンのテキストを選択した場所に設定されているか確認するためにSupportPlaceAutocompleteFragment.classコードを通過した後にそれを固定する方法です。

は、私はそれが

だから、これは私がやったことあるEDITTEXT(R.id.place_autocomplete_search_input)からテキストを取得します気づきました。ボタンのテキストのEditTextからテキストを使用して設定されています

初期の場所が

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


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

これは私が

try { 
     location.setText("Accra,Ghana"); 
    }catch (Exception e){ 
     Log.e(TAG," "+e); 
     placetxt.setText("Accra,Ghana"); 
    } 

仮定はのtry/catchでテキストを設定する方法です。