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.
Related
I have a MainActivity inside I create ViewPager withFragments. I am using savedInstanceState to store values to set TextView after orientation changed. I also want to change value e.g. using button in MainActivity. Button works properly, but if I change the orientation then Button cannot set TextView in Fragment because TextView is now null.
MyFragment
public class MyFragment extends Fragment {
private TextView textView;
private String info;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.item_weather, container, false);
textView = view.findViewById(R.id.text_view);
Bundle bundle = getArguments();
info = bundle.getString("info");
setInfo(info);
return view;
}
public void setInfo(String info) {
this.info = info;
textView.setText(info); //here is the error
}
}
In MainActivity.java in OnCreate
myFragment = new MyFragment();
viewPager = findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(10);
List<Fragment> fragments = new ArrayList<>();
fragments.add(myFragment);
pagerAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(pagerAdapter);
MyPagerAdapter looks like this:
public class MyPageAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
}
As I said everything works, but after orientation chage if I use Button I got an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Any ideas how to solve this?
edit:
full error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.app.myapp, PID: 15400
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.app.myapp.fragments.myFragment.setInfo(myFragment.java:53)
at com.example.app.myapp.MainActivity.onOptionsItemSelected(MainActivity.java:195)
at android.app.Activity.onMenuItemSelected(Activity.java:3543)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:407)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
at android.widget.AdapterView.performItemClick(AdapterView.java:318)
at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
at android.widget.AbsListView$3.run(AbsListView.java:4052)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
Into the fragment try to initialize the textView in the on the onViewCreated method:
#Override
public View onViewCreated(view: View, savedInstanceState: Bundle) {
// Your initialization code here
}
Solution:
Ok, EpicPandaForce thanks for hints.
To solve this i used in MainActivity
#Override
protected void onResume() {
super.onResume();
viewPager.setAdapter(pagerAdapter);
}
#Override
protected void onPause() {
super.onPause();
viewPager.setAdapter(null);
}
This question already has answers here:
findViewByID returns null
(33 answers)
Closed 3 years ago.
This is a basic activity swapping.
The app does not crash if i declare a local button inside the configureActivitySwap() method like this:
Button voiceBtn = (findViewById(R.id.goToVoice));
But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.
I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.
public class RecogActivity extends AppCompatActivity {
private Button voiceBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
voiceBtn = findViewById(R.id.goToVoice);
setContentView(R.layout.main_layout);
// some unrelated code
configureActivitySwap();
}
public void configureActivitySwap(){
// Button voiceBtn = (findViewById(R.id.goToVoice));
voiceBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
My runtime error logs:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tk.gandriks.gaaudiotransform, PID: 23125
java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
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)
You need to call the setContentView() before calling voiceBtn = findViewById(R.id.goToVoice); Since you don't specify the layout the findViewById method will not get the button instance
public class RecogActivity extends AppCompatActivity {
private Button voiceBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the layout first
setContentView(R.layout.YOUR_LAYOUT_XML_FILE_NAME)
voiceBtn = findViewById(R.id.goToVoice);
// some unrelated code
configureActivitySwap();
}
public void configureActivitySwap(){
// Button voiceBtn = (findViewById(R.id.goToVoice));
voiceBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
Try I guess) In your // some unrelated code is contains setContentView method?
public class RecogActivity extends AppCompatActivity {
private Button voiceBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
voiceBtn = findViewById(R.id.goToVoice);
setContentView(R.layout.some_layout)
// some unrelated code
configureActivitySwap();
}
public void configureActivitySwap(){
// Button voiceBtn = (findViewById(R.id.goToVoice));
voiceBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
You caught NPE because of findViewById is calling on inflated view. You are have been calling findViewById before setContentView in the first case and got the exception. And in the second case - in configureActivitySwap, that going after setContentView. Move setContentView after super.onCreate(savedInstanceState) and all will be working fine.
Are you setting layout before trying to find view with findViewById?
setContentView(R.layout.main_layout);
voiceBtn = (Button) findViewById(R.id.goToVoice);
replace the statement in your onCreate() method with the above. It should work.
and use
super.finish() instead of finish()
There is something I'm missing when I'm setting RecyclerView to my adapter. The App crashes when running it. Can anyone please help me with identifying the issue?
// My adapter
public class Adapter extends RecyclerView.Adapter<Adapter.myViewHolder> {
private Context mContext;
private List<item> mData;
public Adapter(Context mContext, List<item> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.card_item, parent, false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
holder.background_img.setImageResource(mData.get(position).getBackground());
holder.profilePhoto.setImageResource(mData.get(position).getProfilePhoto());
holder.tv_title.setText(mData.get(position).getProfileName());
holder.tv_nbFollowers.setText(mData.get(position).getNbFollower() + " Followers");
}
#Override
public int getItemCount() {
return mData.size();
}
public static class myViewHolder extends RecyclerView.ViewHolder {
ImageView profilePhoto, background_img;
TextView tv_title, tv_nbFollowers;
public myViewHolder(View itemView) {
super(itemView);
profilePhoto = itemView.findViewById(R.id.profile_img);
background_img = itemView.findViewById(R.id.card_background);
tv_title = itemView.findViewById(R.id.card_title);
tv_nbFollowers = itemView.findViewById(R.id.card_nb_follower);
}
}
}
And this is how I set the RecyclerView with the adapter
RecyclerView recList = findViewById(R.id.rv_list);
recList.setHasFixedSize(true);
List<item> mlist = new ArrayList<>();
mlist.add(new item(R.drawable.fish0, "Bass", R.drawable.profile0, 2500));
mlist.add(new item(R.drawable.fish1, "Mondo Bass", R.drawable.profile1, 3500));
mlist.add(new item(R.drawable.fish2, "Large Mouth Bass", R.drawable.profile2, 5500));
mlist.add(new item(R.drawable.fish3, "Bass", R.drawable.profile3, 10500));
Adapter adapter = new Adapter(this, mlist);
recList.setAdapter(adapter);
recList.setLayoutManager(new LinearLayoutManager(this));
Here is the Logcat error
2018-10-19 19:17:20.479 10635-10635/fishingfreaks.ffapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: fishingfreaks.ffapp, PID: 10635
java.lang.RuntimeException: Unable to start activity ComponentInfo{fishingfreaks.ffapp/fishingfreaks.ffapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at fishingfreaks.ffapp.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference at fishingfreaks.ffapp.MainActivity.onCreate(MainActivity.java:31) at
From the logs it is clear that you are setting recyclerView.setHasFixedSize() at a point where instance of your recylerview is null. See line 31 of your MainActivity.
You are getting a NullPointerException. So the layout item that you are referring to, is not found while you are trying to call the setHasFixedSize function on it.
This might happen for two reasons.
You might have referred to the wrong layout item id. Double check the id rv_list. Does it has the same spelling in your layout as well?
If the above condition is okay (i.e. your layout does have the rv_list as the id of your RecyclerView, then you might need to check if you have set the content view in your activity's onCreate function. Do you have the setContentView function call in your onCreate function? If not, then add the setContentView(R.layout.your_layout_with_recyclerview) as the first statement after the super call of your onCreate function.
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 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!