Nullpointer on getIntent().getExtras(); - android

code in RegisterActivity1:
Bundle extras = new Bundle();
...
case R.id.continue_button:
extras.putString("email",eMail_eingabe.getText().toString().trim());
extras.putString("pw1", passwort_1_eingabe.getText().toString().trim());
extras.putString("pw2", passwort_2_eingabe.getText().toString().trim());
i.putExtras(extras);
this.startActivity(i);
break;
code in RegisterActivity2:
Bundle extras = getIntent().getExtras(); //Nullpointer oocurs here
semail = extras.getString("email");
spw1 = extras.getString("pw1");
spw2 = extras.getString("pw2");
I'm trying to pass email and password from activity 1 to activity 2, but nothing I have tried so far seems to be working. I always get a Nullpointer Exception here:
Bundle extras = getIntent().getExtras();
Any tips on how to fix this?
Here is the full method from Activity1, in case it has something to do with the override method...
#Override
public void onClick(View view) {
String email = eMail_eingabe.getText().toString().trim();
String password = passwort_1_eingabe.getText().toString().trim();
if (eMail_eingabe.getText().toString().isEmpty()) {
//eMail_eingabe.setError("Bitte email eingeben");
eMail_eingabe.setText("Bitte email eingeben");
eMail_eingabe.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
eMail_eingabe.setError("Bitte eine gültige E-Mail eingeben");
eMail_eingabe.requestFocus();
return;
}
if (password.length() < 6) {
passwort_1_eingabe.setError("Bitte mindestens 6 Zeichen eingeben");
passwort_1_eingabe.requestFocus();
return;
} else if (passwort_1_eingabe.getText().toString().isEmpty()) {
passwort_1_eingabe.setError("Bitte passwort eingeben");
passwort_1_eingabe.requestFocus();
return;
} else if (passwort_2_eingabe.getText().toString().isEmpty()) {
passwort_2_eingabe.setError("Bitte passwort eingeben");
passwort_2_eingabe.requestFocus();
return;
}
if (!passwort_1_eingabe.getText().toString().equalsIgnoreCase(passwort_2_eingabe.getText().toString())) {
passwort_2_eingabe.setError("Passwort stimmt nicht überein");
passwort_2_eingabe.requestFocus();
return;
}
switch (view.getId()) {
case R.id.continue_button:
extras.putString("email", eMail_eingabe.getText().toString().trim());
extras.putString("pw1", passwort_1_eingabe.getText().toString().trim());
extras.putString("pw2", passwort_2_eingabe.getText().toString().trim());
i.putExtras(extras);
this.startActivity(i);
break;
}
}
Exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hoimi, PID: 7812
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hoimi/com.example.hoimi.student.Register2_Student_Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.example.hoimi.student.Register2_Student_Activity.<init>(Register2_Student_Activity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3340)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199) 
at android.os.Handler.dispatchMessage(Handler.java:112) 
at android.os.Looper.loop(Looper.java:216) 
at android.app.ActivityThread.main(ActivityThread.java:7625) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987) 

Bundle extras = getIntent().getExtras();
had to be called in the onCreate method, I called it before so it didn't work.
Someone gave the right answer, but deleted his post later (because he got 2 downvotes??)
Anyways, thanks alot.

Problem is not because of getExtras() its because of getIntent(). Check your getIntent() with null and use further.
Your code should be something like
if(getIntent() != null) {
Bundle extras = getIntent().getExtras(); //Nullpointer oocurs here
semail = extras.getString("email");
spw1 = extras.getString("pw1");
spw2 = extras.getString("pw2");
}
Good luck.

when you call getIntent(), it returns the intent that you created in previous Activity.
public Intent getIntent ()
Return the intent that started this activity.
Activity documentation
so in second activity, your intent is null
in onCreate initiate your intent

Related

Blank Screen showing up after Image Selected from Gallery

I am trying to get an image into the ImageView but whenever I click a picture on the Gallery the app shows a blank screen and closes down.
This ImageView is in a fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_auction_add, container, false);
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
dateTimeAction(v);
return v;
}
private void imageSelectAction(View v) {
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_image = v.findViewById(R.id.auction_add_imageView);
choosePicture();
}
private void choosePicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
if (data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
auction_add_image.setImageURI(selectedImageUri);
}
}
}
}
The Inital Declaration
public class auction_add extends Fragment {
private static final int SELECT_PICTURE = 10;
private static final int PERMISSION_CODE = 11;
ImageButton auction_add_imageViewButton;
//References to all Auction Add Page EditText
EditText auction_add_itemNameTxt;
EditText auction_add_descriptionTxt;
EditText auction_add_initialPriceTxt;
EditText auction_add_startTimeTxt;
EditText auction_add_endTimeTxt;
//Reference to ImageView
private ImageView auction_add_image;
final Calendar myCalendar = Calendar.getInstance();
Would Appreciate the help thanks!
Edit:
Followed is the error on the Run tab of Android Studio
W/System: A resource failed to call close.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.projectcrest, PID: 5618
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=242868079, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:31 flg=0x1 }} to activity {com.example.projectcrest/com.example.projectcrest.pages.LandingPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at com.example.projectcrest.fragments.auction_add.onActivityResult(auction_add.java:155)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2905)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2885)
at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:377)
at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:336)
at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:624)
at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
at android.app.Activity.dispatchActivityResult(Activity.java:8310)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 5618 SIG: 9
By looking into the exception it seems that the App is crashing in #onActivityResult function at line auction_add_image.setImageURI(selectedImageUri); due to NPE (Null Pointer Exception). This expection/crash is caused since the auction_add_image object has null value instead of an ImageView.
After taking an close look into your code, I think the issue has occured due to following code:
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
Note that in #onClick function you are passing view v on which you are going to perform the #findViewById operation. Here the passed view v refers to the auction_add_imageViewButton instead of the v you have captured above.
I would suggest to modify the code as below (just rename the v variable in #onClick function):
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View buttonView) {
imageSelectAction(v);
}
});
This way the variable name collision could be avoided and the error would be resolved.
Also, in case this does not solve your problem, then please check whether the #findViewById is returning an ImageView instead of null. In case the Id provided to #findViewById is not present on the screen or in the child views of view (on which the #findViewById) is being performed then the #findViewById will return null value.
Also, check whether you have assigned null value to auction_add_image in anywhere your code.

getContext() is NULL for a certain fragment flow

2 Fragments & 1 Activity are involved. Here is the flow wherein I am able to reproduce the issue, along with relevant code snippets.
#1. From Frag1, open Frag2
Frag2 fragment = Frag2.newInstance(pos);
BaseFragment.addToBackStack(getContext(), fragment);
Here is BaseFragment.addToBackStack()
BaseFragment
public static void addToBackStack(Context context, BaseFragment fragment) {
FragmentManager fragmentManager = ((BaseActivity) context).getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(BaseActivity.getContainerIdForCurrentActivity(context), fragment);
transaction.addToBackStack(null).commit();
}
#2. Press Back to open Frag1 again.
#3. Open Activity A1 with startActivityForResult() from an Adapter in Frag1.
Intent intent = new Intent(context, Act1.class);
intent.putExtra(..);
intent.putExtra(..);
((BaseActivity) context).startActivityForResult(intent, Frag1.REQ_CODE_ISSUE_DONE);
#4. Go back to Frag1, either by pressing Back or finishing A1 with
setResult()
#5. onActivityResult() of Frag1 is called. But inside it, both getContext() and getActivity() are NULL.
Frag1
if (resultCode == Ac1.RESULT_CODE_OPEN_LANDING_SCREEN) {
if (getActivity() instanceof MainActivity) {
BaseFragment.replaceStack(getContext(), landingFrag.newInstance());
} else {
Intent intent1 = new Intent(getContext(), MainActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
}
If A1 is opened directly from Frag1, then getContext() is NOT null inside startActivityForResult() and works perfectly.
Logcat:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=792, result=135, data=null} to activity {in.shadowfax.gandalf/in.shadowfax.gandalf.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
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 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4449)
at in.shadowfax.gandalf.help.issues.IssuesFrag.onActivityResult(IssuesFrag.java:153)
at in.shadowfax.gandalf.help.HelpPresenter.triggerIssuesFragOnActivityResult(HelpPresenter.java:72)
at in.shadowfax.gandalf.help.HelpFrag.onActivityResult(HelpFrag.java:100)
at in.shadowfax.gandalf.MainActivity.onActivityResult(MainActivity.java:901)
at android.app.Activity.dispatchActivityResult(Activity.java:6428)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
at android.app.ActivityThread.-wrap16(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
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) 
Instead of
((BaseActivity) context).startActivityForResult(intent, Frag1.REQ_CODE_ISSUE_DONE);
using
fragment.startActivityForResult(intent, Frag1.REQ_CODE_ISSUE_DONE);
solved the issue.
onActivityResult() inside Nested Fragments is now called in support lib 23.2. So no need to reroute the onActivityResult() from Actvity to frag manually as I was doing in my case.
Ref: https://inthecheesefactory.com/blog/onactivityresult-nested-fragment-support-library-v23.2/en

Android - Null Array. Runs in Android Studio emulator but not on real device when unplugged

I've been testing my app in Android Studio emulator through my Samsung S7 phone (API 23 and 6.0.1) and it works fine. When I unplug it from my laptop and run the app it crashes.
My logcat says that I am trying to call a null array... but it isn't null? I don't understand why when I run the app through Android Studio to my phone everything works fine but when I run it alone it crashes. Thankful for any help!
Here is my logcat
FATAL EXCEPTION: main
Process: com.example.abc.def, PID: 28693
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abc.def/com.example.abc.def.MainActivity}: java.lang.NullPointerException: Attempt to read from null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to read from null array
at com.example.abc.def.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) 
at android.app.ActivityThread.access$1100(ActivityThread.java:221) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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) 
And here is my code. The issue arises at the bottom when I call btn1.setText(itemArray[0]) because the array is "null"
public class MainActivity extends AppCompatActivity {
Button btn1, btn2;
String btn1Name, btn2Name;
String btnValue = "", itemValue = "", itemPosition = "";
String[] buttonArray = new String[]{"blank", "blank"};
String[] itemArray = new String[]{"blank", "blank"};
String[] positionArray = new String[]{"blank", "blank"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
btnValue = extras.getString("btnValue");
itemValue = extras.getString("itemValue");
itemPosition = extras.getString("itemPosition");
buttonArray = extras.getStringArray("buttonArray");
itemArray = extras.getStringArray("array");
positionArray = extras.getStringArray("positionArray");
if (btnValue != null && btnValue.equals("btn1")){
buttonArray[0] = btnValue;
itemArray[0] = itemValue;
positionArray[0] = itemPosition;
} else if (btnValue != null && btnValue.equals("btn2")) {
buttonArray[1] = btnValue;
itemArray[1] = itemValue;
positionArray[1] = itemPosition;
}
}
btn1.setText(itemArray[0]);
btn2.setText(itemArray[1]);
}
}
I'm guessing here, but is MainActivity the first activity in the project?
I think you wrote the code to handle returning to this activity with data from other activities. I just tried and getIntent().getExtras() returns null when the activity is first created on an emulator.
However, when I ran it on my device, getIntent generated this exception.
Note that onCreate is called once, so if you want to see the results of another activity, take a look at How to manage `startActivityForResult` on Android?.

android.content.Context.getPackageName()' on a null object reference

I am begineer in android and having problems
Above error showing while i'm trying to open main activity from login button on login activity.
when pressing the login button suddenly app stops and following error is showing
following error is showing in android monitor
10-20 18:47:23.314 13432-13432/com.antherx.prasenjit.ihdfbachatgat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antherx.prasenjit.ihdfbachatgat, PID: 13432
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.antherx.prasenjit.ihdfbachatgat/com.antherx.prasenjit.ihdfbachatgat.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2460)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2629)
at android.app.ActivityThread.access$800(ActivityThread.java:182)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1474)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5706)
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:1033)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:4358)
at com.antherx.prasenjit.ihdfbachatgat.MainActivity.<init>(MainActivity.java:26)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2629)
at android.app.ActivityThread.access$800(ActivityThread.java:182)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1474)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5706)
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:1033)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
this is login activity code is their any problem in this code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Please do not
Email = (EditText)findViewById(R.id.email);
Password = (EditText)findViewById(R.id.password);
String wel_on_login = "Welcome On IHDF Bachat Gat app";
Toast welcome = Toast.makeText(getApplicationContext(),wel_on_login,Toast.LENGTH_LONG);
welcome.show();
final Button signIn = (Button)findViewById(R.id.email_sign_in_button);
final Button register = (Button)findViewById(R.id.registration) ;
final Intent main_trans = new Intent(this, MainActivity.class);
final Intent reg_trans = new Intent(this, register.class);
signIn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
startActivity(main_trans);
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(reg_trans);
}
});
this is main activity codes is their any problem in here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.home_toolbar);
setSupportActionBar(toolbar);
newMember = (MenuItem)findViewById(R.id.new_member);
newProfile = (MenuItem)findViewById(R.id.profile) ;
Drawer =(DrawerLayout)findViewById(R.id.drawerLayout);
sToggle = new ActionBarDrawerToggle(this,Drawer,R.string.open,R.string.close);
Grp_ico = (ImageView)findViewById(R.id.grp_ico);
Drawer.addDrawerListener(sToggle);
sToggle.syncState();
getSupportActionBar();
String wel_on_main = "You are successfully on Main Home";
Toast welcome = Toast.makeText(getApplicationContext(),wel_on_main,Toast.LENGTH_LONG);
welcome.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.new_member :
startActivity(new_new_member);
case R.id.profile :
startActivity(new_new_profile);
case R.id.setting :
startActivity(new_new_setting);
case R.id.meeting :
startActivity(new_new_meeting);
default:
return super.onOptionsItemSelected(item);
}
}
for me i was trying to use the application with no base context accidently.
so i had in my application override:
#Override
protected void attachBaseContext(Context newBase) {
}
//instead of calling its super:
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);}
Change your getApplicationContext() from
Toast welcome = Toast.makeText(getApplicationContext(),wel_on_main,Toast.LENGTH_LONG);
to either getBaseContext() or preferably this

NPE at intent.getStringExtra when launched from home screen

On some device running Android 5.0 and above, my app will crash when it's opened from home screen with the following message:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.imincode.menitiplus.MainActivity.loadSelectedIntent(MainActivity.java:229)
at com.imincode.menitiplus.MainActivity.onNewIntent(MainActivity.java:213)
at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1233)
at android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2462)
at android.app.ActivityThread.performNewIntents(ActivityThread.java:2475)
at android.app.ActivityThread.handleNewIntent(ActivityThread.java:2484)
at android.app.ActivityThread.access$1600(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
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:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
and here's the code that caused the error.
private void loadSelectedIntent(Intent intent){
if ((intent != null) && (intent.getExtras() != null)){
Fragment fragment = null;
FragmentManager fManager = this.getSupportFragmentManager();
FragmentTransaction transaction = fManager.beginTransaction();
Bundle bundle;
if (intent.getStringExtra("intentCaller").equals("expensesRecurring")){
fragment = new MenuNotifications();
bundle = new Bundle();
bundle.putString("tab", "0");
fragment.setArguments(bundle);
transaction.replace(R.id.container, fragment, "fragmentMenuNotifications");
transaction.addToBackStack(null);
transaction.commit();
}else if (intent.getStringExtra("intentCaller").equals("creditCard")){
fragment = new MenuNotifications();
bundle = new Bundle();
bundle.putString("tab", "1");
fragment.setArguments(bundle);
transaction.replace(R.id.container, fragment, "fragmentMenuNotifications");
transaction.addToBackStack(null);
transaction.commit();
}else if (intent.getStringExtra("intentCaller").equals("locationAlert")){
fragment = new MenuNotifications();
bundle = new Bundle();
bundle.putString("tab", "2");
fragment.setArguments(bundle);
transaction.replace(R.id.container, fragment, "fragmentLocationAlert");
transaction.addToBackStack(null);
transaction.commit();
}
}
}
Specifically, the line that throws the error is
if (intent.getStringExtra("intentCaller").equals("expensesRecurring"))
loadSelectedIntent would be called from 2 places in MainActivity.
The first one:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
loadSelectedIntent(intent);
}
And the second one:
#Override
protected void onResume() {
super.onResume();
Intent isThereAnyIntentHere = getIntent();
if ((isThereAnyIntentHere != null) && (isThereAnyIntentHere.getExtras() != null)){
loadSelectedIntent(isThereAnyIntentHere);
}
}
Take note that this error would only appear when the user tries to launch the app by clicking on the app's icon on the home screen. The app can be lauched without any problem if the user clicks on 'Open App' from Play Store.
Why do this error happens only on selected devices, and only when launched from the home screen?
And I thought by putting the code
if ((intent != null) && (intent.getExtras() != null))
it surely would have made sure intent.getStringExtra isn't null?
The line intent.getExtras() != null only guarantees there is some kind of extra in your intent, but that is not limited to only the extras you've set. The launch intent may contain anything.
The problem is that intent.getStringExtra() can return null if it doesn't find the extra name you were trying to find. One quick and dirt solution is to invert your if statement as follows:
if ("expensesRecurring".equals(intent.getStringExtra("intentCaller")))
You can also check for the nullity of your extra and then consume it as in:
if (intent.getStringExtra("intentCaller") != null && intent.getStringExtra("intentCaller").equals("expensesRecurring"))
And I thought by putting the code
if ((intent != null) && (intent.getExtras() != null))
it surely would have made sure intent.getStringExtra isn't null?
nope, you know that the extras bundle isn't null but you haven't established that the specific keys exist. getStringExtra documentation
So from getExtras documentation we know that it will return null if there aren't any extras.

Categories

Resources