As per some google crash report of my app i am seeing NullPointerException,
"Attempt to invoke virtual method int android.os.Bundle.getInt(java.lang.String) on a null object reference" but i have made sure and cross checked that intent to that activity always some Extras is set. Can some one suggest me what might be wrong, i am suspecting not overriding onNewIntent, is causing problem but my activity is launched with "noHistory =true" flag so onNewIntent is never called?
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_alert_dialog);
mBackToMain = false;
mDoExit = false;
int stringMessageId = getIntent().getExtras().getInt(name);
String stringMessage = getIntent().getExtras().getString(fullName);
initFields(name,fullName);
}
#Override
protected void onNewIntent(Intent intent)
{
mLog.d("WarningActivity","on new Intent triggered "+ intent.getExtras());
super.onNewIntent(intent);
int stringMessageId = getIntent().getExtras().getInt(name);
String stringMessage = getIntent().getExtras().getString(fullName);
initFields(name,fullName);
}
You may be putting extras right and something else goes wrong so make sure that the extras is not null by checking it first like so:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if(extras != null) {
if(extras.containsKey("your key here")) {
int x = extras.getInt("your key here");
}
else {
Log.d("extras", "No Key");
}
} else {
Log.d("extras", "Null Extras");
}
and then check your logcat and you should see what's really going on
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an android app with three activities A, B, and C. B starts with a necessary intent form A and from B I can startActivity C. But when I use the back button on the action bar to go back from C to B, the app crashes because B received no intent. How to solve this.
Code for Activity B, getting intent from Activity A. It is important to have this intent for the activity B to function.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parking_spot);
getSupportActionBar().hide();
spot = getIntent().getParcelableExtra("spot");
init();
}
private void init() {
days = findViewById(R.id.spot_days);
rate = findViewById(R.id.spot_rate);
timing = findViewById(R.id.spot_timing);
name = findViewById(R.id.spot_name);
address = findViewById(R.id.spot_address);
spots = findViewById(R.id.spot_spots);
// This is where null pointer exception is thrown on accessing spot variable
name.setText(spot.getName());
address.setText(spot.getAddress());
timing.setText(spot.getTiming());
String temp = getResources().getString(R.string.rs) + " " + spot.getRate() + "/HR";
rate.setText(temp);
temp = spot.getDays();
for (int i = 0; i < temp.length(); i++) {
if (temp.charAt(i) == 'T') {
setDay(i);
}
}
FirebaseDatabase.getInstance().getReference(spot.getPath()).child("spots").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long total = dataSnapshot.getChildrenCount(), free = 0;
for (DataSnapshot shot : dataSnapshot.getChildren()) {
Log.v("Spot", shot.child("status").getValue(Integer.class) + "");
if (shot.child("status").getValue(Integer.class) == 0) {
free++;
}
}
String temp = free + "/" + total;
spots.setText(temp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
findViewById(R.id.navigate_spot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + spot);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
});
findViewById(R.id.book_now).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ParkingSpotActivity.this, BookingActivity.class);
intent.putExtra("spot", spot);
startActivity(intent);
}
});
setupSlider();
}
Going to C from B
confirm.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), CheckoutActivity.class);
intent.putExtra("spot", parkingSpot);
intent.putExtra("pos", pos);
startActivity(intent);
});
Now app has opened activity C. Clicking on the back arrow icon in Activity B to C leads to an error as B loses its intent data
Erro from debugger when i press back button
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mobile.solutions.parking, PID: 26598
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobile.solutions.parking/com.mobile.solutions.parking.activity.ParkingSpotActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mobile.solutions.parking.model.ParkingSpot.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3374)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2109)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mobile.solutions.parking.model.ParkingSpot.getName()' on a null object reference
at com.mobile.solutions.parking.activity.ParkingSpotActivity.init(ParkingSpotActivity.java:59)
at com.mobile.solutions.parking.activity.ParkingSpotActivity.onCreate(ParkingSpotActivity.java:47)
at android.app.Activity.performCreate(Activity.java:7815)
at android.app.Activity.performCreate(Activity.java:7804)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)
The only point is that B to C works fine but not vice versa. This I think is because B doesn't retain its intent data
In the OnCreate method add this:
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Then add this method:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
You can use MVVM, Moxy MVP structure or savedInstance to store your data and use it. When you back from C to B it will use one of this data store algorithm and you will not get crashed. So, check every time
if (savedInstance != null ){
spot = savedInstance.getParcelable("spot");
} else {
spot = getIntent().getParcelableExtra("spot");
}
Can anybody please tell me? I am making a sample and want to detect miss call on a particular number. Suppose I opened the dialler with the number (0123456789) and when call on this number then detect missed call on this number. how can I do that. Please help ..
Check the flowing code ->
In your broadcast receiver check that if the call is received or not. Then you can find the call status.
public class CallBroadcast extends BroadcastReceiver {
private static boolean isMissedCall;
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// Ringing
isMissedCall = true;
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
// Call Received
isMissedCall = false;
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
// Call Drop
// If don't receive call then it will be missed call
if(isMissedCall){
// do your code for missed call
}
}
}
}catch (Exception e){e.printStackTrace();}
}
}
Please I get a NullPoiterException when I try to get the extras form the intent.
The error is thrown exactly when I call
int posizione2 =Integer.parseInt((getIntent().getExtras().getString(Intent.EXTRA_TEXT)));
Any help very much appreciated!
private void aggiungiImm(View arg1, int arg2) {
Intent i=newintent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
i.putExtra(Intent.EXTRA_TEXT, Integer.toString(arg2));
startActivityForResult(i, PICK_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data) {
Uri contactData=null;
if (requestCode==PICK_REQUEST) {
if (resultCode==RESULT_OK) {
contactData=data.getData();
int posizione2 =Integer.parseInt((getIntent().getExtras().getString(Intent.EXTRA_TEXT)));
EDITED:
No solution so far.
Can it be that the problem is related to the fact that this is an Implicit Intent??
Try to use data.getStringExtra(Intent.EXTRA_TEXT)
instead of
int posizione2 =Integer.parseInt((getIntent().getExtras().getString(Intent.EXTRA_TEXT)));
Try that:
Bundle extras = getIntent().getExtras();
if (extras==null) {
Log.e( "", "No extras provided" );
return;
}
String myText = extras.getString(Intent.EXTRA_TEXT);
if (myText==null) {
Log.e( "", "No text provided" );
return;
}
int posizione2 = Integer.parseInt(myText);
Should help you to see what is giving the exception...
By the way, your returned text (if that text is comming as result from the other activity) will be available in the Intent passed to the function. So you should be doing:
if (data.getString(Intent.EXTRA_TEXT)==null) {
Log.e( "", "No text provided" );
return;
}
int posizione2 = Integer.parseInt(data.getString(Intent.EXTRA_TEXT));
The getIntent() method will give you the intent with which the calling activity had been started. No the intent holding the result of the called activity.
If you are getting the No text provided message, that means you have not properly returned the result in the activity that computes it.
Here is my onCreate() method. I am trying to pass a variable from one intent to this intent. That works fine. When I press back button and go back to previous intent to change the value, then the application crashes. And also when I change the orientation, the application crashes. I am getting "Nullpointer exception" at the pp.getData() method. It passes null argument into the function. How can I overcome this? do I need to add any other details?
public void onCreate(Bundle savedInstanceState) {
// get intent data
Intent i = getIntent();
setQuery(i.getExtras().getString("query"));
Log.v("query:", getQuery());
userquery = getQuery();
super.onCreate(savedInstanceState);
setContentView(R.layout.product_view_layout);
try {
pp = new Parser(userquery);
productData = pp.getData(asynctask, userquery);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mProductViewPagerAdapter = new ProductViewPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mProductViewPagerAdapter);
}
If the "query" extra doesn't exist in the Intent then it will return null. You should perform a null check to make sure you don't get nullPointerExceptions.
String query = i.getExtras().getString("query"));
if(query == null) {
setQuery("");
}
else {
setQuery(query);
}
If you want to receive results in the first activity you have to user this"
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
}
also when you start the first activity you have to start it startActivityForResult.
On back set the result as RESULT_OK or RESULT_CANCEL. look in tho activity on developers android.
this actually does nothing when i click the button.
The button is like:
Button Confirmar = (Button)findViewById(R.id.btConfirma);
Confirmar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String Login = edLogin.getText().toString();
String Senha = edSenha.getText().toString();
if(Login.length() == 0 || Senha.length() ==0) {
Toast.makeText(getuser.this, "Por favor preencha o login e a senha!", Toast.LENGTH_LONG).show();
return;
}
if (chkKeep.isChecked() && (edLogin.getText().toString() != Settings.getUser() || edSenha.getText().toString() != Settings.getPass())) {
Settings.setUser(edLogin.getText().toString());
Settings.setPass(edSenha.getText().toString());
Settings.setKeepUser(chkKeep.isChecked());
jXML.updateConfigXml();
}
Intent i = getIntent();
Bundle bD = new Bundle();
bD.putStringArray("Login", new String[] {edLogin.getText().toString(), edSenha.getText().toString()});
i.putExtras(bD);
finishActivity(555);
}
});
As asked --> Button XML:
<Button android:layout_width="180dip" android:layout_height="wrap_content" android:id="#+id/btOkLogin" android:text="Confirmar"></Button>
SOLVED: Had to use setResult(ResulCode, Intent) before finish();
Answered by: #Sam-Quest
i guess you have to set the result before calling the finish
...
Intent i = getIntent();
Bundle bD = new Bundle();
bD.putStringArray("Login", new String[] {edLogin.getText().toString(), edSenha.getText().toString()});
i.putExtras(bD);
setResult(RESULT_OK, i);
finishActivity(555);
check this link if you have any doubt. LINK
Put a breakpoint on first line inside onClick listener, run on debug mode and see where it goes on the code.
That's a strange error. I'd try to maybe setOnClickListener(this) and let your activity implement onClick(View). Otherwise you can add android:onClick tag to the xml button object.