空对象引用上的DialogFragment'java.lang.String android.content.Context.getPackageName()'

时间:2018-11-02 04:20:41

标签: java android

我正在使用DialogFragment并使用Volley将数据插入mysql。数据已成功插入数据库,但之后始终会崩溃。我总是在我的logcat java.lang.NullPointerException中收到此错误:尝试在空对象引用上调用虚拟方法'java.lang.String android.content.Context.getPackageName()'。错误在我的Toast中。请帮助

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

这是我的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)

2 个答案:

答案 0 :(得分:1)

尝试

  • 这是您的代码,您可以在tost getcontext中传递getcontext()返回空值。

getContext:-:它是应用程序/对象当前状态的上下文。

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

getContext像这样更改为getActivity:

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

getActivity:- getActivity是一个函数,它返回一个Activity。它是Fragment的功能,并返回该片段所附加的Activity。如果片段没有任何活动,则为null。

希望对您有帮助

答案 1 :(得分:0)

更新

调用 onAttach 方法时存储上下文

public class ExpensesLeisureDialog extends DialogFragment {
       Context context;

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

并在需要时使用 context 变量。