I have an application with one activity and this activity has a fragment. In this fragment I show in a Listview "pending orders". I set up I method to reload the search in my database for the pending order once every 55 seconds. And I reload the Activity once every 60 seconds. 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
And I am trying to track this problem but it's not very easy because I am still a beginner in Android development.
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 78 is:
VolleyHelper.java 34 is:
For the Pending order fragment: Line 47 is:
public class PendingOrdersFragment extends Fragment implements AdapterView.OnItemClickListener {
Line 105 is:
new VolleyHelper(getActivity()).get("chefOrderDetailsByDate/" + PrefernceHelper.getString(getActivity(), Commons.Constants.USER_ID) + "/" + date, null, new Response.Listener<JSONObject>() {
Line 222 is:
callServiceForMenuStatusDetails(postFormater.format(c.getTime()));
Your Error means that the variable that the function getCacheDir () uses is null. 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()
.
This Error is because the mContext which you are passing is null
//Put an if condition to check if mContext is null or not
if(mContext()!=null) {
requestQueue = Volley.newRequestQueue(mContext());
}
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.