Exception when referencing MapView in a fragment - OSMdroid - java

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.

Related

findViewById in Fragment cannot obtain its View(on a null object reference)

#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_map,container,false);
Button btn_new = rootView.findViewById(R.id.btn_new);
//Button btn_new = getView().findViewById(R.id.btn_new);I have tried this code as well, but it still failed.
btn_new.setText("text");
return rootView;
}
//onViewCreated() cannot resolve this problem.
//#Override
//public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
// Button btn_new =getActivity().findViewById(R.id.btn_new);
//}
I used "import androidx.fragment.app.Fragment;"
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference
at com.example.flightnavigation.AirportsFragment.onCreateView(AirportsFragment.java:90)

Is there any method after creating the view of fragments?How to change Layout of tabs after creating fragments

I need to call a method in which I parse the JSON objects and set the values I sets values in TextFields and button values, I created fragments but after creating the fragments how will I change the text field values
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
//Switch to different layout accordingly
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1: {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
break;
}
case 2: {
rootView = inflater.inflate(R.layout.fragment_receipt, container, false);
break;
}
case 3: {
rootView = inflater.inflate(R.layout.fragment_totals, container, false);
break;
}
case 4: {
rootView = inflater.inflate(R.layout.fragment_keyboard, container, false);
break;
}
case 5: {
rootView = inflater.inflate(R.layout.fragment_keylock, container, false);
break;
}
}
return rootView;
}
}
I tried to call the method in onStart but onStart method is been called first before the onCreateView and hence I get null pointer exception when I am assigning the value :
#Override
public void onStart() {
super.onStart();
parseJsonResponse(response_message);
}
In the parseJsonResponse() method, I sets the value
String UIFooter = ResponseHeaderObject.getString("FOOTER");
//Set Header Display
headerTextView =(TextView) findViewById(R.id.headerTextView);
headerTextView.setText(UIHeader);
here is the error from logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.mpos.kits.smartpos.PosMainActivity.parseJsonResponse(PosMainActivity.java:366)
Fragments have a function named: onViewCreated which called after your view was created
Yes, that method exists: onViewCreated. however, if you want to assign a text to the TextView outside the method on which it has been created, you have to declare the TextView as a member property (outside any method), to allow its use by all class methods. Otherwise, within a fragment, it will be difficult to manipulate it.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.mpos.kits.smartpos.PosMainActivity.parseJsonResponse(PosMainActivity.java:366)
You are getting this error because this headerTextView =(TextView) findViewById(R.id.headerTextView); returns null in your fragment unless it's referred to a root view like in the onCreateView method. this way (TextView) rootView.findViewById(R.id.section_label);
If you want to override onViewCreated method, do it this way:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//your code
}

Android view is null object reference inside fragment

i'm having a hard time with some code. I am using sliding tabs with 2 fragment. Inside one of my fragment i'm trying to get a LinearLayout and add some stuff in it but everytime i try to do getView().findViewByID() I got null object reference
I'm calling the function after the onCreateView() I tried making a variable of type View and putting the View that i inflate in the onCreateView in it but i keeps getting the same error. I also tried putting a if() before to check if view isnt null , but even with this , I get null object reference. Can someone help me ?
public class listAlarmFragment extends Fragment{
public View view = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle){
View v = inflater.inflate(R.layout.list_alarm,vg,false);
view = v;
return v;
}
public void showAlarm(Cursor c){
if(view != null) { //even with that check, I got a null pointer exception
LinearLayout baseList = (LinearLayout) view.findViewById(R.id.baseList); // NullPointerException: Attempt to invoke virtual method on a null object reference
}
}
}
Replacing view with getView() doesnt change anything.
This is how I'm calling the function from the Main Activity
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment c = adapter.getItem(0);
((listAlarmFragment)(c)).showAlarm(dbHelper.getAlarm()); // where I call the function
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I'm opening this fragment at the beggining when my app open. It crashs when im trying to switch to another fragment.
here is the stack trace :
04-02 18:41:54.615 31584-31584/al.demo.alarmmanagerdemo E/AndroidRuntime: FATAL EXCEPTION: main
Process: al.demo.alarmmanagerdemo, PID: 31584
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at al.demo.alarmmanagerdemo.fragment.listAlarmFragment.showAlarm(listAlarmFragment.java:83)
at al.demo.alarmmanagerdemo.MainActivity$1.onPageSelected(MainActivity.java:54)
at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1971)
at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:689)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:673)
at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2288)
at android.view.View.dispatchTouchEvent(View.java:10779)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2858)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2534)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2864)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2549)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:605)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1895)
at android.app.Activity.dispatchTouchEvent(Activity.java:3241)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:567)
at android.view.View.dispatchPointerEvent(View.java:11008)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5155)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5007)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4585)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4551)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4684)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4559)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4741)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4585)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4551)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4559)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7092)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7024)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6985)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7202)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:323)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:6776)
04-02 18:41:54.615 31584-31584/al.demo.alarmmanagerdemo E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1510)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1400)
I would do something like this,
public class listAlarmFragment extends Fragment{
//public View view = null; // no need
private LinearLayout baseList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle bundle){
View v = inflater.inflate(R.layout.list_alarm,vg,false);
baseList = (LinearLayout) v.findViewById(R.id.baseList);
//view = v; no need
return v;
}
public void showAlarm(Cursor c){
if(baseList!=null){
//do something with your baseList
}
}
}
Also check R.id.baseList exists in the layout xml R.layout.list_alarm.
and it should be LinearLayout with
id=#+id/baseList

Android: Can't access static elements outside Fragment class

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.

Getting Id of a Textview in a fragment OnCreate() method

I am trying to get the Id of a text view in a fragment's onCreate() method. It returns null everytime.
I want to display my contacts in a fragment. For that at the end of FetchContact() method I assign the contact list to TextView.
Since my code is returning null when I find the TextView my application gives NullPointerException.
Anyone who could tell me how to get the Id of TextView of a Fragment in onCreate() method.
I tried making an object of activity class to get the TextView, still the code returned null. No luck.
public class ContactsFragment extends Fragment {
public TextView outputtext;
Context context;
class ActivityObj extends Activity{
public TextView text;
Context objContext;
#Override
public void onCreate(Bundle savedInstanceState) {
text =(TextView)findViewById(R.id.textContact);
objContext = getApplicationContext();
super.onCreate(savedInstanceState);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
ActivityObj obj = new ActivityObj();
super.onCreate(savedInstanceState);
outputtext =(TextView) getView().findViewById(R.id.textContact);
// outputtext= obj.text;
context=getActivity().getApplicationContext();
//fetchContacts();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.contacts_layout, container, false);
return rootView;
}
find the TextView my application gives NullPointerException.
Because in Fragment lifecycle onCreate method called before onCreateView method.
override onViewCreated which call after onCreateView method and use use first parameter of onViewCreated method for accessing views from Fragment layout:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView text =(TextView)view.findViewById(R.id.textContact);
/// your code here....
}
use
rootView.findViewById(R.id....) in your oncreateView there is where you should do the UI related work
You should use like this on onActivityCreated method
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView tv = (TextView) getActivity().findViewById(R.id.textView1);
}
}
Or use callbacks
You cannot initialize any view using findViewById before onCreateView method calls.
So you must have to wait for the callback to run. And there are two ways to get it. And it will work on onActivityCreated because it called after onCreateView
As described by ρяσѕρєя K using the View param came from onViewCreated.
You can call getView() in any callback(delegate) which call after
onCreateView()
Like
TextView tv = (TextView) getView().findViewById(R.id.tv_id);

Categories