简体   繁体   中英

DialogFragment 'java.lang.String android.content.Context.getPackageName()' on a null object reference

I am working with DialogFragment and using Volley to insert data into mysql. The data is successfully inserted into the db but it always crashes after. I always get this error in my logcat java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference The error is in my Toast. Please help

public class ExpensesLeisureDialog extends DialogFragment {
EditText name, amount, details;
String nameHolder, amountHolder, detailsHolder;
Boolean CheckEditText;
RequestQueue requestQueue;

HashMap<String,String> hashMap = new HashMap<>();
String finalResult;
HttpParse httpParse = new HttpParse();
String HttpURL = "http://10.0.2.2:63343/TheMoneyger/api/add-leisure.php";

@Override
public Dialog onCreateDialog (Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.fragment_add_expenses_dialog, null));
    requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
    builder.setTitle("Add leisure expense")
            .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    name = (EditText) getDialog().findViewById(R.id.editText1);
                    amount = (EditText) getDialog().findViewById(R.id.editText2);
                    details = (EditText) getDialog().findViewById(R.id.editText3);

                    CheckEditTextIsEmpty();
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpURL,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
                                }
                            }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("expensename", nameHolder);
                            params.put("expenseamount", amountHolder);
                            params.put("details", detailsHolder);
                            return params;
                        }
                    };

                    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
                    requestQueue.add(stringRequest);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    return builder.create();
}

public void CheckEditTextIsEmpty() {
    nameHolder = name.getText().toString();
    amountHolder = amount.getText().toString();
    detailsHolder = details.getText().toString();
}

Here is my logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                                                                                   at android.widget.Toast.<init>(Toast.java:114)
                                                                                   at android.widget.Toast.makeText(Toast.java:277)
                                                                                   at android.widget.Toast.makeText(Toast.java:267)
                                                                                   at com.example.merylle.themoneyger.fragment.ExpensesLeisureDialog$2$1.onResponse(ExpensesLeisureDialog.java:65)
                                                                                   at com.example.merylle.themoneyger.fragment.ExpensesLeisureDialog$2$1.onResponse(ExpensesLeisureDialog.java:62)
                                                                                   at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                                                                                   at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                                                                                   at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                                   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)

Try This

  • this is your code you can pass the getcontext() in your tost getcontext return he null value.

getContext:- it's the context of the current state of the application/object.

Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();

getContext change into getActivity like this:

Toast.makeText(getActivity(), response, Toast.LENGTH_SHORT).show();

getActivity :- getActivity is a function, it returns an Activity. It's a function of a Fragment, and returns the Activity the fragment is attached to. It's null if no Activity is attached to the fragment.

I hope it helps you

Update

Store context when onAttach method called.

public class ExpensesLeisureDialog extends DialogFragment {
       Context context;

       @Override
       public void onAttach(Context context) {
           super.onAttach(context);
           this.context = context;
       }
       .
       .
}

And use context variable when you have required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM