tablayout.newtab null pointer [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
hey I am trying to use tabs on android but i am getting error when setting the tablayout
Here is my code
TabLayout tabLayout = findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("Fruits"));
tabLayout.addTab(tabLayout.newTab().setText("Vegetables"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = findViewById(R.id.pager);
final FruitsAdapter adapter = new FruitsAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
this is the error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mohad.grocery/com.mohad.grocery.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.design.widget.TabLayout$Tab android.support.design.widget.TabLayout.newTab()' 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 'android.support.design.widget.TabLayout$Tab android.support.design.widget.TabLayout.newTab()' on a null object reference
at com.mohad.grocery.Main2Activity.onCreate(Main2Activity.java:30)
I couldn't find anyone who has the same problem as me so I asked his question
The problem is on newtab but I dont know why
Thank you for help

When you do TabLayout tabLayout = findViewById(R.id.tablayout);, tabLayout is null. The problem is probably because you referencing a wrong TabLayout id in your layout file (.xml).
Please validate that both id's are the same (case sensitive).

I think you are missing a call to setupWithViewPager() after initializing the viewPager.
Can you try?
final FruitsAdapter adapter = new FruitsAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);

Related

MainActivity RecyclerView and Room Database crash - Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
Could someone offer some help please, I have tried using some solutions on Stackoverflow and searching for similar topics but nothing works.
I have a project that uses a bottomnavbar to cycle through fragments. The main activity which is using a fragment has a recycler view running in it. Implemented Room database for a simple note taking function to display with RecyclerView
App crashes after splash screen when launching MainActivity
MainActivity.java
public class MainActivity extends AppCompatActivity {
private NoteViewModel noteViewModel;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_logbook, R.id.navigation_settings, R.id.navigation_aircraft, R.id.navigation_pilots, R.id.navigation_totals)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupWithNavController(binding.navView, navController);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
NoteAdapter adapter = new NoteAdapter();
recyclerView.setAdapter(adapter);
noteViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication())
.create(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
//update RecyclerView
adapter.setNotes(notes);
}
});
}
}
Logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.company.swiftlogbook/com.company.swiftlogbook.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at com.company.swiftlogbook.MainActivity.onCreate(MainActivity.java:50)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Many Thanks for any advice or help with this.
This is because in your activity_main.xml view there is no widget with the id recyclerView.
Please check the ids in your view or use a type-safe mode of databinding by calling the widget from the binding variable instead of findViewById
It could be like this RecyclerView recyclerView = binding.recyclerView instead of RecyclerView recyclerView = findViewById(...)

Context Null Pointer when starting intent [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Hi i am new to android studio and I am trying to start a new activity - however, I am having endless issues with getting Context - I have tried a few different methods posted on stack overflow but It just keeps throwing a null pointer please help. See onCreate method and exception below.
AddRoutine.class is just a blank activity
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.mContext = this.getApplicationContext();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Add Routine
FloatingActionButton fab = findViewById(R.id.addRoutine);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddRoutine.class));
}
});
generateRoutineListing(getAppContext());
//if returnListing.length > 0
// recyclerView.addItems
//else
// Show Jumbotron/Message board explaining that no routines have been created
}
Exception
E/AndroidRuntime: FATAL EXCEPTION: main
Process: za.co.freelanceweb.routines, PID: 14648
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:130)
at android.content.Intent.<init>(Intent.java:5780)
at za.co.freelanceweb.routines.MainActivity$1.onClick(MainActivity.java:38)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24774)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6518)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Thanks so Much
Instead of:
MainActivity.mContext = this.getApplicationContext();
Use:
Context mcontext = MainActivity.this; //Also, set mcontext as a global variable.
Also,
Instead of:
generateRoutineListing(getAppContext());
Use:
generateRoutineListing(mcontext);
The problem is probably in this line:
MainActivity.mContext = this.getApplicationContext();
Activity extends Context so you can always use this to refer to the activity's context.
I am not sure what you are trying to do with that but you should not be using the application's context on one activity. The application context lives through out the entire lifetime of the application.
If you want want to start a new activity do this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, AddRoutineActivity.class);
startActivity(intent);
}
And then register AddRoutineActivity in your AndroidManifest.xml file like so:
<activity android:name=".AddRoutineActivity" />
If you are new to android you may want to check out Kotlin.

App crashes when attempting to swap activities [duplicate]

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()

RecyclerView Adapter Android Studio

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.

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.

Categories