我正在尝试从服务器获取数据并将其显示在我的应用中。 但是,我从服务器获取结果为null。是否有可能结果为空并且无法从服务器获取数据?
这是我服务器的数据
{
"COLUMNS": ["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"],
"DATA":
[[195,4,4,"09:00","09:00","09:00","09:00","09:00","Closed","Closed","16:30","16:30","16:30","16:30","16:30","Closed","Closed","May, 16 2017 08:16:12"]
]}
这就是我尝试获取数据的方式,
TextView timeStatus;
public static final String MON_O = "MON_O";
public static final String TUE_O = "TUE_O";
public static final String WED_O = "WED_O";
public static final String THU_O = "THU_O";
public static final String FRI_O = "FRI_O";
public static final String SAT_O = "SAT_O";
public static final String SUN_O = "SUN_O";
public static final String MON_C = "MON_C";
public static final String TUE_C = "TUE_C";
public static final String WED_C = "WED_C";
public static final String THU_C = "THU_C";
public static final String FRI_C = "FRI_C";
public static final String SAT_C = "SAT_C";
public static final String SUN_C = "SUN_C";
public static final String JSON_ARRAY = "COLUMNS";
timeStatus = (TextView) view.findViewById(R.id.time_status);
单击RelativeLayout,调用getData()函数,
timeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (timeLayoutCollapse.getVisibility() == View.GONE) {
timeLayoutCollapse.setVisibility(View.VISIBLE);
getData();
} else {
timeLayoutCollapse.setVisibility(View.GONE);
}
}
});
和JSON Response函数如下,
private void getData() {
if (dBranchID == 0) {
Log.e("no branch id", "sdsfsdf");
return;
}
String url = context.getString(site_url)+"branch_time.cfc?method=branchtime&branchid=" +dBranchID;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String name = "";
String address = "";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject companyData = result.getJSONObject(0);
mon = companyData.getString(MON_O);
tue = companyData.getString(TUE_O);
wed = companyData.getString(WED_O);
} catch (JSONException e) {
e.printStackTrace();
}
timeStatus.setText(mon);
}
我收到错误,
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference.
答案 0 :(得分:0)
问题出在这里。你得到的是timestatus的空值。修复它。
timeStatus.setText(mon);
答案 1 :(得分:0)
您的timestatus textview为null 请转换(findviewbyid)timestatus,或者你可以在doinbackground中调用该方法。 如果你把那个metod放在doinbackground中,那么它会给出空指针异常