MainActivity RecyclerView and Room Database crash - Java [duplicate] - java

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

Related

Can't find proper context for .findNavController()

So, I'm working on an Android app etc. I have this Main2Activity with a bottomNavView that helps me switch between ProfileFragment and HomeFragment. The thing is I want to use another navView inside my ProfileFragment, I simulated some kind of TabView so I can see two different fragments inside my ProfileFragment.
So, this is my Main2Activity
public class Main2Activity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
BottomNavigationView navView = findViewById(R.id.nav_view);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_settings, R.id.navigation_new_post,
R.id.navigation_notifications, R.id.navigation_profile)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
}
public BottomNavigationView getBottomNavigationView(){
return findViewById(R.id.nav_view);
}
public Activity getActivity(){
return this;
}
}
This is my ProfileFragment, and here's where the problem is. I can't find the context to use in findNavController() and setupWithNavController():
public class ProfileFragment extends Fragment {
private ProfileViewModel notificationsViewModel;
private boolean isLoading = false;
public ProfileFragment() {
}
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
notificationsViewModel = ViewModelProviders.of(this).get(ProfileViewModel.class);
View root = inflater.inflate(R.layout.fragment_profile, container, false);
BottomNavigationView navView = root.findViewById(R.id.profile_nav_view);
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_my_posts, R.id.nav_applied_to)
.build();
NavController navController = Navigation.findNavController(getActivity(), R.id.profile_nav_host_fragment);
NavigationUI.setupActionBarWithNavController(new Main2Activity(), navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
return root;
}
}
The error I keep getting: java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
Anyone?
UPDATE: This is the stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.heirup, PID: 17523
java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
at android.app.Activity.requireViewById(Activity.java:2772)
at androidx.core.app.ActivityCompat.requireViewById(ActivityCompat.java:363)
at androidx.navigation.Navigation.findNavController(Navigation.java:58)
at com.example.heirup.ui.profile.ProfileFragment.onCreateView(ProfileFragment.java:38)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7081)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
I/Process: Sending signal. PID: 17523 SIG: 9
Use findNavController(View v) with parameter root.findViewById(#your nav_host id)

tablayout.newtab null pointer [duplicate]

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

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.

Edit String in XML file [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to create a user profile section in my app. In my Login Activity, I ask for the username from FirebaseAUTH.getCurrentUser().getDisplayName() and save it in a string.
In my xml file for the main activity, I put a textView with a string containing a placeholder.
I tried both in the Login and the Main Activity Java files to .setText .format etc, but the text simply doesnt change..
Any hints on how to solve this?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private HomeFragment hf;
private WebViewFragment wvf;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser().getDisplayName() != null) {
String name = firebaseAuth.getCurrentUser().getDisplayName();
final TextView profile = (TextView)findViewById(R.id.profile_section);
profile.setText("Test");
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vreeni.firebaseauthentiction, PID: 6060
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vreeni.firebaseauthentiction/com.example.vreeni.firebaseauthentication.MainActivity}: 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:2822)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2897)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1598)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6563)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
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.example.vreeni.firebaseauthentication.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
You can find a simple example right at the top of this resource.
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView helloTextView = (TextView) findViewById(R.id.text_view_id);
helloTextView.setText(R.string.user_greeting);
}
}
If you still have problems, please provide your code.

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