When I run the app and go to the user's activity the app crashes showing me that the mUsersList.setHasFixedSize(true); is making the app crash.
this is the message "Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference"
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users_single_layout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersList = findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
}
The stacktrace tells you everything you need. mUsersList is null, so you can't call any methods on it. You should make sure your layout file R.layout.users_single_layout has a RecyclerView with id of "#+id/users_list" defined in it. Also, you should do a null pointer check:
mUsersList = findViewById(R.id.users_list);
if (mUsersList != null) {
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
}
Related
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.
I'm trying to make my app handle device rotation but it always crashes when I add the below code on the onCreate method from the mainActivity. Here is the error that I am getting. how to I fix this? :
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ArrayAdapter.clear()' on a null object reference
2019-09-25 06:58:16.743 10444-10444/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 10444
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.clear()' on a null object reference
at com.example.myapplication.MainActivity$1.onChanged(MainActivity.java:48)
at com.example.myapplication.MainActivity$1.onChanged(MainActivity.java:44)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:131)
at androidx.lifecycle.LiveData.setValue(LiveData.java:289)
at androidx.lifecycle.LiveData$1.run(LiveData.java:91)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contactListView = (ListView) findViewById(R.id.contactsListView);
adapter = new ArrayAdapter<Contact>(this,android.R.layout.simple_list_item_1, contacts);
contactListView.setAdapter(adapter);
contactListView.setOnItemClickListener(this);
setContentView(R.layout.activity_main);
}
You should better place your LiveData in a ViewModel and observe it in the activity, probably in the onCreate() method. Let me show you how can you properly use LiveData in a ViewModel,
YourViewModel
public class YourViewModel extends ViewModel {
// Create a LiveData with a List of Contact
private MutableLiveData<List<Contact>> contactList = new MutableLiveData<>();
// encapsulated with immutable live data
public LiveData<List<Contact>> getContactList() {
return contactList;
}
// call this method with a list of new contacts whenever you need to refresh your list
public void updateContactList(List<Contact> list) {
contactList.setValue(list);
}
// Rest of the ViewModel...
}
YourActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactListView = (ListView) findViewById(R.id.contactsListView);
yourViewModel = ViewModelProviders.of(this).get(YourViewModel.class);
if(contacts==null) contacts = new ArrayList<>();
adapter = new ArrayAdapter<Contact>(this,android.R.layout.simple_list_item_1, contacts);
contactListView.setAdapter(adapter);
contactListView.setOnItemClickListener(this);
yourViewModel.getContactList().observe(this, contactObserver);
}
Observer<List<Contact>> contactObserver = new Observer<List<Contact>>() {
#Override
public void onChanged(#Nullable List<Contact> newContacts) {
if(adapter != null && newContacts != null) {
adapter.clear();
adapter.addAll(newContacts);
}
}
};
Above way you are ensuring the liveData is tied with the activity lifecycle and it gets a non null adapter in the onChanged() method. I hope my answer will help you solve your issue.
when the device is rotated android tears down the activity and recreates it. So the entire life cycle is called.
so save everything in onSavedInstanceState then extract data in onRetainInstanceState
for more details read here :https://developer.android.com/guide/topics/resources/runtime-changes
Also here I believe here the issue is setContentView(R.layout.activity_main) is called after contactListView = (ListView) findViewById(R.id.contactsListView)
try this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactListView = (ListView) findViewById(R.id.contactsListView);
adapter = new ArrayAdapter<Contact>(this,android.R.layout.simple_list_item_1, contacts);
contactListView.setAdapter(adapter);
contactListView.setOnItemClickListener(this);
}
It should work
Handling lifecycle changes is a pain in the butt. I strongly recommend you to take a look at architecture component ViewModel. It will handle orientation changes and other lifecycle changes like a charm. Add together with DataBinding and you have a much more robust application that will handle lifecycle changes automatically for you.
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 am trying to implement RecyclerView in one of my custom alert dialogue. Its crashing with error called
Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
on this line
hsv_font_bartextview.setLayoutManager(layoutManager);
My function code of custom dialogue is like below
private void showGotoPageDialog() {
final Dialog mDialog = new Dialog(SettingsActivity.this);
mDialog.setContentView(R.layout.font_dialogue);
mDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayoutManager layoutManager
= new LinearLayoutManager(SettingsActivity.this, LinearLayoutManager.HORIZONTAL, false);
hsv_font_bartextview=(RecyclerView)findViewById(R.id.hsv_font_bartextview);
hsv_font_bartextview.setLayoutManager(layoutManager);
TextAdapterTextview textAdaptertextview = new TextAdapterTextview(SettingsActivity.this, Globle.getFontArray());
hsv_font_bartextview.setAdapter(textAdaptertextview);
textAdaptertextview.setOnClickLIstner(new OnTClickLIstner() {
#Override
public void onClick(View v, String image, int position) {
Toast.makeText(SettingsActivity.this,image,Toast.LENGTH_SHORT).show();
}
});
mDialog.show();
TextView dismiss = (TextView) mDialog.findViewById(R.id.dialog_dismiss);
dismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDialog.dismiss();
}
});
}
Let me know if someone can help me for solve my issue. Thanks
hsv_font_bartextview=(RecyclerView)findViewById(R.id.hsv_font_bartextview);
findViewById() returns null, because your activity does not have a widget with that ID. Your dialog might, but the dialog is not the activity. Call findViewById() on the dialog if that is where the hsv_font_bartextview is.
I am new to Android developement and had recently started on a project to get WiFi SSID, BSSID and MAC address. However, the app crashed unexpectedly immediately after opening it.
The error log in Android Studio says that:
FATAL EXCEPTION: main
Process: com.example.android.wifi, PID: 3875
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.wifi/com.example.android.wifi}: 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:2993)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3248)
at ...
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:2277)
at
com.example.android.wifi.MainActivity.<init>(MainActivity.java:16)
at ...
My java file can be found at http://www.yikjin.ga/MainActivity.java
There were no syntax errors recorded by Android Studio.
Thanks in advance!
From your error is seems you are trying to get the View inside the constructor of your class or you are calling findViewById() outside.
com.example.android.wifi.MainActivity.<init>(MainActivity.java:16)
Move those code to onCreate() method after calling setContentView()
Update:
Change
TextView viewWifiSSID = (TextView) findViewById(R.id.network);
TextView viewWifiBSSID = (TextView) findViewById(R.id.bssid);
TextView viewWifiMAC = (TextView) findViewById(R.id.mac);
to
TextView viewWifiSSID;
TextView viewWifiBSSID;
TextView viewWifiMAC;
and add the following to onCreate() after setContentView()
viewWifiSSID = (TextView) findViewById(R.id.network);
viewWifiBSSID = (TextView) findViewById(R.id.bssid);
viewWifiMAC = (TextView) findViewById(R.id.mac);
you are referring object before activity is created ... onCreate() is called when your activity is created so refer object inside onCreate()...
TextView viewWifiSSID, viewWifiBSSID, viewWifiMAC;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewWifiSSID = (TextView) findViewById(R.id.network);
viewWifiBSSID = (TextView) findViewById(R.id.bssid);
viewWifiMAC = (TextView) findViewById(R.id.mac);
getWifi();
}