我在android中創建應用程序,我有登錄註銷活動,Multilistview活動哪些數據來自其他Web服務。這裏的問題是,當從登錄活動調用webservice時,我得到錯誤networkonmainthreadexception然後我搜索了有關該異常的護目鏡,有人說在堆棧溢出使用AsyncTask在你的代碼分離線程和我在我的代碼中執行asynctask但不工作。我完全混淆瞭如何使用asynctask,我想在下面的代碼中添加asynctask。我提供的代碼沒有asynctask,我做了。任何人都可以幫助我在調用webservice時如何正確使用asynctask。android:如何在Rest Web服務中使用asyncTask?
以下是編輯文本通話功能
UserFunctions userFun = new UserFunctions();
if ((username.trim().length() > 0)&&(userpsw.trim().length() > 0)) {
JSONObject json = userFun.loginUser(username, userpsw);
.
.
.
以下是功能類
public JSONObject loginUser(String userEmail, String userPsw) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", userEmail));
params.add(new BasicNameValuePair("password", userPsw));
JSONObject json = jsonParser.getJsondataFromUrl(params);
//Log.d("tag", json.toString());
return json;
}
下面是實際WebService類提前
public void getJsondataFromUrl(List<NameValuePair> params) {
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResp = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResp.getEntity();
inStream = httpEntity.getContent();
//Log.d(tag, inStream.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader bufferReader = new BufferedReader(new InputStreamReader
(inStream, "iso-8859-1"), 8);
StringBuilder strBuilder = new StringBuilder();
String line = null;
while ((line = bufferReader.readLine()) != null) {
strBuilder.append(line + "n");
}
inStream.close();
json = strBuilder.toString();
//Log.d("JSON", json);
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObj;*/
}
由於獲取數據
感謝Snicolas很好的信息。我還閱讀了關於robospice的鏈接。 – Nilesh