我正在尝试获取故障单响应并将其显示在自定义列表视图中。问题是,如果票证存在并从服务器获得此类响应,它将完美显示列表,但是当没有票证且服务器响应为Status:failed Msg:No ticket available
时。
以下是我的代码:
class viewticket extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(UserLogedIn.this);
pdialog.setMessage("Loading....");
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
pdialog.show();
}
@Override
protected String doInBackground(String... params) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("userid", u_id));
// JSONObject jsonArray = jpar.makeHttpRequest(URLMyTicket, "POST", param);
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(URLMyTicket, ServiceHandler.POST, param);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try {
contacts = new JSONArray(jsonStr);
a=contacts.length();
Log.v(TAG,""+a);
if(a > 0 )
{
id = new String[contacts.length()];
prob = new String[contacts.length()];
desc = new String[contacts.length()];
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String aa = c.getString(TAG_ID);
String bb = c.getString(TAG_PROB);
String cc = c.getString(TAG_DESC);
Log.v(TAG, "TAG_ID" + aa);
Log.v(TAG, "TAGPROB" + bb);
Log.v(TAG, "TAGDESC" + cc);
id[i] = aa;
prob[i] = bb;
desc[i] = cc;
Log.v(TAG, "aaaaa" + id[i]);
Log.v(TAG, "bbbbb" + prob[i]);
Log.v(TAG, "ccc" + desc[i]);
}
}
} catch (JSONException e) {
System.out.print("hiiiiiiiiiiii" );
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Dismiss the progress dialog
Log.v(TAG,"length of aaaaa"+a);
if(id.length > 0 )//i will get error if ticket is not present Attempt to get length of null array
{
Ticket_adapter adapter=new Ticket_adapter(UserLogedIn.this,id,prob,desc);
lv.setAdapter(adapter);
}
else
{
Toast.makeText(UserLogedIn.this, "No Ticket Present", Toast.LENGTH_SHORT).show();
}
pdialog.hide();
pdialog.dismiss();
}
}
如果票证不存在,我会收到以下错误
处理:com.example.surun.suruninfocore,PID:22673 java.lang.NullPointerException:尝试获取null数组的长度 at com.example.surun.suruninfocore.UserLogedIn $ viewticket.onPostExecute(UserLogedIn.java:791) at com.example.surun.suruninfocore.UserLogedIn $ viewticket.onPostExecute(UserLogedIn.java:720)
见第791行:
if (id.length > 0)
和第720行:
class viewticket extends AsyncTask<String, Void, String> {
答案 0 :(得分:0)
Change your if condition to id!=null && id.length > 0
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Dismiss the progress dialog
Log.v(TAG,"length of aaaaa"+a);
if(id!=null && id.length > 0 )//i will get error if ticket is not present Attempt to get length of null array
{
Ticket_adapter adapter=new Ticket_adapter(UserLogedIn.this,id,prob,desc);
lv.setAdapter(adapter);
}
else
{
Toast.makeText(UserLogedIn.this, "No Ticket Present", Toast.LENGTH_SHORT).show();
}
pdialog.hide();
pdialog.dismiss();
}