简体   繁体   English

Android:尝试对空对象引用调用虚拟方法

[英]Android: Attempt to invoke virtual method on a null object reference

I have an application with one activity and this activity has a fragment.我有一个包含一个活动的应用程序,这个活动有一个片段。 In this fragment I show in a Listview "pending orders".在这个片段中,我在 Listview 中显示了“挂单”。 I set up I method to reload the search in my database for the pending order once every 55 seconds.我设置了 I 方法,每 55 秒在我的数据库中重新加载对挂单的搜索。 And I reload the Activity once every 60 seconds.我每 60 秒重新加载一次活动。 The problem is that something when the fragment is being loaded I get this error:问题是在加载片段时出现此错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.io.File android.content.Context.getCacheDir()”

And I am trying to track this problem but it's not very easy because I am still a beginner in Android development.我正在尝试跟踪这个问题,但这不是很容易,因为我仍然是 Android 开发的初学者。

This is the fragment:这是片段:

public class PendingOrdersFragment extends Fragment implements AdapterView.OnItemClickListener {

    ListView lstOrders;
    ArrayList<ChefOrderList> orderLists;
    TextView empty;

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private final Handler handler = new Handler();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_list, null);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        doTheAutoRefresh();
        lstOrders = (ListView) view.findViewById(lstFood);
        lstOrders.setOnItemClickListener(this);
        empty = (TextView) view.findViewById(R.id.empty);

        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (NetworkHelper.isOnline(getActivity())) {
                    callServiceForMenuStatusDetails(PrefernceHelper.getString(getActivity(),Commons.Constants.DATE));
                } else {
                    NetworkHelper.noNetworkToast(getActivity());
                }
            }
        });

        System.out.println(PrefernceHelper.getString(getActivity(), Commons.Constants.DATE));

        if (NetworkHelper.isOnline(getActivity())) {
            callServiceForMenuStatusDetails(PrefernceHelper.getString(getActivity(), Commons.Constants.DATE));
        } else {
            NetworkHelper.noNetworkToast(getActivity());
        }

    }

    //ProgressDialog progressDialog;

    private void callServiceForMenuStatusDetails(String date) {

        //progressDialog = new ProgressDialog(getActivity());
        //progressDialog.setTitle("Loading");
        //progressDialog.setMessage("Please Wait");
        //progressDialog.setCancelable(false);
        //progressDialog.show();

        new VolleyHelper(getActivity()).get("chefOrderDetailsByDate/" + PrefernceHelper.getString(getActivity(), Commons.Constants.USER_ID) + "/" + date, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                orderLists = new ArrayList<ChefOrderList>();
                mSwipeRefreshLayout.setRefreshing(false);
                try {
                    JSONArray jsonArray = response.getJSONArray("orderlist");
                    int pending = 0, accepted = 0, rejected = 0;

                    for (int i = 0; i < jsonArray.length(); i++) {
                        ChefOrderList orderList = new ChefOrderList();
                        JSONObject jsonObject = jsonArray.getJSONObject(i);


                        orderList.setOrderId(jsonObject.getString("orderid"));
                        orderList.setOrderStatus(jsonObject.getString("order_status"));
                        orderList.setOrderDate(jsonObject.getString("order_date"));
                        orderList.setOrderFrom(jsonObject.getString("orderfrom"));

                        if(jsonObject.getString("order_status").equals("Pending")) {
                            //System.out.println(orderList.getOrderId());
                            orderLists.add(orderList);
                            pending = pending + 1;
                            TabLayoutScreenActivity.orderSizeVariable = TabLayoutScreenActivity.orderSizeVariable + 1;
                        } else if (jsonObject.getString("order_status").equals("Order accepted by chef")){
                            accepted = accepted + 1;

                        } else if (jsonObject.getString("order_status").equals("Order rejected by chef")){
                            rejected = rejected + 1;
                        }
                    }

                    //for (int i= 0; i< orderLists.size();i++) {
                    //    System.out.println(orderLists.get(i).getOrderId());
                    //}

                    System.out.println("Variable: " + TabLayoutScreenActivity.orderSizeVariable);
                    System.out.println("Fixed: " + TabLayoutScreenActivity.orderSizeFixed);

                    if (TabLayoutScreenActivity.orderSizeVariable > TabLayoutScreenActivity.orderSizeFixed){
                        TabLayoutScreenActivity.orderSizeFixed = TabLayoutScreenActivity.orderSizeVariable;
                        PushNotification();
                    }
                    TabLayoutScreenActivity.orderSizeVariable = 0;



                    if(jsonArray.length() > 0 && pending!=0) {
                        lstOrders.setVisibility(View.VISIBLE);
                        empty.setVisibility(View.INVISIBLE);
                        ChefOrderListAdapter adpater = new ChefOrderListAdapter(getActivity(), orderLists);
                        lstOrders.setAdapter(adpater);
                    }else {
                        lstOrders.setEmptyView(getView().findViewById(android.R.id.empty));
                        empty.setVisibility(View.VISIBLE);
                        lstOrders.setVisibility(View.INVISIBLE);
                    }

                    //progressDialog.dismiss();


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    public void PushNotification()
    {
        NotificationManager nm = (NotificationManager)getContext().getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(getContext());
        Intent notificationIntent = new Intent(getContext(), TabLayoutScreenActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(getContext(),0,notificationIntent,0);

        //set
        builder.setContentIntent(contentIntent);
        builder.setSmallIcon(R.drawable.chef_hat);
        builder.setContentText("Click here to open the app.");
        builder.setContentTitle("You have a new order!");
        if(android.os.Build.VERSION.SDK_INT>=21) {
            builder.setColor(Color.parseColor("#D8540D"));
        }
        builder.setAutoCancel(true);
        builder.setDefaults(Notification.DEFAULT_ALL);

        Notification notification = builder.build();
        nm.notify((int)System.currentTimeMillis(),notification);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        System.out.println("Test");
        Intent intent = new Intent();
        intent.putExtra("orderID", orderLists.get(position).getOrderId());
        intent.putExtra("orderFrom", orderLists.get(position).getOrderFrom());
        intent.setClass(getActivity(), OrderDetailsActivity.class);
        startActivity(intent);
        getActivity().finish();

    }

    private void doTheAutoRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                System.out.println("Auto refresh: Pending");
                //if (!(PrefernceHelper.getString(getActivity(), Commons.Constants.DATE).equals(null))) {
                Calendar c = Calendar.getInstance();
                SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd");
                callServiceForMenuStatusDetails(postFormater.format(c.getTime()));
                //}
                doTheAutoRefresh();
            }
        }, 55000);
    }
}

This is the full log cat for the error:这是错误的完整日志猫:

在此处输入图片说明

Volley.java 43 is: Volley.java 43 是:

在此处输入图片说明

Volley.java 78 is: Volley.java 78 是:

在此处输入图片说明

VolleyHelper.java 34 is: VolleyHelper.java 34 是:

在此处输入图片说明

For the Pending order fragment: Line 47 is:对于挂单片段:第 47 行是:

public class PendingOrdersFragment extends Fragment implements AdapterView.OnItemClickListener {

Line 105 is:第 105 行是:

new VolleyHelper(getActivity()).get("chefOrderDetailsByDate/" + PrefernceHelper.getString(getActivity(), Commons.Constants.USER_ID) + "/" + date, null, new Response.Listener<JSONObject>() {

Line 222 is:第 222 行是:

callServiceForMenuStatusDetails(postFormater.format(c.getTime()));

Your Error means that the variable that the function getCacheDir () uses is null.您的错误意味着函数getCacheDir ()使用的变量为空。 In this case your variable context.在这种情况下,您的变量上下文。 You can get your Application Context like this:您可以像这样获取应用程序上下文:

public void onCreate() {
    super.onCreate();
    Context mContext = getApplicationContext();
}

In my case, the crash was happening because of activity reference, when I was trying to finish Activity, to restart the App.就我而言,崩溃是由于活动引用而发生的,当我尝试完成活动以重新启动应用程序时。 The following error was coming for me:以下错误对我来说:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.finish()' on a null object reference

I solved it like this, NameOfActivity.this.finish() .我是这样解决的, NameOfActivity.this.finish()

This Error is because the mContext which you are passing is null此错误是因为您传递的 mContext 为空

//Put an if condition to check if mContext is null or not

     if(mContext()!=null) {
        requestQueue = Volley.newRequestQueue(mContext());               
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试在null对象引用上调用虚拟方法android.widget.EditText.getText() - Attempt to invoke virtual method on Attempt to invoke virtual method android.widget.EditText.getText() on a null object reference Android尝试在空对象引用上调用虚拟方法“…” - Android Attempt to invoke virtual method '…' on a null object reference Android Studio“尝试在空对象引用上调用虚拟方法” - Android studio “ Attempt to invoke virtual method on a null object reference” 尝试在空对象引用android上调用虚方法 - attempt to invoke virtual method on a null object reference android Android Studio蓝牙:-尝试在空对象引用上调用虚拟方法 - Android Studio Bluetooth :- attempt to invoke a virtual method on a null object reference android studio:尝试在空对象引用上调用虚拟方法 - android studio: Attempt to invoke virtual method on a null object reference Android Kotlin 片段:&#39;&#39;尝试在空对象引用上调用虚拟方法&#39;&#39; - Android Kotlin Fragments: ''Attempt to invoke virtual method on a null object reference'' Android 应用程序因“尝试在 null object 参考上调用虚拟方法”而崩溃 - Android app crashes with “Attempt to invoke virtual method on a null object reference” 尝试在空对象引用上调用虚拟方法(Android) - Attempt to invoke virtual method on a null object reference (Android) Android上下文NullPointerException:尝试在空对象引用上调用虚拟方法 - Android context NullPointerException : Attempt to invoke virtual method on a null object reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM