I have a bunch of fragments in a FragmentPagerAdapter with one ImageView in side each fragment. If I swipe really fast this error comes up:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wilsapp.wilsapp, PID: 21319
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.wilsapp.wilsapp.Fragments.BuyerHomePageFragment9$DownloadImageTask.onPostExecute(BuyerHomePageFragment9.java:212)
at com.wilsapp.wilsapp.Fragments.BuyerHomePageFragment9$DownloadImageTask.onPostExecute(BuyerHomePageFragment9.java:192)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
If I swipe slowly then it works perfectly fine.
Android Code (code is the same for each fragment. Code in AsyncTask):
protected void onPostExecute(Bitmap result) {
try {
ImageView img = (ImageView) getView().findViewById(R.id.ProductOneImageView);
img.setImageBitmap(result);
}catch (Exception e){
ImageView img = (ImageView) getView().findViewById(R.id.ProductOneImageView);
int id = getResources().getIdentifier("com.wilsapp.wilsapp:drawable/" + "error", null, null);
img.setImageResource(id);
}
}
Android onCreatView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_buyer_home_page, container, false);
return view;
}
how can i avoid the NullPointerException?
ImageView img = (ImageView) getView().findViewById(R.id.ProductFiveImageView);
ImageView need initialize in onCreateView. A case of you getView() return null...
Add your initialization snippet in onViewCreated method instead of onCreateView. it will ensure that imageview will be initialize after your view is inflated.
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
ImageView img = (ImageView) view.findViewById(R.id.ProductFiveImageView);
img.setImageBitmap(result);
}
ImageView img = (ImageView) getView().findViewById(R.id.ProductFiveImageView);
hi You can add a judgment,getView Whether to null, and Fault tolerant processing!
Related
I'm stuck at this point:
I have a RecyclerView with a list of CardViews.
When a button is pressed, the addItem(); method is called, which obviously adds an item.
Here's how:
String text = hwtext.getText().toString();
mList.add(new HomeWork_Item(the.image.I.want, text));
mAdapter.notifyItemInserted(mList.size());
Which works, great!
Now, I have added a Spinner. The spinner contains a few Subjects. If, let's say, the subject history is selected, I'd like to change the.image.I.want from the addItem(); method to another one in the drawable.
I tried using glide but this didn't work:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String SpinnerText = parent.getItemAtPosition(position).toString();
Toast.makeText(getContext(), SpinnerText, Toast.LENGTH_SHORT).show();
if (SpinnerText.equals("History")) {
Glide.with(getActivity()).load(R.drawable.history).into(R.id.theImageView);
}
}
Notice: The Item would be added only when a button is pressed which calls the method to add it. After selecting a Subject it should just prepare the Image to use when the Item will be added.
Thanks!
Crash Logcat:
2019-03-08 14:59:10.328 9808-9808/com.reogen.ssr E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reogen.ssr, PID: 9808
java.lang.NullPointerException: Argument must not be null
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:31)
at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:25)
at com.bumptech.glide.RequestBuilder.into(RequestBuilder.java:685)
at com.reogen.ssr.Fragments.Homework.onItemSelected(Homework.java:170)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:1331)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:1320)
at android.widget.AdapterView.-wrap1(Unknown Source:0)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:1282)
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)
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)
Create an ImageView as
ImageView historyImage = findViewById(R.id.historyImage);
Then in your glide you do this :
Glide.with(view.getContext()).load(R.drawable.history).into(historyImage);
You are passing an int into the into and you should pass the ImageView directly.
Edit
Change your code to this one
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_homework, container, false);
insert = rootView.findViewById(R.id.insert_text);
hwtext = rootView.findViewById(R.id.hwinput);
SubjectImage = rootView.findViewById(id.HWImage);
spinner = rootView.findViewById(R.id.spinner);
buildView(rootView);
return rootView;
}
public void buildView(View rootView) {
mRecyclerView = rootView.findViewById(R.id.RecycleHW);
mRecyclerView.setHasFixedSize(true);
mManager = new LinearLayoutManager(getActivity());
mAdapter = new HomeWorkAdapter(mList);
mRecyclerView.setLayoutManager(mManager);
mRecyclerView.setAdapter(mAdapter);
}
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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to do a simple operation: click a button and show a custom DialogFragment, but I'm getting a NullPointExpection and I can't figure out why.
mAlertDialog.java:
public class mAlertDialog extends DialogFragment {
TextView title;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_invalid_time, container, false);
title = (TextView)view.findViewById(R.id.titleText);
return view;
}
public void setTheTitle(String title) {
this.title.setText(title);
}
}
Showing mAlertDialog:
mAlertDialog dialog = new mAlertDialog();
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));
dialog.show(fm, "InvalidTime");
Error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at m.inschool8.Objects.mAlertDialog.setTheTitle(mAlertDialog.java:20)
at m.inschool8.bSubjects.Fragment_Subjects$55.onClick(Fragment_Subjects.java:2654)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The title is still null when you are calling
mAlertDialog dialog = new mAlertDialog();
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));
so what you can do is
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_invalid_time, container, false);
title = (TextView)view.findViewById(R.id.titleText);
setTheTitle(getActivity().getString(R.string.invalidTimeTitle));
return view;
}
// call it
mAlertDialog dialog = new mAlertDialog();
dialog.show(fm, "InvalidTime");
Your title is null until the DialogFragment is shown causing onCreateView to kick-in. Hence change the order as below:
mAlertDialog dialog = new mAlertDialog();
dialog.show(fm, "InvalidTime");
dialog.setTheTitle(getActivity().getString(R.string.invalidTimeTitle));
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.
I'm trying to declare a Button on my APP (It's on a fragment), what I've tried is:
TextView tvPregunta = (TextView) getActivity().findViewById(R.id.tvPregunta);
It does not give me an error, but when I'm launching the APP it does...
My LogCat error is :
01-30 08:22:18.865 16165-16165/joancolmenero.taulaperiodica.com.taulaperiodicaapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: joancolmenero.taulaperiodica.com.taulaperiodicaapp, PID: 16165
java.lang.NullPointerException
at joancolmenero.taulaperiodica.com.taulaperiodicaapp.JocFragment.seguentelement(JocFragment.java:102)
at joancolmenero.taulaperiodica.com.taulaperiodicaapp.JocFragment.onCreateView(JocFragment.java:90)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
This line is the TextView tvPregunta. :
at joancolmenero.taulaperiodica.com.taulaperiodicaapp.JocFragment.seguentelement(JocFragment.java:102)
And this one is seguentelement(); :
at joancolmenero.taulaperiodica.com.taulaperiodicaapp.JocFragment.onCreateView(JocFragment.java:90)
seguentelement() it's a private void created out of onCreateView, so my question is why is this TextView crashing?
I've got a onCreateView where I've got the rootview and the calls of the voids...
onCreateView
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.joc_fragment, container, false);
// Titol del joc
TextView tvJuego = (TextView) rootView.findViewById(R.id.tvJuego);
// shadow del textview
tvJuego.setShadowLayer(1, 0, 3, Color.GRAY);
// creem una variable per a cada ib
// NewGame HIDEEEEEEEEEE
NewGame = (Button)rootView.findViewById(R.id.btNewGame);
NewGame.setVisibility(View.INVISIBLE);
NewGame.setText("");
// IB --> ID imageButton
berijuego=(ImageButton)rootView.findViewById(R.id.ibBeriJuego);
borojuego=(ImageButton)rootView.findViewById(R.id.ibBoroJuego);
cobajuego=(ImageButton)rootView.findViewById(R.id.ibCobaJuego);
indijuego=(ImageButton)rootView.findViewById(R.id.ibIndiJuego);
hidrojuego=(ImageButton)rootView.findViewById(R.id.ibHidroJuego);
ununjuego=(ImageButton)rootView.findViewById(R.id.ibUnunJuego);
plutojuego=(ImageButton)rootView.findViewById(R.id.ibPlutoJuego);
radijuego=(ImageButton)rootView.findViewById(R.id.ibRadiJuego);
promjuego=(ImageButton)rootView.findViewById(R.id.ibPromJuego);
sodijuego=(ImageButton)rootView.findViewById(R.id.ibSodiJuego);
zicrojuego=(ImageButton)rootView.findViewById(R.id.ibZicroJuego);
molijuego=(ImageButton)rootView.findViewById(R.id.ibMoliJuego);
// setOnClickListener para todoos
berijuego.setOnClickListener(this);
borojuego.setOnClickListener(this);
cobajuego.setOnClickListener(this);
indijuego.setOnClickListener(this);
hidrojuego.setOnClickListener(this);
ununjuego.setOnClickListener(this);
plutojuego.setOnClickListener(this);
radijuego.setOnClickListener(this);
promjuego.setOnClickListener(this);
sodijuego.setOnClickListener(this);
zicrojuego.setOnClickListener(this);
molijuego.setOnClickListener(this);
//Nivellactual 12 MAX o aun quedan errores
if ((nivellactual <= 12) || (errores > 0)) {
nivellactual = nivellactual + 1;
seguentelement();
}
return rootView;
}
And then it crashes here :
public void seguentelement() {
switch (nivellactual) {
case 1:
TextView tvPregunta = (TextView) getActivity().findViewById(R.id.tvPregunta);
String pregunta = ("Quin element és el Hidrògen?");
tvPregunta.setText(pregunta);
// int de elemento es la imagebutton
elementcorrecte = (R.id.ibHidroJuego);
break;
Hope you can find my error.
You should not call getActivity() because it returns the parent Activity and NOT the fragment where your TextField is added.
see http://developer.android.com/reference/android/app/Fragment.html#getActivity%28%29
Instead, you can create a global variable TextField and instantiate it in onCreateView() by calling findViewId() of the rootView.
NOTE: Your TextView is in layout joc_fragment right?
TextView tvPregunta;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.joc_fragment, container, false);
...
tvPregunta = (TextView) rootView.findViewById(R.id.tvPregunta); // instantiate here
berijuego=(ImageButton)rootView.findViewById(R.id.ibBeriJuego);
...
return rootView;
}
public void seguentelement() {
switch (nivellactual) {
case 1:
//
String pregunta = ("Quin element és el Hidrògen?");
tvPregunta.setText(pregunta);
// int de elemento es la imagebutton
elementcorrecte = (R.id.ibHidroJuego);
break;
}
...
}
on your seguentelement() method
TextView tvPregunta = (TextView) getActivity().findViewById(R.id.tvPregunta);
here id of tvPregunta not generated so you have to put it on your OnCreateView() like
TextView tvPregunta = (TextView) rootView.findViewById(R.id.tvPregunta);
Inside Fragment class you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
//or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
You should use ButterKnife to inject your views into your fragment, like so:
public class YourFragment extends Fragment {
#InjectView(R.id.btnSave)
public Button saveButton;
#OnClick(R.id.btnSave)
public void save(View view) {
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_fragment, container, false);
ButterKnife.inject(this, rootView);
...
}
}
Add the following dependency to use it to your build.gradle file:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.jakewharton:butterknife:6.0.0'