0

I am trying to implement the ViewModel Module but it is giving me this Null Pointer Exception Error.

Here is the error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ssnwa.cargoin.cargoincustomer, PID: 11374
java.lang.NullPointerException: Attempt to invoke virtual method 'androidx.lifecycle.MutableLiveData androidx.lifecycle.SavedStateHandle.getLiveData(java.lang.String)' on a null object reference
    at com.ssnwa.cargoin.cargoincustomer.DriverToPickupViewModel.getPickupLocation(DriverToPickupViewModel.java:43)
    at com.ssnwa.cargoin.cargoincustomer.DrivertoPickupActivity.onMapReady(DrivertoPickupActivity.java:287)
    at com.google.android.gms.maps.zzak.zza(Unknown Source:2)
    at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source:12)
    at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source:12)
    at android.os.Binder.transact(Binder.java:627)
    at cj.b(:com.google.android.gms.dynamite_mapsdynamite@19831052@19.8.31 (040700-0):14)
    at com.google.android.gms.maps.internal.bb.a(:com.google.android.gms.dynamite_mapsdynamite@19831052@19.8.31 (040700-0):4)
    at com.google.maps.api.android.lib6.impl.bi.run(:com.google.android.gms.dynamite_mapsdynamite@19831052@19.8.31 (040700-0):2)
    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:6494)
    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)

Here is the calling activity:

public class DrivertoPickupActivity extends AppCompatActivity implements
    OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener , RoutingListener {

public static String driverphno;
public Marker drivermarker;
public static Location driverloc=new Location("");
public static Location pickuploc=new Location("");
private DriverToPickupViewModel vm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.driver_reach_pickup_activity);

    vm = new ViewModelProvider(this).get(DriverToPickupViewModel.class);

    mpleasewait=new ProgressDialog(this);
    mpleasewait.setTitle("Please Wait ...");


    pickuploc.setLatitude(pickcordinates.latitude);
    pickuploc.setLongitude(pickcordinates.longitude);





    database=FirebaseDatabase.getInstance();
    d2=FirebaseDatabase.getInstance();
    ref=database.getReference();
    ref2=d2.getReference();

    drivername=findViewById(R.id.driver_name);
    number=findViewById(R.id.phone_number);
    kmtoreach=findViewById(R.id.reach_km_to_pickup);
    timetoreach=findViewById(R.id.reach_time_to_pickup);
    cancelbooking=findViewById(R.id.cancel_booking);
    inforide=findViewById(R.id.info_ride);




    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.drivermap);
    mapFragment.getMapAsync(this);



    setupActions();

}

@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);


    if(vm!=null){
//CRASHES AT THIS LINE AND ALL OTHER SIMILAR LINES THAT FOLLOW
        vm.getdrivername().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                drivername.setText(s);
            }
        });

        vm.getdriverphone().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                number.setText(s);
            }
        });

        vm.getdistance().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                kmtoreach.setText(s);
            }
        });

        vm.gettime().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                timetoreach.setText(s);
            }
        });
    }

}

IT CRASHES AT THIS LINE AND ALL OTHER SIMILAR LINES THAT FOLLOW

vm.getdrivername()

Here is the ViewModel class

public class DriverToPickupViewModel extends ViewModel {
private SavedStateHandle mState;

public DriverToPickupViewModel(){}

public DriverToPickupViewModel(SavedStateHandle savedStateHandle){
    mState = savedStateHandle;
}

void setPickupLocation(Location L){
    mState.set("Pickup",L);
}

void setDriverLocation(Location L){
    mState.set("Driver",L);
}

void setdrivername(String drivername){
    mState.set("drivername",drivername);
}

void setdriverphone(String phone){
    mState.set("phone", phone);
}

void setdistance(String distance){
    mState.set("distance",distance);
}

void settime(String time){
    mState.set("time",time);
}

LiveData<Location> getPickupLocation(){
    return mState.getLiveData("Pickup");
}

LiveData<Location> getDriverLocation(){
    return mState.getLiveData("Driver");
}

LiveData<String> getdrivername(){
    return mState.getLiveData("drivername");
}

LiveData<String> getdriverphone(){
    return mState.getLiveData("phone");
}

LiveData<String> getdistance(){
    return mState.getLiveData("distance");
}

LiveData<String> gettime(){
    return mState.getLiveData("time");
}

}

I am not able to understand as to why this is happening. I have checked for vm==null. It is not crashing here, which means the viewmodel is not null but it is crashing at every vm.get**** method

As per the recent answer, mState was null which was stupid on my part to not see it.

But I try to correct it as:

        vm = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(),this)).get(DriverToPickupViewModel.class);

And i get the error:

Activity cannot be convert to SavedStateRegistry owner
Aditya Chandel
  • 105
  • 1
  • 9

1 Answers1

2

vm is not null, but mState is. The empty constructor doesn't set mState, so it is null. getdrivername then tries to call a method on the null reference.

Jeremy Roman
  • 16,137
  • 1
  • 43
  • 44
  • Yes, sorry it was stupid of me to have not seen it. When I try to correct it, I run into some other issue which i have updated. Can you help me with that – Aditya Chandel Dec 28 '19 at 14:46