-2

I am working with an Uber clone tutorial and trying to set car type in a layout when updating driver info. Everything else works except the radio button part.

I tried the following but only got the following errors:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.check(int)' on a null object reference
                                                                               at DriverHome.showDialogUpdateInfo(DriverHome.java:783)
    at DriverHome.onNavigationItemSelected(DriverHome.java:771)

layout_update_info

...

<RadioGroup
        android:id="@+id/radioGroup"
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:layout_marginRight="10dp"
            android:id="@+id/RydeX"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="UberX"/>

        <RadioButton
            android:layout_marginRight="10dp"
            android:id="@+id/RydeVan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="UberBlack"/>

        <RadioButton
            android:id="@+id/RydeSUV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="UberXL"/>

    </RadioGroup>
....

DriverHome.java

public class DriverHome extends AppCompatActivity {

   private RadioGroup radioGroup;
   String service;
   private String userID;
   private DatabaseReference driverDB;

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

     ...

   }

   @RequiresApi(api = Build.VERSION_CODES.M)
   @SuppressWarnings("StatementWithEmptyBody")
   @Override
   public boolean onNavigationItemSelected(MenuItem item) {
   // Handle navigation view item clicks here.
   int id = item.getItemId();

   if (id == R.id.nav_update_info) {
     showDialogUpdateInfo();
   }

   DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
   drawer.closeDrawer(GravityCompat.START);
   return true;
   }

}


private void showDialogUpdateInfo() {

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(DriverHome.this);
    alertDialog.setTitle("UPDATE INFORMATION");
    alertDialog.setMessage("Please fill in all information");

    LayoutInflater inflater = this.getLayoutInflater();
    View layout_pwd = inflater.inflate(R.layout.layout_update_info, null);

    final MaterialEditText editName = (MaterialEditText)layout_pwd.findViewById(R.id.editName);
    final MaterialEditText editPhone = (MaterialEditText)layout_pwd.findViewById(R.id.editPhone);
    final ImageView image_upload = (ImageView) layout_pwd.findViewById(R.id.image_upload);

    saveUserInfo();

    image_upload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chooseImage();
        }
    });

    alertDialog.setView(layout_pwd);

    //Set Button
    alertDialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            final SpotsDialog waitingDialog = new SpotsDialog(DriverHome.this);
            waitingDialog.show();

            String name = editName.getText().toString();
            String phone = editPhone.getText().toString();

            Map<String, Object> updateInfo = new HashMap<>();

            if (!TextUtils.isEmpty(name)) {
                updateInfo.put("name", name);
            }

            if (!TextUtils.isEmpty(phone)) {
                updateInfo.put("phone", phone);
            }


            // user_driver.tbl = "Users/Drivers"
            DatabaseReference driverInformation = FirebaseDatabase
                    .getInstance().getReference(Common
                            .user_driver_tbl);
            driverInformation.child(FirebaseAuth.getInstance()
                    .getCurrentUser().getUid())
                    .updateChildren(updateInfo)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                Toast.makeText(DriverHome.this,
                                        "Information Updated!",
                                        Toast.LENGTH_SHORT).show();

                            } else {
                                Toast.makeText(DriverHome.this,
                                        "Information Update Failed!",
                                        Toast.LENGTH_SHORT).show();
                            }

                            waitingDialog.dismiss();
                        }
                    });

            getUserInfo();
        }

    });

    alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    alertDialog.show();
}


private void saveUserInfo() {

    radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
    radioGroup.check(R.id.UberX);

    int selectId = radioGroup.getCheckedRadioButtonId();

    final RadioButton radioButton = (RadioButton)findViewById(selectId);

    if (radioButton.getText() == null) {
        return;
    }

    service = radioButton.getText().toString();

    Map updateInfo = new HashMap();
    updateInfo.put("service", service);
}


private void getUserInfo() {

    driverDB.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                if(map.get("service")!=null){
                    service = map.get("service").toString();
                    switch (service){
                        case"RydeX":
                            radioGroup.check(R.id.UberX);
                            break;
                        case"RydeVan":
                            radioGroup.check(R.id.UberBlack);
                            break;
                        case"RydeSUV":
                            radioGroup.check(R.id.UberXL);
                            break;
                    }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });

}

This is how it looks:

enter image description here

What I am trying to do is save the information to Firebase database: name, phone, image and Type of Car the driver has.

halfer
  • 19,824
  • 17
  • 99
  • 186
LizG
  • 2,246
  • 1
  • 23
  • 38

1 Answers1

1

Its simply a java.lang.NullPointerException

Problem
your RadioGroup is part of AlertDialog not DriverHome Activity. so the line below will return null.

radioGroup = (RadioGroup)findViewById(R.id.radioGroup);

Solution

You should get RadioGroup from its parent container which is AlertDialog. and do same for RadioButton although you can also get RadioButton from RadioGroup cause its the parent of all RadioButton.

radioGroup = (RadioGroup)layout_pwd.findViewById(R.id.radioGroup);
ADM
  • 20,406
  • 11
  • 52
  • 83
  • I tried putting the contents of saveUserInfo() into AlertDialog and got same error. – LizG Jan 06 '18 at 04:16
  • You have to use `layout_pwd.findViewById()` not `findViewById()` as i said in my answer. – ADM Jan 06 '18 at 04:23
  • I just tried that and got error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.check(int)' on a null object reference at com.devhopes.rydedriver.DriverHome.showDialogUpdateInfo(DriverHome.java:783) at com.devhopes.rydedriver.DriverHome.onNavigationItemSelected(DriverHome.java:771) – LizG Jan 06 '18 at 04:26
  • line783: alertDialog.setTitle("UPDATE INFORMATION"); – LizG Jan 06 '18 at 04:27
  • line 771; if (id == R.id.nav_update_info) { showDialogUpdateInfo() – LizG Jan 06 '18 at 04:27
  • I also updated this line final RadioButton radioButton = (RadioButton)layout_pwd.findViewById(selectId); and it showed the Dialog but it didn't update to Firebase => service: "UberX" – LizG Jan 06 '18 at 04:36