NullPointerException при изменении подсказки PlaceAutoCompleteFragment
В одном из моих фрагментов я реализовал PlaceAutocompleteFragment следующим образом:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
placeAutocompleteFragment = new SupportPlaceAutocompleteFragment();
getChildFragmentManager().beginTransaction()
.replace(R.id.place_autocomplete_fragment_container, placeAutocompleteFragment)
.addToBackStack(SupportPlaceAutocompleteFragment.class.getName())
.commit();
EditText etPlace = (EditText) placeAutocompleteFragment.getView().findViewById(R.id.place_autocomplete_search_input);
etPlace.setHint("Type your address");
}
Последние две строки - моя попытка изменить текст подсказки в строке поиска. Однако, когда я добавляю их, я получаю исключение
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
Я также попробовал placeAutocompleteFragment.setHint(). Как я должен идти о вызове setHint () вместо этого? Заранее спасибо.
Изменить: Журнал аварии показывает следующее
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setHint(java.lang.CharSequence)' on a null object reference
at me.user.appname.ExploreFragment.onCreateView(ExploreFragment.java:99)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2425)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2623)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2410)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2365)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2242)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:654)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:168)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1244)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1092)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1622)
at android.view.View.measure(View.java:23265)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:23265)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:23265)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23265)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:23265)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:23265)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6928)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:898)
at android.view.View.measure(View.java:23265)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2832)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1869)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2124)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1738)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7745)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
at android.view.Choreographer.doCallbacks(Choreographer.java:723)
at android.view.Choreographer.doFrame(Choreographer.java:658)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938) 08-05 01:26:32.231 28683-28683/me.user.appname E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Редактировать #2: Основы моего ExploreFragment
public class ExploreFragment extends Fragment {
GeoDataClient mGeoDataClient;
SupportPlaceAutocompleteFragment placeAutocompleteFragment;
private OnFragmentInteractionListener mListener;
public ExploreFragment() {
// Required empty public constructor
}
public static ExploreFragment newInstance(String param1, String param2)
{
ExploreFragment fragment = new ExploreFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_explore,
container, false);
mGeoDataClient = Places.getGeoDataClient(getActivity());
placeAutocompleteFragment = new SupportPlaceAutocompleteFragment();
getChildFragmentManager().beginTransaction()
.replace(R.id.place_autocomplete_fragment_container, placeAutocompleteFragment)
.addToBackStack(SupportPlaceAutocompleteFragment.class.getName())
.commit();
EditText etPlace = (EditText) rootView.findViewById(R.id.place_autocomplete_search_input);
etPlace.setHint("Type your address");
return rootView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onAttachFragment(Fragment childFragment) {
super.onAttachFragment(childFragment);
((SupportPlaceAutocompleteFragment) childFragment).setOnPlaceSelectedListener(
new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// set place variables here
}
@Override
public void onError(Status status) {
Log.i("OnPlaceSelected", "An error occurred: " + status);
}
}
);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// methods here
}
}
2 ответа
Переместите следующий код в свой placeAutocompleteFragment
внутри onCreateview
Я заменил placeAutocompleteFragment.getView()
с view
EditText etPlace = (EditText) view.findViewById(R.id.place_autocomplete_search_input);
etPlace.setHint("Type your address");
В своем первом фрагменте кода вы использовали:
EditText etPlace = (EditText) placeAutocompleteFragment.getView().findViewById(R.id.place_autocomplete_search_input);
Но во втором фрагменте вы использовали
EditText etPlace = (EditText) rootView.findViewById(R.id.place_autocomplete_search_input);
Можете ли вы отладить и убедиться, что ваш текст редактирования etPlace не нулевой?
Когда вы используете SupportPlaceAutocompleteFragment, ваша деятельность должна быть реализована AppCompatActivity
(или же FragmentActivity
и использовать getSupportFragmentManager()
) чтобы добраться до ваших фрагментов.
Для второго варианта вы можете создать PlaceAutoCompleteFragment
вместо SupportPlaceAutoCompleteFragment
,