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.
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.
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));
}
I'm very new to android development as I just took a class of it only now, so I'm very confused with my current situation as I am writing the codes using the references I currently have at the moment.
I have also been trying to use references from other sources, though, sadly, I can't really comprehend how those really works.
My current assignment is that I have to make an application that serves as a catalog for movies and tv shows using fragments, and the following is the codes of one of the fragments:
public class MovieFragment extends Fragment {
View view;
private String[] titleMovie;
private String[] descMovie;
private TypedArray posterMovie;
private String[] genreMovie;
private String[] castMovie;
private String[] duration;
private String[] directorMovie;
private MovieAdapter adapter;
private ArrayList<Movie> movies;
private RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.mv_fragment,container,false);
recyclerView = view.findViewById(R.id.mv_list);
adapter = new MovieAdapter(getContext(), movies);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()) {});
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prepare();
addItem();
}
private void prepare() {
titleMovie = getResources().getStringArray(R.array.name_mv);
descMovie = getResources().getStringArray(R.array.desc_mv);
posterMovie = getResources().obtainTypedArray(R.array.poster_mv);
genreMovie = getResources().getStringArray(R.array.genre_mv);
castMovie = getResources().getStringArray(R.array.cast_mv);
directorMovie = getResources().getStringArray(R.array.director_mv);
duration = getResources().getStringArray(R.array.duration);
}
private void addItem() {
movies = new ArrayList<>();
for (int i = 0; i < titleMovie.length; i++){
Movie movie = new Movie();
movie.setTitleMovie(titleMovie[i]);
movie.setDescMovie(descMovie[i]);
movie.setPosterMovie(posterMovie.getResourceId(i,-1));
movie.setGenreMovie(genreMovie[i]);
movie.setDuration(duration[i]);
movie.setDirectorMovie(directorMovie[i]);
movie.setCastMovie(castMovie[i]);
movies.add(movie);
}
adapter.setMovie(movies);
}
}
And when I try to run the application from the emulator provided in Android Studio, I got the following error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wisnu_1605450.utsmobpro, PID: 18250
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.wisnu_1605450.utsmobpro.MovieAdapter.setMovie(java.util.ArrayList)' on a null object reference
at com.wisnu_1605450.utsmobpro.MovieFragment.addItem(MovieFragment.java:74)
at com.wisnu_1605450.utsmobpro.MovieFragment.onCreate(MovieFragment.java:47)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2586)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:838)
at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1197)
at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1080)
at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:119)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866)
Any explanation on why I screwed up is very much appreciated, will also give more of the codes if necessary for the context.
From the Fragment Life cycle documentation, onCreate event will be called before onCreateView event. That mean when you call adapter.setMovie(movies), the adapter is not created. It'll cause a NullPointerException.
You should call addItem in onViewCreated or onStart event.
OnCreate() method should be called before onCreateView() and after that onViewCreated() will be called.
Whereas in your code prepare(),addItem() methods are called in onCreate() so that instance not create for your MovieAdapter().please remove prepare(),addItem() methods in onCreate() and place it OnViewCreated()
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 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.