Reputation: 27
im trying to use the following code in asynce task cause i want to show asynce task to the user for some reasons.
but this asynce task not working at all...
AsyncTask task = new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://persiancoder.tk/appservice/service.php");
//conn.setConnectTimeout(7000);
//YOUR PHP SCRIPT ADDRESS
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
//parse json data
try {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
String n = "";
String a = "";
String j = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
if (i == 0) {
int j1 = json.getInt("id");
if (j1 == 1) {
} else if (j1 == 0) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(Main.this);
dlgAlert.setMessage("برنامه توسط تيم از دسترس خارج شده! لطفا بعدا امتحان کنيد");
dlgAlert.setTitle("Server Out!");
dlgAlert.setCancelable(false);
dlgAlert.setNegativeButton("باشه", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
});
dlgAlert.show();
}
}
}
} catch (Exception e) {
Log.e("log_tag", "Error Parsing Data " + e.toString());
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(Main.this);
dlgAlert.setMessage("مشکلي نامعلوم پيش آمده!اينترنت خود را چک کنيد");
dlgAlert.setTitle("Unknown Problem!");
dlgAlert.setCancelable(false);
dlgAlert.setNegativeButton("باشه", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
});
}
return null;
}
};
task.execute(/* optional params */);
i have tried ways but not working.
whats the problem?
Upvotes: 0
Views: 62
Reputation: 3389
I can't post this kind of answer in a comment or I would, this is AsyncTask 101. In VERY simple terms:
doInBackground
is designed to perform background operations
onPostExecute
is designed to utilize the background operation results on the main UI thread
onPreExecute
is designed to handle any UI requirements prior to running in the background thread
onProgressUpdate
is designed to perform quick updates to the UI based on the progress of doInBackground
So if you have an AsyncTask like yours, and you want to show a Toast based on the operations of the network request, do something like this
new NetworkTask().execute("http://persiancoder.tk/appservice/service.php");
Where your NetworkTask class looks like
public class NetworkTask extends AsyncTask<String, Void, String[]>{
@Override
public String[] doInBackground(String... urls){
String url = urls[0];
// Do the code that you already have BUT whenever you are building/showing your
// alert dialog, instead of doing that send a result back as an array with your
// title and message and show the alert dialog there
// i.e.
...
} else if (j1 == 0)
return new String[]{"Server Out!", "برنامه توسط تيم از دسترس خارج شده! لطفا بعدا امتحان کنيد"};
...
return null; // return null on success/no error
}
@Override
public void onPostExecute(String[] results){
if(results == null)
return;
else{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(Main.this);
dlgAlert.setTitle(results[0])
.setMessage(results[1]);
.setCancelable(false);
.setNegativeButton("باشه", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
});
dlgAlert.show();
}
}
}
This, by all means, is not the best way of doing things, but it works. I would recommend looking into Volley
for networking, but this should at least give you a basic idea of how AsyncTasks work.
Upvotes: 1