I have a fragment that contains a MapView and it works by itself. When I launch that same fragment inside another fragment the app crashes.
My app crashes after mapView.onCreate(null) with the following stack. However it only crashes when it is nested in another fragment.
java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.view.ViewGroup
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1282)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2426)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2205)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2161)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2062)
at android.app.FragmentManagerImpl.dispatchMoveToState(FragmentManager.java:3051)
at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2998)
at android.app.Fragment.performActivityCreated(Fragment.java:2537)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1318)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2426)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2205)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2161)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2062)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:738)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
This is my fragment which works by itself
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_map_view, container, false);
setup();
return view;
}
private void setup() {
mapView = view.findViewById(R.id.mapViewFragment);
mapView.onCreate(null);
mapView.onResume();
MapsInitializer.initialize(this.getActivity().getApplicationContext());
}
and this is how I am nesting the fragments
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.frameLayoutBuffer, new MapViewFragment()).commit();
The id is from a framelayout.
If I change to another Fragment, the other fragment displays just fine, so it something to do with the MapView.
Both fragments also do not contain any ImageView, any help about this problem will be appreciated.
I fixed by calling the setup method inside the onResume() and changing view.findViewById() to getView().findViewbyId()
Edit: Actually that did not fix the problem. I added a delay before creating the map in another thread, and that seemed to fix.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
i have been creating an App that uses Fragments Mostly
here is how it is supposed to work, on the Home Fragment i click a button that takes me to another Fragment for filling information
on this fragment when I click a button a Dialog Fragment opens and I select a City Name then Submit, it dismisses the Dialog and is supposed to SetText on a TextView.
I use an interface that calls a method on the City Selection fragment in order to set the Text. here is some Code
Declaration for the EditText
EditText editText_From;
Setting finding the View
OnCreate
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_trip_date, container, false);
editText_From = view.findViewById(R.id.editText_From);
return view;
}
public void setSelectedCity(String city)
{
Log.i("<<269>>", "Setting Text on Edit Text <<269>>:" + city);
editText_From.setText(city);
}
This Method below is supposed to set text for the my EditText or TextView
public void setSelectedCity(String city)
{
Log.i("<<269>>", "Setting Text on Edit Text <<269>>:" + city);
selectedCityConfirmed = city;
editText_From.setText(city);
}
the App Crashes on EditText with the Following Error Message,
02-16 19:37:43.928 26582-26582/com.example.bob2609.busticketingapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bob2609.busticketingapp, PID: 26582
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference
at com.example.bob2609.busticketingapp.TripDateFragment.setSelectedCity(TripDateFragment.java:188)
at com.example.bob2609.busticketingapp.MainActivity.selectedCity(MainActivity.java:176)
at com.example.bob2609.busticketingapp.LocationSelector$1.onItemClick(LocationSelector.java:69)
at android.widget.AdapterView.performItemClick(AdapterView.java:313)
at android.widget.AbsListView.performItemClick(AbsListView.java:1201)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3195)
at android.widget.AbsListView$3.run(AbsListView.java:4138)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
The Interface Method on MainActivity
#Override
public void selectedCity(String city)
{
tripDateFragment.setSelectedCity(city);
}
Anyone knows a way around this?
Why are you declaring again Textview again in onCreate Method?
Declare outside the onCreate and Find the View using "findViewByID" inside on create.
I have written an app with OSMdroid using activities, but I am now trying to port it over to fragments instead (I'm new to fragments though). I am getting the error:
"java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setBuiltInZoomControls(boolean)' on a null object reference"
It seems that the MapView has not yet been initialised, am I initialising in the wrong place (OnCreateView)? According to the activity lifecycle, OnCreate is called before OnCreateView, so it would make sense that it is not recognised, but I am confused as to where then to put my code.
Code for my implementation of the fragment:
//inflating fragment layout
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
map = (MapView) view.findViewById(R.id.map);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));
setupMap();
}
//initializing map
private void setupMap() {
//adding zoom and touch controls
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
//getting current location using coarse/fine location so we can set centerpoint
currentLocation = getCurrentLocation();
... code continues ...
Error stack trace:
java.lang.NullPointerException: Attempt to invoke virtual method 'void org.osmdroid.views.MapView.setBuiltInZoomControls(boolean)' on a null object reference
at skicompanion.skicompanion.MapFragment.setupMap(MapFragment.java:101)
at skicompanion.skicompanion.MapFragment.onCreate(MapFragment.java:86)
at android.app.Fragment.performCreate(Fragment.java:2214)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1153)
at android.app.BackStackRecord.run(BackStackRecord.java:800)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:487)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
In your posted code it doesn't look like you need to override onCreate method in your case. just move this code:
context = getActivity();
Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));
setupMap();
into the onCreateView method before the return call and should be ok.
I am doing a project on android studio. The problem is I cannot add a fragment class to my project. I was able to add two fragment classes when I started doing this project. But, after completing about half of my project, now I cannot add a third fragment class. When I add a third fragment class and run my project, this exception pops up:
java.lang.NoSuchMethodError: No static method zzb(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzaa; or its super classes (declaration of 'com.google.android.gms.common.internal.zzaa' appears in /data/data/com.hashcoder.eegoomain/files/instant-run/dex/slice-com.google.android.gms-play-services-basement-10.0.1_d1c25087bea669c827e484b09b1949315ba5fc5f-classes.dex)
at com.google.firebase.provider.FirebaseInitProvider.zza(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
at android.app.ActivityThread.installProvider(ActivityThread.java:5172)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4767)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4707)
at android.app.ActivityThread.access$1600(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
And I tried both android.app.Fragment or android.support.v4.app.Fragment. Both doesn't work.....
Try this.Make a java class and extends it from Fragment.
This is the basic structure of a fragment class.
public class MyFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.<your xml layout>, container, false);
//Do your work here
return view;
}
}
and make sure you extends it from android.support.v4.app.Fragment
MainActivity.java
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentOne fragment = new FragmentOne();
fragmentTransaction.add(R.id.layoutFragmentContainer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
...
FragmentOne.java
public class FragmentOne extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list,container,false);
}
}
When I click the button search , the fragment appears , but when I click it again the application crashes.Can someone help , I am new in android and I can't solve this problem.
....
log:
Process: com.example.user1.volleyballmanager, PID: 26892
java.lang.IllegalStateException: commit already called
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:625)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:617)
at com.example.user1.volleyballmanager.MainActivity$2.onClick(MainActivity.java:52)---
line 52 : fragmentTransaction.commit();
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Put this method into your main activity
//FRAGMENT BACK STACK
public void getFragmentWithTag(Fragment fragment, String tag) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.replace(R.id.activityFrame, fragment, tag).commit();
}
You can call it from your fragment like this..
activity.getFragmentWithTag(Fragment, FragmentTag)
you cannot have multiple transaction commits.
So you need to begin and close the transaction. So when you click one, it works. Then you click again, and it give you error which says one transaction<--> one commit.
I am trying to change elements such TextViews etc. that are parts of the Fragment (which is used for SlidingTabLayout). I can access TextView from the Tab1 class:
public class Tab1 extends Fragment {
public static TextView serverName;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_1,container,false);
serverName = (TextView) view.findViewById(R.id.serverName);
serverName.setText("This works, but I can't change text from outside the Tab1 class");
return view;
}
But when I want access the serverName TextView from anywhere I am always getting null value. Here I am trying to change the text from the activity which contains Sliding Tabs (Tab1 is a part of it):
public class Dashboard2 extends AppCompatActivity {
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence tabsTitles[] = {"Info", "Options"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard2);
InitializeToolbarAndTabs();
Tab1.serverName.setText("This doesn't work");
}
private void InitializeToolbarAndTabs()
{
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), tabsTitles, tabsTitles.length);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
}
}
Logs from the Android Studio:
java.lang.RuntimeException: Unable to start activity ComponentInfo{ASD.Dashboard2}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3119)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3218)
at android.app.ActivityThread.access$1000(ActivityThread.java:198)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1676)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6837)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at ASD.Dashboard2.onCreate(Dashboard2.java:54)
at android.app.Activity.performCreate(Activity.java:6500)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3072)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3218)
at android.app.ActivityThread.access$1000(ActivityThread.java:198)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1676)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6837)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference - how to solve this problem?
Not sure what you are doing but you can always find your fragment by FragmentManage.findFragmentByTag() or FragmentManager.findFragmentById().
Once found just access your field.
I don't think you have initialized the Tab1 fragment, at least I can't see it there.
Accessing fragment variables from an Activity through static declarations is a horrible idea, use voids in the fragment class.
I am sorry, the error you are getting is not related with accessing or not a static object of the Fragment. The error you are receiving is because at the moment you call Tab1.serverName.setText("This doesn't work"); your fragment still didnt inflate the view or still didn't charge the TextView (didn't arrive yet to serverName = (TextView) view.findViewById(R.id.serverName);). The fragments are charged into the view in a asynchrounous way, so even if you declare it in your layout as a tag, it may be possible that the Fragment's view is still not fully loaded.
If you absolutely want to be sure the fragment's view is fully loaded, use the protected void onResumeFragments() method:
#Override
protected void onResumeFragments() {
super.onResumeFragments();
Tab1.serverName.setText("This doesn't work");
}
Anyway, I strongly recommend you NOT to access fragment objects statically, but to use the findFragmentById() or findFragmentByTag() methods and then to access a public method inside the given fragment.
Hope it helps.