Android后退导航导致基于意图的活动崩溃

时间:2020-02-24 04:42:08

标签: android android-intent

我有一个包含三个活动A,B和C的Android应用。B以必要的意图形式A开头,而BI可以startActivityC。但是,当我使用操作栏上的后退按钮从C返回到B,因为B没有收到意图,应用程序崩溃。如何解决这个问题。

活动B的代码,从活动A获得意图。对于活动B起作用,具有此意图很重要。

 @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();
}

从B转到C

 confirm.setOnClickListener(v -> {
        Intent intent = new Intent(getApplicationContext(), CheckoutActivity.class);
        intent.putExtra("spot", parkingSpot);
        intent.putExtra("pos", pos);
        startActivity(intent);
    });

现在,应用已打开活动C。在活动B中点击向C的后退箭头图标会导致错误,因为B丢失了其意图数据

Activity B

Activity C

按下返回按钮时,调试器出现错误

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)

唯一的一点是B到C可以正常工作,反之亦然。我认为这是因为B没有保留其意图数据

3 个答案:

答案 0 :(得分:1)

在OnCreate方法中添加以下内容:

if (getSupportActionBar() != null)
{
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

然后添加此方法:

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

答案 1 :(得分:0)

在代码行下面放入活动B onCreate(),在其中获取意图数据

if(getIntent()!=null){
   //your intent code
}

这就是;)

答案 2 :(得分:0)

您可以使用MVVM,Moxy MVP结构或saveInstance来存储您的数据并使用它。当您从C返回到B时,它将使用该数据存储算法之一,并且不会崩溃。因此,每次检查

if (savedInstance != null ){
    spot = savedInstance.getParcelable("spot");
} else {
    spot = getIntent().getParcelableExtra("spot");
}