Click here to Skip to main content
15,845,308 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have error
Process: id.ac.astra.polytechnic.toolmaintenance, PID: 22120
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
    at id.ac.astra.polytechnic.toolmaintenance.viewModel.RoleListViewModel.addRole(RoleListViewModel.java:53)
    at id.ac.astra.polytechnic.toolmaintenance.AddRoleFragment$2.onClick(AddRoleFragment.java:79)
    at android.view.View.performClick(View.java:7756)
    at android.view.View.performClickInternal(View.java:7729)
    at android.view.View.access$3700(View.java:860)
    at android.view.View$PerformClick.run(View.java:29318)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:210)
    at android.os.Looper.loop(Looper.java:299)
    at android.app.ActivityThread.main(ActivityThread.java:8298)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:576)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1073)



And this is my code:
AddRoleFragment.java
public class AddRoleFragment extends Fragment {
    private Role mRole;
    private EditText roleName;
    private RoleListViewModel mRoleListViewModel;


    public static AddRoleFragment newInstance() {
        return new AddRoleFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Log.i(TAG, "UserFragment.onCreate() called");

        mRole = new Role();
        mRoleListViewModel = new ViewModelProvider(this)
                .get(RoleListViewModel.class);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.add_role, container, false);

        Button btnSimpan = view.findViewById(R.id.btnSimpan);
        roleName = view.findViewById(R.id.inputNamaJabatan);
        roleName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
               mRole.setRolename(s.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        btnSimpan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Ketika btnPeminjaman ditekan, tampilkan PeminjamanFragment

            //    mRole.setRolename(String.valueOf(roleName));

                mRoleListViewModel.addRole(mRole);

                Fragment peminjamanFragment = ListKelolaRoleFragment.newInstance();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, peminjamanFragment, "peminjaman");
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });

        return view;
    }
}


RoleListViewModel.java

public class RoleListViewModel extends ViewModel {

    private MutableLiveData<List<Role>> mRoleListMutableLiveData;
    private RoleRepository mRoleRepository;

    public RoleListViewModel(){
        Log.d(TAG, "RoleListViewModel constructor called");
        mRoleRepository = RoleRepository.get();

    }
    public MutableLiveData<List<Role>> Roles(){
        mRoleListMutableLiveData = mRoleRepository.Roles();
        Log.d(TAG,"RoleListViewModel.getRoles() called ="+
                mRoleListMutableLiveData.toString());
        return mRoleListMutableLiveData;
    }

    public void addRole (Role Role) {

        mRoleRepository.addRole (Role);
        Log.d(TAG,"RoleListViewModel.getRoles() called ="+
                mRoleListMutableLiveData.toString());
    }
    }


RoleRepository
public class RoleRepository {
    private static final String TAG = "RoleRepository";
    public static RoleRepository INSTANCE;

    private RoleService mRoleService;

    private MutableLiveData<List<Role>> mRoleListMutableLiveData;

    //hubungan dgn APIutils utk daepetin fungsi
    private RoleRepository(Context context) {
        mRoleService = ApiUtils.getRoleService();
    }

    public static void initialize(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new RoleRepository(context);
        }
    }
    private  RoleRepository(){

    }
    public static RoleRepository get() {

        return INSTANCE;
    }

    public MutableLiveData<List<Role>> Roles() {
        MutableLiveData<List<Role>> Roles = new MutableLiveData<List<Role>>();

        Call<List<Role>> call = mRoleService.Roles();
        call.enqueue(new Callback<List<Role>>() {
            @Override
            public void onResponse(Call<List<Role>> call, Response<List<Role>> response) {
                if (response.isSuccessful()) {
                    Roles.setValue(response.body());
                    Log.d(TAG, "getRoles.onResponse() called");
                }
            }

            @Override
            public void onFailure(Call<List<Role>> call, Throwable t) {
                Log.e("Error API call :", t.getMessage());
            }
        });
        return Roles;
    }

    public void addRole(Role Role){
        Log.i(TAG, "addRole() called");
        Call <Role> call = mRoleService.addRole (Role);
        Log.i(TAG, "addRole2() called");

        call.enqueue(new Callback<Role>() {
            @Override
            public void onResponse (Call<Role> call, Response <Role> response) { if (response.isSuccessful()){
                Log.i(TAG, "Role added " + Role.getRolename());
            }
            }
            @Override
            public void onFailure (Call<Role> call, Throwable t) {
                Log.e("Error API call ", t.getMessage());
            }
        });
    }
}


What I have tried:

Please help me to solve this error
Posted
Updated 3-Jul-23 1:48am

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Details here:
Class NullPointerException[^]
Java error java.lang.nullpointerexception[^]

DEBUG and look for the potential place and fix/handle it.

Reference: How to resolve the java.lang.NullPointerException[^]
Quote:
In Java, the java.lang.NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Your case, error and line of code is pretty clear being raised from:
Java
public void addRole (Role Role) {
        mRoleRepository.addRole (Role);

Debug and see why that is null. Set it up correctly and handle null condition.

If needed, look:
jdb - The Java Debugger[^]
Debugging the Eclipse IDE for Java Developers | The Eclipse Foundation[^]
 
Share this answer
 
This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and your IDE will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
By checking stack traces it is clear your exception has been thrown in

public void addRole (Role Role) {

      mRoleRepository.addRole (Role);
      Log.d(TAG,"RoleListViewModel.getRoles() called ="+
              mRoleListMutableLiveData.toString());
  }


and @
mRoleListMutableLiveData.toString());
. Since
mRoleListMutableLiveData
reference has not been initialized ( had null value )before accessing it in above method . Please use null check

like

Log.d(TAG,"RoleListViewModel.getRoles() called ="+( mRoleListMutableLiveData!=null ?  mRoleListMutableLiveData.toString() :"");


or Initialize it in constructor

public RoleListViewModel(){
        Log.d(TAG, "RoleListViewModel constructor called");
        mRoleRepository = RoleRepository.get();
mRoleListMutableLiveData = mRoleRepository.Roles();

    }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900