I have Service and AsyncTask in it, which due to check updatings on the server. It have to be reexecuted if it get some data and also if it doesn't. So my AsyncTask implementation is :
private class DklabExecute extends AsyncTask<Void, String, Void> {
int count;
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
String url = "http://192.168.0.250:81/?identifier=nspid_"+md5(LoginActivity.passUserId)+
",nspc&ncrnd="+Long.toString(currentTimestamp.getTime());
HttpGet rplPost = new HttpGet(url);
protected Void doInBackground(Void... args)
{
Log.i("service count", Integer.toString(count));
count ++;
Log.i("md5 func", md5(LoginActivity.passUserId));
String testData = "http://192.168.0.250/app_dev.php/api/comet/testOrder/";
JSONParser parser = new JSONParser();
DefaultHttpClient testClient = new DefaultHttpClient();
DefaultHttpClient rplClient = new DefaultHttpClient();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("", ""));
HttpGet httpTest = new HttpGet(testData);
httpTest.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
rplPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
try {
httpResponse = rplClient.execute(rplPost);
}
catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Header[] head = httpResponse.getAllHeaders();
Log.i("http Response",httpResponse.toString());
for (Header one:head)
{
Log.i("headers",one.toString());
}
Log.i("response code", Integer.toString(httpResponse.getStatusLine().getStatusCode()));
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);// + "n");
}
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
json = sb.toString();
Log.i("rpl response",json);
if (new JSONArray(json) != null)
jArr = new JSONArray(json);
else
this.cancel(true);
JSONObject toObj = jArr.getJSONObject(0);
JSONObject data = toObj.getJSONObject(KEY_DATA);
if (data.has(KEY_ORDER))
{
for (Order a : ServiceMessages.orderExport)
{
Log.i("service before list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("before dashboard list", a.toString());
}
JSONObject jsonOrder = data.getJSONObject(KEY_ORDER);
Gson gson = new Gson();
Order orderObj= gson.fromJson(jsonOrder.toString(), Order.class);
try
{
for (ListIterator<Order> itr = orderExport.listIterator(); itr.hasNext();)
{
Order a = itr.next();
Log.i("order count", a.toString());
if(orderObj.getOrderid()==a.getOrderid())
{
Log.i("Service","order was changed");
a = orderObj;
someMethod("Your order "+ orderObj.getTitle() + " was changed");
}
else
{
Log.i("Service","order"+ orderObj.getTitle()+" was added");
// DashboardActivityAlt.forPrint.add(0, orderObj);
ServiceMessages.orderExport.add(0,orderObj);
Log.i("status",Integer.toString(orderObj.getProcess_status().getProccessStatusId()));
someMethod("Your order "+ orderObj.getTitle() + " was added");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
for (Order a : ServiceMessages.orderExport)
{
Log.i("service after list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("after dashboard list", a.toString());
}
// intentOrder.putParcelableArrayListExtra("ordersService", orderExport);
sendBroadcast(intentOrder);
Log.i("after parse order",orderObj.toString());
Log.i("orders after updating",DashboardActivityAlt.orders.toString() );
}
else if (data.has(KEY_MESSAGE))
{
JSONObject jsonMessage = data.getJSONObject(KEY_MESSAGE);
Gson gson = new Gson();
Log.i("messages before parse", jsonMessage.toString());
for (Order a: DashboardActivityAlt.forPrint)
{
Log.i("messages count", Integer.toString(a.getCusThread().getMessages().size()));
}
Log.i("disparse message",jsonMessage.toString());
Message message = gson.fromJson(jsonMessage.toString(),Message.class);
Log.i("incomming message",message.toString());
JSONObject jsonThread = jsonMessage.getJSONObject(KEY_THREAD);
Threads thread = gson.fromJson(jsonThread.toString(),Threads.class);
Log.i("incomming thread",thread.toString());
Order orderChanged = new Order();
String orderName = null;
for(Order as : DashboardActivityAlt.forPrint)
{
if (as.getOrderid() == thread.getTreadOrder().getOrderid())
{
orderName = as.getTitle();
orderChanged = as;
Log.i("messages count after", Integer.toString(as.getCusThread().getMessages().size()));
}
}
Log.i("orderchanged",orderChanged.toString());
someMethod("Your order "+ thread.getTreadOrder().getTitle() + " was changed. Message was added");
orderChanged.getCusThread().addMessage(message);
sendBroadcast(intentMessage);
Log.i("messages service", "before sleep");
Log.i("messages service", "after sleep");
}
else
{
this.cancel(true);
}
}
catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
rplClient.getConnectionManager().shutdown();
testClient.getConnectionManager().shutdown();
someMethod("You've lost internet connection. You should try later.");
e2.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void bitmap) {
this.cancel(true);
new DklabExecute().execute();
}
}
If I send some data to the server, it gives me back in JSON format via rpl server. Everything works good, but the problem is when I get some data from the server, AsyncTask reexecuted in onPostExecute() method and it is the same reapeted one or two times data in my list of orders. If I do not reexecute AsyncTask the listening happens only in onStartCommand() method but not permanently. Tell me please how can I implement this in the best manner...
if it's a service there's no reason to use an AsyncTask.
AyncTasks were build to deliver content back on the original thread (normally a UI thread), but services don't have those.
I suggest you use a ScheduledExecutorService instead http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
private ScheduledExecutorService executor;
// call those on startCommand
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(run, 250,3000, TimeUnit.MILLISECONDS);
and have a Runnable doing the work
private Runnable run = new Runnable() {
#Override
public void run() {
// do your network stuff
}
};
and don't forget to cancel everything when your service stops
executor.shutdown();
edit:
or to use a thread in loop you can:
boolean isRunning;
.
// this on your start
Thread t = new Thread(run);
isRunning = true;
t.start();
the runnable
private Runnable run = new Runnable() {
#Override
public void run() {
while(isRunning){
// do your network stuff
}
}
};
and again, don't forget to finish it whenever the service finishes with:
isRunning = false;
Related
The docs say AsyncTask is designed to handle short operations(few seconds maximum) and states that Java classes like FutureTask are better for operations that last long. So I tried to send my location updates to the server using FutureTask but I am getting NetworkOnMainThreadException. I don't want to use AsyncTask because I wanted to keep the http connection open until the updates are cancelled. Here is my code:
SendLocation updates = new SendLocation(idt, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
FutureTask ft = new FutureTask<String>(updates);
boolean b = ft.cancel(false);
ft.run();
class SendLocation implements Callable<String> {
String t, la, lo;
public SendLocation(String a, String b, String c){
this.t = a;
this.la = b;
this.lo = c;
}
public String call() {
sendUpdates(token, la, lo);
return "Task Done";
}
public void sendUpdates(String a, String b, String c){
HttpURLConnection urlConn = null;
try {
try {
URL url;
//HttpURLConnection urlConn;
url = new URL(remote + "driver.php");
urlConn = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", "true");
//urlConn.setDoInput(true); //this is for get request
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.connect();
try {
//Create JSONObject here
JSONObject json = new JSONObject();
json.put("drt", a);
json.put("drlat", b);
json.put("drlon", c);
String postData = json.toString();
// Send POST output.
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
os.flush();
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg = "";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line;
}
Log.i("msg=", "" + msg);
} catch (JSONException jsonex) {
jsonex.printStackTrace();
Log.e("jsnExce", jsonex.toString());
}
} catch (MalformedURLException muex) {
// TODO Auto-generated catch block
muex.printStackTrace();
} catch (IOException ioex) {
ioex.printStackTrace();
try { //if there is IOException clean the connection and clear it for reuse(works if the stream is not too long)
int respCode = urlConn.getResponseCode();
InputStream es = urlConn.getErrorStream();
byte[] buffer = null;
int ret = 0;
// read the response body
while ((ret = es.read(buffer)) > 0) {
Log.e("streamingError", String.valueOf(respCode) + String.valueOf(ret));
}
// close the errorstream
es.close();
} catch(IOException ex) {
// deal with the exception
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ERROR", "There is error in this code " + String.valueOf(e));
}
}
}
Doesn't it get executed in a worker thread? If the answer is no why does the docs say that it is an alternative to AsyncTask?
Your code must not be in the void run() method. This is where the asynchronous code is ran.
I'm really bad at googling things I want so I decided to ask here. My question is is it possible to show a progress bar while fetching the data from the database? I'm using the typical code when fetching data(Pass value to php and the php will do the query and pass it again to android)
Edit(I have tried adding proggressdialog but the problem now is the loaded data will appear first before the progress dialog here's my AsyncTask code)
public class getClass extends AsyncTask<String, Void, String> {
public getClass()
{
pDialog = new ProgressDialog(getActivity());
}
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}
Have you tried using an AsyncTask?
You can show your progress bar on the preExecute method and then hide it on postExecute. You can do your querying inside the doInBackground method.
In addition to what #torque203 pointed, I would suggest you to check
http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)
this method was created for that purpose, showing progress to the user.
From developers docs:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
#Override
protected void onPreExecute() {
//show progress bar here
}
protected Long doInBackground(URL... urls) {
//Pass value to PHP here
//get values from your PHP
}
protected void onPostExecute(Long result) {
//Here you are ready with your PHP value. Dismiss progress bar here.
}
}
public void onPreExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void doInBackground() {
//do your JSON Coding
}
public void onPostExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
public class getClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}
I have a method that need to update its status periodically to the server.
I am using AsyncTask to run the HTTP call in background.
PROBLEM: In onPostExecute method upon checking AsyncTask.getStatus, It show the previous task still running which is causing the error.
ERROR: java.lang.IllegalStateException: Cannot execute task: the task is already running.
DIFFERENT STRATEGIES USED TO SOLVE THE PROBLEM BUT NONE IS WORKING
1. Before Relaunching AsyncTask, checked the status, it is showing the thread is RUNNING.
2. Called the AsyncTask.cancel(true), immediately before calling the AsyncTask.execute if it is still running. It turns out AsyncTask still RUNNING and taking more than 3 mins to get cancel.
NOTE: I have checked many similar questions here, but haven't found helpful.
I would really appredicae if any one of you guys give me an example to solve this issue, Thanks a Million in advance......
public class MainActivity extends Activity implements AsyncResponse{
ConnectServer asyncTask =new ConnectServer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
//Start updating server using below method
loop();
}
public void processFinish(String output){
//this you will received result fired from async class of onPostExecute(result) method.
//Log.v(TAG, output);
if(output != null){
//not using this at this point
}
}
//Method that will call Async method to reach server
public void loop(){
TextView b = (TextView) findViewById(R.id.mField);
String str;
try {
str = asyncTask.execute(true).get();
b.setText(str);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// START SERVER CONNECTION
class ConnectServer extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
public int i = 0;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://192.168.0.21:8080");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("GPSApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
TextView mField = (TextView) findViewById(R.id.mField);
mField.setText(result+i);
try {
Thread.sleep(10000);
//asyncTask =new ConnectServer();
i++;
String str = asyncTask.execute(true).get();
mField.setText(str+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onPreExecute() {}
}
}
Call getStatus() to get the status of AsyncTask. If the status is AsyncTask.Status.RUNNING, cancel it.
I want to upload files one by one just like queue. In brief suppose there are 10 files and I want to upload all files and it should be checking for network connectivity is available or not, if not then those file should be into the queue and will try to upload later. It will keep on trying till any single file in left queue. Please help me out, How can I achieve this in android.
This is the sample code that I have tried so far
final Thread thread = new Thread(){
public void run() {
try {
while(true){
ThisCaching ic = new ThisCaching(getApplicationContext());
fileToUpload = ic.getDataFromCache("audiofiles", "SELECT * FROM audiofiles WHERE STATUS = '2' OR STATUS = '3' ORDER BY rowid DESC");
if(fileToUpload != null)
{
for (int i=0; i<fileToUpload.size(); i++) {
try {
System.out.println("Current position while uploading ::> " + i);
Thread.sleep(1000);
ConstantData.selectedFile = fileToUpload.get(i).toString();
ConstantData.position = i;
if(checkConnectivity()){
new Uploading().execute();
myApplication.getHttpClient().getConnectionManager().closeExpiredConnections();
}else{
String[] status = {"STATUS"};
String[] val = {"2"};
try {
SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB();
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (Exception e) {
return;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
};
String line = null;
HttpClient httpClient = null;
HttpContext localContext = null;
HttpPost httpPost = null;
MultipartEntity entity = null;
HttpResponse response = null;
HttpEntity httpEntity =null;
SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB();
try {
String strArray[]={"http://myurl.com","filename",ConstantData.selectedFile,"activityType",ConstantData.activityType,"patientId",ConstantData.patientId,"caseId",ConstantData.caseId,"doctorId",ConstantData.doctorId,"clinicCode",ConstantData.clinicCode,"documentType",ConstantData.documentType,"templateId",ConstantData.templateId};
httpClient = new DefaultHttpClient();
//httpClient.getConnectionManager().r
localContext = new BasicHttpContext();
httpPost = new HttpPost(strArray[0]);
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(ConstantData.selectedFile);
String type = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")+1);
if(strArray.length>1)
{
for(int i=1;i<strArray.length;i=i+2)
{
if(strArray[i]!=null){
if(!strArray[i].equalsIgnoreCase("")){
// System.out.println("i) : "+i +" i+1) : "+(i+1));
Log.i(strArray[i], "::" + strArray[i+1]);
if(strArray[i].equalsIgnoreCase("filename")){
entity.addPart("filename", new FileBody(file,"audio/"+type));
}else{
entity.addPart(strArray[i], new StringBody(strArray[i+1]));
}
}
}
}
}
httpPost.setEntity(entity);
response = httpClient.execute(httpPost,localContext);// i m getting error at this line
System.out.println("Response code is ::> " +response.getStatusLine().getStatusCode());
code = response.getStatusLine().getStatusCode();
httpEntity = response.getEntity();
line = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (IOException e) {
code=100;
e.printStackTrace();
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
} catch (Exception e) {
code=100;
e.printStackTrace();
ConstantData.uploaded = false;
String[] status = {"STATUS"};
String[] val = {"3"};
try {
new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
} catch (Exception e1) {
e1.printStackTrace();
}
}finally{
//
try {
// System.out.println("&&&& while realeasing connection");
//// if(httpClient != null){
//// httpClient.getConnectionManager().releaseConnection((ManagedClientConnection) httpClient.getConnectionManager(), -1, TimeUnit.MINUTES);
//// }
// if(httpPost.getEntity().getContent() != null){
// InputStream content = httpPost.getEntity().getContent();
// content.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
}
return line;
`
From what I see, do you use plain Threads (cant see the edit, yet). Since Java 1.5 there's an package for such things as queues and mutlithreading, that makes live much easier.
For your purpose of a queue, you can create a single threaded executor with Executors.newSingleThreadExecutor(). You get a Threadpool with just one thread that executes each task you submit(Runnable) in the order you submitted them. Java garanties, that the Executor always has one thread working on the queue (Java recreates the Thread automatically if it dies)
Each task you submit implements a Runnable. So, to implement the three retries you described, you just need a class that implements the Runnable interface, that counts the retries and - if the upload was not succesful - it increments the counter and resubmits itself.
Here's the Guide, Tutorial and Reference to Executors and ExecutorService.
I understand the point of the android.os.NetworkOnMainThreadException that targets HoneyComb devices but the following code throws the same exception:
class MakeRequest extends AsyncTask<String,Integer,Void>
{
#Override
protected Void doInBackground(String... params) {
DefaultHttpClient cli = new DefaultHttpClient();
try {
String url = params[0].replace(" ", "%20");
HttpResponse resp = cli.execute(new HttpGet(url));
BufferedReader read = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
String tmp = "",rezultat = "";
setResult("");
while ((tmp = read.readLine()) != null)
{
rezultat = rezultat + tmp;
}
setResult(rezultat);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
setResult("");
return null;
}
return null;
}
//Sample call
HttpRequester cc = new HttpRequester();
MakeRequest test = cc.new MakeRequest();
test.doInBackground(url);
try this.
new MakeRequest().execute(url);