How Do I Make My Connection An Asynctask Connection
UPDATE: I found that the easiest way is to use AQuery. I need to get my HttpPost for getting JSON data on another thread and I dont know how to get it all working together. Ive lo
Solution 1:
I think you can try something like this:
publicclassMyActivityextendsActivity {
// paring dataint q_id;
String q_label;
String q_title;
String q_description;
String q_gotoURL;
Context context;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
mList = (ListView) findViewById(R.id.sidebar_list);
context = getApplicationContext();
newHttpTask().execute("http://192.168.1.34/xxxx/xxxxx_list.php");
}
privateclassHttpTaskextendsAsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
HttpClienthttpClient=newDefaultHttpClient();
HttpPosthttpPost=newHttpPost(urls[0]);
List<NameValuePair> nameValue = newArrayList<NameValuePair>();
httpPost.setEntity(newUrlEncodedFormEntity(nameValue));
HttpResponsehttpResponse= httpClient.execute(httpPost);
HttpEntityhttpEntity= httpResponse.getEntity();
is = httpEntity.getContent();
// Get resultBufferedReaderBufR=newBufferedReader(newInputStreamReader(is, "iso-8859-1"), 8);
sb = newStringBuilder();
sb.append(BufR.readLine() + "\n");
Stringline="0";
while ((line = BufR.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(context, "HTTP Connection Error : " + e.toString(), Toast.LENGTH_LONG).show();
returnnull;
}
}
protectedvoidonPostExecute(String result) {
try {
if(result == null)
thrownewException("result is null");
jArray = newJSONArray(result);
JSONObjectjson_data=null;
for (inti=0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
q_id = json_data.getInt("_ID");
q_label = json_data.getString("label");
q_title = json_data.getString("title");
q_description = json_data.getString("description");
q_gotoURL = json_data.getString("gotoURL");
// mList.add();
}
//send message to handler to draw list
drawListHandler.sendEmptyMessage(0);
} catch (Exception e1) {
Toast.makeText(context, e1.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
HandlerdrawListHandler=newHandler(){
/* (non-Javadoc)
* @see android.os.Handler#handleMessage(android.os.Message)
*/@OverridepublicvoidhandleMessage(Message msg) {
setupList();
}
};
}
Solution 2:
Other than setupList()
(assuming that updates some ListView
) and the Toast
, the rest of that should be in doInBackground()
. You want as little code as possible to be on the main application thread.
Post a Comment for "How Do I Make My Connection An Asynctask Connection"