I found this question was marked as duplicate for one about how to prevent Null Pointer Exceptions. For clarification, the problem is that the library is throwing it. My variable isn't null. More specific help about the library is more helpful.
I am creating an app for playing music. I am trying to make use of the MediaController class to add controls to the song being played. However, when I run the .show() function, I get a Null Pointer Exception.
Here is the code for the MediaController:
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
MediaController timer = view.findViewById(R.id.song_progress);
timer.setMediaPlayer(new MediaController.MediaPlayerControl() {
#Override
public void start() {
MainActivity.playingSong.start();
}
#Override
public void pause() {
MainActivity.playingSong.pause();
}
#Override
public int getDuration() {
return MainActivity.playingSong.getDuration();
}
#Override
public int getCurrentPosition() {
return MainActivity.playingSong.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
MainActivity.playingSong.seekTo(pos);
}
#Override
public boolean isPlaying() {
return MainActivity.playingSong.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return MainActivity.playingSong.getAudioSessionId();
}
});
timer.setAnchorView(view);
timer.setEnabled(true);
timer.show();
}
Here is the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.luner.mobilemusic, PID: 2021
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.measure(int, int)' on a null object reference
at android.widget.MediaController.updateFloatingWindowLayout(MediaController.java:173)
at android.widget.MediaController.show(MediaController.java:363)
at android.widget.MediaController.show(MediaController.java:314)
at com.luner.mobilemusic.Playlist$Song$PlayFragment.onViewCreated(Playlist.java:271)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:892)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
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:7156)
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:975)
Why is this happening? Is there a good way to fix this, or should I use a different class completely? I would very much appreciate any code examples you might have.
Also, I found that removing the setAnchorView(view) prevented the error, but then caused no MediaController to appear.
Edit
After doing a more thorough search, I found two things:
The line numbers aren't accurate for some reason; the line for updateFloatingWindowLayout appeared inside a different method.
The culprit is the mDecor variable, which while running the setAnchorView method is set to the view variable. However, the view variable can't be null, as that would have caused an exception before getting to the show function. Thus, I still can't quite figure out the source of this ... the mDecor variable must somewhere be set to null, but only when I add a custom anchor view.
Edit 2
I have made lots of changes to the program at this point, so I am unable to test if a solution works. However, feel free to post an answer to help anyone else with the issue. I will accept any answer with a good amount of upvotes, as the upvotes signify that the solution worked. Thanks to everyone who tried to help!
Related
I am using BaseExpandableListAdapter and trying to do a dynamic list, where elements appears and disappears when you check or uncheck other elements. The group is an ArrayList of an object tha I made calle Mode, and children are a HashMap like that: HashMap> children.
The problem comes when I actualize the list to add children and they are added perfectly, but when I check other elements and the new children must disappear the program give me a NullPointerException in the method getChildrenCount(). I am actually using the notifyDataSetChanged() in both cases, when I am adding and when I am removing.
This is a piece of my code (the important part is that if I find another Mode object with the same parent ID in the DB I must to delete the old one):
cbMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isSelected = modeDao.rbIsAlreadySelected(currentChild);
if(!isSelected) {
//if checked uncheck all the children of the same parent AND delete the children
Mode oldMode = modeDao.isThereAnotherRB(currentChild.getIdFather());
if(oldMode != null){
uncheckTheOldCB(oldMode);
setFalseOnCb(oldMode);
modeDao.deleteMode(oldMode);
deleteModeChildren(oldMode);
}
//AND insert it on the DB
modeDao.setSelectedMode(currentChild);
currentChild.setChecked(true);
//if has children show them
if(currentChild.hasChildren() == 1){
setNewFatherMode(currentChild);
}
}else {
//if unchecked delete this from the DB
modeDao.deleteMode(currentChild);
deleteModeChildren(currentChild);
currentChild.setChecked(false);
}
notifyDataSetChanged();
}
});
It shows as how I delete the children:
private void deleteModeChildren(Mode oldMode){
for (Map.Entry<Mode, ArrayList<Mode>> entry : children.entrySet()) {
Mode currentMode = entry.getKey();
if(currentMode.getId() == oldMode.getId()) {
children.remove(entry.getKey());
break;
}
}
}
And this is how I overrided the getChild method:
#Override
public Object getChild(int groupPosition, int childPosition) {
return this.children.get(this.parents.get(groupPosition))
.get(childPosition);
}
This it the track of the exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at com.iurban.iurbanapp.Adapters.NewModesAdapter.getChildrenCount(NewModesAdapter.java:63)
at android.widget.ExpandableListConnector.refreshExpGroupMetadataList(ExpandableListConnector.java:563)
at android.widget.ExpandableListConnector.access$000(ExpandableListConnector.java:50)
at android.widget.ExpandableListConnector$MyDataSetObserver.onChanged(ExpandableListConnector.java:857)
at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
at android.widget.BaseExpandableListAdapter.notifyDataSetChanged(BaseExpandableListAdapter.java:56)
at com.iurban.iurbanapp.Adapters.NewModesAdapter$3.onClick(NewModesAdapter.java:223)
at android.view.View.performClick(View.java:4787)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:19873)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
And this is the getChildCount method:
#Override
public int getChildrenCount(int groupPosition) {
return children.get(parents.get(groupPosition)).size();
}
Ok, after a while I just to realise that I was deleting the children but not the corresponding parent of it. So, the getChildCount method gave me an error because the groupCount value were 4 when it must be 3.
Thank you all!
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
This tells you that the size() method is what threw the NPE, so there's a good chance that it is the list which is null.
Double check that it is indeed initialised.
In my application I want 2 fragments in a Activity. and for showing these 2 fragments I use ViewPager.
In Fragment two I have one method, and I want call this method from Fragment one!
My method in Fragment two :
public void getComments() {
JsonObject requestBean = new JsonObject();
requestBean.addProperty("entityType", 4);
requestBean.addProperty("reviewType", 5);
requestBean.addProperty("reviewUserType", 2);
requestBean.addProperty("entityID", serialID);
requestBean.addProperty("celebrityId", 0);
requestBean.addProperty("pageIndex", 1);
requestBean.addProperty("pageSize", 10);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<CommentResponse> call = api.getComments(token, requestBean);
call.enqueue(new Callback<CommentResponse>() {
#Override
public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
if (response.body().getData() != null) {
if (response.body().getData().size() > 0) {
reviewSerialFrag_NoComment.setText("");
} else {
reviewSerialFrag_NoComment.setText(context.getResources().getString(R.string.noReviews));
}
commentModel.clear();
commentModel.addAll(response.body().getData());
commentsListAdapter.notifyDataSetChanged();
reviewSerialFrag_newsCommentsRecyclerView.setAdapter(commentsListAdapter);
reviewSerialFrag_newsCommentsUserTypeText.setText(userTypeStr);
reviewSerialFrag_newsCommentsReviewTypeText.setText(reviewTypeStr);
reviewSerialFrag_Progress.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<CommentResponse> call, Throwable t) {
reviewSerialFrag_Progress.setVisibility(View.GONE);
}
});
}
And call this method with below codes from Fragment one :
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<SendCommentResponse> call = api.getSendComment(token, sendData);
showView(loadProgress);
goneView(sendBtn);
call.enqueue(new Callback<SendCommentResponse>() {
#Override
public void onResponse(Call<SendCommentResponse> call, Response<SendCommentResponse> response) {
if (response.body().getData()) {
Alerter.create(getActivity())
.setText(context.getResources().getString(R.string.successSendComment))
.setDuration(2000)
.setIcon(R.drawable.ic_tick_new)
.setBackgroundColorRes(R.color.colorPrimary)
.enableSwipeToDismiss()
.enableProgress(true)
.setOnShowListener(new OnShowAlertListener() {
#Override
public void onShow() {
watchlistDialog.dismiss();
goneView(loadProgress);
showView(sendBtn);
}
})
.setOnHideListener(new OnHideAlertListener() {
#Override
public void onHide() {
infoEpisodeFrag_addWatchList.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_eye_white));
infoEpisodeFrag_addWatchList.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#1da8b9")));
getData();
new EpisodeDetail_ReviewFrag().getComments();
}
})
.setProgressColorRes(R.color.whiteMe)
.show();
}
}
#Override
public void onFailure(Call<SendCommentResponse> call, Throwable t) {
}
});
But show me this error in LogCat :
FATAL EXCEPTION: main
Process: com.example.app, PID: 11978
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.support.v4.app.FragmentActivity.getResources()' on a null object reference
at com.example.app.Fragments.EpisodeDetailFrags.EpisodeDetail_ReviewFrag$6.onResponse(EpisodeDetail_ReviewFrag.java:305)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Show me error for this line in Fragment two :
reviewSerialFrag_NoComment.setText(context.getResources().getString(R.string.noReviews));
How can I fix it? Please help me
It is really a bad idea to use Fragments like regular classes. Even when you want to pass simple data around you'd use and instance or use the bundle.
If your method does not rely on the fragment itself, create a separate utility class that both fragments share. Just pass it a context so it can resolve some of the variables in it.
Separate the UI manipulation in a separate class within your fragments. Create a listener to this utility class and change the visual state in your fragment.
No need to call getResources() method. Just getString(R.string.noReviews) works.
Get the instance of fragment
ExampleFrag frag=(ExampleFrag)getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment2);
Then call any method
frag.myMethod();
I'm loading a picture from a url into a bitmap. This code below worked on previous classes that extended Fragment. This time, I'm just copying the code and trying to use it in a class that extends AppCompatActivity. The only difference is how I'm getting context.
public void loadBitmap(String url) {
if (loadtarget == null) loadtarget = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
handleLoadedBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
mContext = MyActivity.this;
Picasso.with(mContext).load(url).into(loadtarget); //giving me null
}
In the original code, where I used it in a Fragment, I had it as
Picasso.with(getActivity()).load(url).into(loadtarget);
So now, since this class extends AppCompatActivity, I thought I could use "this" or MyActivity.this but that didn't work. I've tried initializing a Context variable "mContext" in onCreate and right before I load the image into the bitmap (like above) but neither worked. I've tried this.getApplicationContext() and I've also tried to pass mContext as a parameter in the loadBitmap() method but that didn't work either.
My URL string is correct. I'm just not sure how to tackle this problem after trying, what seems like, everything.
Last piece of information, the exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:112)
at com.salty.seas.Driver.MyActivity.loadBitmap(MyActivity.java:144)
at com.salty.seas.Driver.MyActivity$1.onKeyEntered(MyActivity.java:61)
at com.firebase.geofire.GeoQuery$2.run(GeoQuery.java:126)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
In the comments to the question you said that the activity, the loadBitmap() belongs to, you actually instantiate yourself (in some other fragment) and use it as an utility class.
You should never create activites manually as they are managed by android and they have a lifecycle android maintains.
In your case the activity is not in a correct state (one of its internal fields is null), that's why you get NPE.
For utility methods create utility classes and call those from wherever you want.
I have a simple Android Fragment CreateAccountBookingFragment which inherits from CreateAccountFragment, that has the following method :
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
passwordTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
|| (actionId == EditorInfo.IME_ACTION_DONE)) {
onSignUpClick();
}
return false;
}
});
}
method onSignUpClick() is overridden in CreateAccountBookingFragment.
Recently there was a bug caught :
java.lang.NullPointerException
at com.myapp.ui.auth.CreateAccountBookingFragment.onSignUpClick(CreateAccountBookingFragment.java:82)
at com.myapp.ui.auth.CreateAccountFragment$1.onEditorAction(CreateAccountFragment.java:83)
at android.widget.TextView.onEditorAction(TextView.java:4594)
at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:138)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:297)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:175)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(NativeStart.java)
I quite don't understand how it could throw NullPointer. It means that inner class is still alive and outer is not ? I though it's impossible. Can anyone help me understand what's going on here ? And what will be the solution to this. Any help appreciated. Thanks.
Device the bug occurred : Samsung GT P3113
Update :
method onSingUpClick() is here :
#SuppressWarnings("unused")
#OnClick(R.id.frag_auth_sign_up_btn) // line 82, this is ButterKnife annotation
protected void onSignUpClick() {
String email = emailText.getText().toString().trim();
String password = passwordText.getText().toString().trim();
int errorMsg = 0;
if (TextUtils.isEmpty(email)) {
errorMsg = R.string.enter_email;
} else if (!Utils.isValidEmail(email)) {
errorMsg = R.string.invaild_email;
} else if (TextUtils.isEmpty(password)) {
errorMsg = R.string.enter_password;
} else if (!Utils.isValidPassword(password)) {
errorMsg = R.string.invaild_password;
} else if (!NetworkUtils.isNetworkConnected(getActivity())) {
errorMsg = R.string.network_not_connected;
}
if (errorMsg > 0) {
ViewUtils.getInfoDialog(getActivity(), errorMsg).show();
} else {
showLoadingDialog();
signUp(email, password);
}
ViewUtils.hideKeyboard(getActivity());
}
Can you post the code of your signUp() function from the CreateAccountBookingFragment class? Are you in some way using getActivity() in that method?
There is chance that sometimes getActivity() returns null. It is most probably that error. So in this case, add a null check on getActivity(),
that is:
if (getActivity()!=null){
// only then do your singIn() method stuff
}
I have a similar problem. I'm curious if my 'solution' will work for you as well. This problem is also occurring on a Samsung GT P3113 for me.
I moved the anonymous listener to the class itself eliminate the inner classs accessor. for you that would mean adding TextView.OnEditorActionListener to the 'implements' part of your Fragment class definition and then implementing the onEditorAction() method in the fragment class. That way the lifetime of the listener object is always the same as that of the fragment. I know, it shouldn't be a problem, but since the NPE is occurring when it tries to invoke the method using the accessor object.. it seems to be working for me.
Maybe something you are using in CreateAccountBookingFragment class, any variable used from outside the anonymous inner class has to be final or it will have an issue due to cloistering.
When I attempt to call the method loadUserList() from another class, I get the following error:
Attempt to invoke virtual method android.content.res.Resources
android.content.Context.getResources() on a null object reference
This is my loadUserList method
public void loadUserList()
{
final ProgressDialog dia = ProgressDialog.show(this, null, getString(R.string.alert_loading));
ParseQuery<ParseObject> query = ParseQuery.getQuery("Chat_User");
query.whereEqualTo("receiver", ParseUser.getCurrentUser());
query.include("sender");
query.findInBackground(new FindCallback<ParseObject>()
{
#Override
public void done(List<ParseObject> li, ParseException e)
{
dia.dismiss();
if (li != null)
{
if (li.size() == 0)
Toast.makeText(com.yarnyard.UserList.this, R.string.msg_no_user_found,
Toast.LENGTH_SHORT).show();
uList = new ArrayList<ParseObject>(li);
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new UserAdapter());
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3)
{
loadUserList();
/*startActivity(new Intent(com.yarnyard.UserList.this, Chat.class)
.putExtra(Const.EXTRA_DATA, uList.get(pos).getUsername()));*/
}
});
}
else
{
Utils.showDialog(
com.yarnyard.UserList.this,
getString(R.string.err_users) + " "
+ e.getMessage());
e.printStackTrace();
}
}
});
}
This is how I am calling it
public void done(ParseException e)
{
UserList UserList = new UserList();
UserList.loadUserList();
}
My error log
07-30 14:14:56.219 13383-13383/com.anonimv2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.anonimv2, PID: 13383
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:85)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at android.content.Context.getString(Context.java:376)
at com.yarnyard.UserList.loadUserList(UserList.java:96)
at com.yarnyard.custom.CustomActivity.onOptionsItemSelected(CustomActivity.java:116)
at android.app.Activity.onMenuItemSelected(Activity.java:2882)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1131)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at android.widget.ActionMenuView.invokeItem(ActionMenuView.java:587)
at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:141)
at android.view.View.performClick(View.java:4832)
at android.view.View$PerformClick.run(View.java:19839)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5321)
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:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
Any advice would be much appreciated.
Normal, non-static methods are called on objects, not on classes. This is a fine point that you really need to learn before using object oriented languages. Only then you will see, in practice, how you can connect objects by passing references.
The UserList objects that you construct in the done method is not the one you want to call, it's just an empty, uninitialized shell.
As I understand, you extend UserList from Context, right?
Then keep in mind that in Android never initial a Context object by yourself, it's framework's job..
In your case, because you create a context instance without attach to any baseContext, so when access to common resource, you got a NPE.
I guess that you are trying to move to a new Fragment or Actvity? Then read these link start activity switch fragment