App crashes when attempting to swap activities [duplicate] - java

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

Related

Android app crashes when activity is initialised from fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am currently trying to create a calendar app in android studio. The app contains a calendar with different "Views" e.g. monthly view, weekly view, and daily view.
The app uses fragments as pages and each view is an activity.
This is the code for the fragment and buttons to initialise each view
public class CalendarFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
Button btn1 = (Button) v.findViewById(R.id.openCalendar);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(),CalendarActivity.class);
startActivity(intent);
}
});
Button btn2 = (Button) v.findViewById(R.id.openWeek);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), WeekViewActivity.class);
startActivity(intent);
}
});
return v;
}
The first button which displays the monthly view of the calendar called "CalendarActivity" in code works fine but when the second button is clicked which displays the weekly view of the calendar, causes the app to crash and gives the following error in the logcat
2022-05-13 14:44:59.642 15183-15183/com.example.finalyearproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalyearproject, PID: 15183
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finalyearproject/com.example.finalyearproject.WeekViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3685)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
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:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at com.example.finalyearproject.CalendarUtils.monthYearFromDate(CalendarUtils.java:16)
at com.example.finalyearproject.WeekViewActivity.setWeekView(WeekViewActivity.java:40)
at com.example.finalyearproject.WeekViewActivity.onCreate(WeekViewActivity.java:29)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Activity.performCreate(Activity.java:8034)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1341)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
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:2252) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7842) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
I am not sure what the problem is as I have been following a tutorial and the other features work. I have also included the code for each activity below.
Monthly View
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setMonthView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void nextMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusMonths(1);
setMonthView();
}
public void previousMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusMonths(1);
setMonthView();
}
Weekly View
public class WeekViewActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_view);
initWidgets();
setWeekView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setWeekView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> days = daysInWeekArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(days, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void previousWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusWeeks(1);
setWeekView();
}
public void nextWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusWeeks(1);
setWeekView();
}
Any suggestions would be greatly appreciated.
My suggestions:
Firstly you didn't initialized CalendarUtils.selectedDate
Cover code with breakpoints for. debugging or with Log.d() messages to find, which variable is null

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.

invoke virtual method on null object reference (setDisplayHomeAsUpEnabled)

I want my update_activity to display a back arrow button but this code gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at this line:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
What do you suggest?
public class UpdateActivity extends AppCompatActivity {
TextView textView;
AppBarLayout appbar;
private static Socket s;
private static PrintWriter pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button button = findViewById(R.id.UpdateButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
connect();
}
});
}
when I substitute that command with
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
it returns me this other error (which I think is the same):
Unable to start activity
ComponentInfo{io.anycopy.googleplusdemo/io.anycopy.googleplusdemo.UpdateActivity}: java.lang.NullPointerException
Most likely you are using NoActionBar themes, in which case getSupportActionBar () return null and you must either change the theme or use getActionBar ()

To Do app crash

I'm trying to make a To Do app in android studio. But as soon as I click on add-button (+ in top right corner) the app crashes. I am very new to java and android studio but I think the problem may lay in "saveListInfo()" but I can't figure out how to fix it...
Code from EditedActivity.java:
public class EditedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edited);
String name;
name = getIntent().getStringExtra("theName");
EditText editList = (EditText) findViewById(R.id.editText);
editList.setText(name);
}
private void saveListInfo() {
EditText editList = (EditText) findViewById(R.id.editText);
String name = editList.getText().toString();
Bundle listBundle = new Bundle();
listBundle.putString("name", name);
Intent finalIntent = new Intent(this, MainActivity.class);
finalIntent.putExtras(listBundle);
setResult(RESULT_OK, finalIntent);
}
Button addBtn = (Button) findViewById(R.id.add_btn);
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
}
Code from MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
saveTodoInfo();
}
return true;
}
private void saveTodoInfo(){
TextView nameView = (TextView) findViewById(R.id.action_add_task);
String name = nameView.getText().toString();
Intent myIntent = new Intent(this, EditedActivity.class);
myIntent.putExtra("theName", name);
startActivityForResult(myIntent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0){
if(resultCode == RESULT_OK){
Bundle ListBundle = data.getExtras();
String name = ListBundle.getString("theName");
updateToDo(name);
}
}
}
private void updateToDo(String name){
TextView nameView = (TextView) findViewById(R.id.action_add_task);
nameView.setText(name);
}
}
This is the error I get when clicking the add-button:
02-12 16:07:40.553 1410-1410/com.carpe_diem.anitas_todolist
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.carpe_diem.anitas_todolist, PID: 1410
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.carpe_diem.anitas_todolist/com.carpe_diem.anitas_todolist.EditedActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.Window.findViewById(int)' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.View android.view.Window.findViewById(int)' on a
null object reference
at android.app.Activity.findViewById(Activity.java:2090)
at
com.carpe_diem.anitas_todolist.EditedActivity.(EditedActivity.java:40)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
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)
By the logs, we can see that you crash is happening in following line:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at
android.app.Activity.findViewById(Activity.java:2090) at
com.carpe_diem.anitas_todolist.EditedActivity.(EditedActivity.java:40)
...
After checking your code, I can find in line 40 (EditedActivity.java:40) that following code is outside of any method or function.
Button addBtn = (Button) findViewById(R.id.add_btn);
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
So, you have to move the lines above to onCreate() method.
EditedActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edited);
String name;
name = getIntent().getStringExtra("theName");
EditText editList = (EditText) findViewById(R.id.editText);
editList.setText(name);
Button addBtn = (Button) findViewById(R.id.add_btn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
Root Cause
If you leave the line below outside of any method, it will run during object instantiation.
Button addBtn = (Button) findViewById(R.id.add_btn);
However, during object creation, the view was not created yet. So, findViewById wont find anything and will return null. Thus, that CRASH (or Force Close) will happen.
Solution
So, make sure to add findViewById() inside a method which is called after the view was already created (otherwise, it will never find the view).
As you can see, I suggested to add at onCreate() method after setContentView(R.layout.activity_edited) (which is responsible to add the objects to VIEW).
After that line, findViewById() will be able to find the views (if you add them in the layout, of course).
Remove the brackets around this code
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
Should look like this
Button addBtn = (Button) findViewById(R.id.add_btn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
If you want to know why the crash happened, you can read more about What is an initialization block?

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