How Android Async Task Works with UrlConnection - android

I am new with the android. I am developing an app that will load content from target url in file. If the url didn't work, it will contact our server to request the correct url. If still fail, then it will ask the url from user input dialog. And it will try to initialize again. I have code like this:
if (initialize(target)!=true) {
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("sns", getSerial(PREF_NAME));
jsonParam.put("code", pwd);
} catch (JSONException e) {
e.printStackTrace();
}
target = getContent(samURL + "/sam_ip", jsonParam);
if (initialize(target)!=true) {
askIpUserDialog();
}
}
and the initialize() as follow
private boolean initialize(String url) {
Boolean success = false;
if ((!url.trim().startsWith("http://")) && (!url.trim().startsWith("https://"))) {
url = "http://" + url;
}
if (url.endsWith("/")) {
url = url.substring(0,url.length()-1);
}
String sUrl = url + "/android_view";
URL pUrl;
HttpURLConnection urlConn = null;
try {
DataOutputStream printout;
DataInputStream input;
pUrl = new URL (sUrl);
urlConn = (HttpURLConnection) pUrl.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("snc", serialClient);
jsonParam.put("code", pwd);
printout = new DataOutputStream(urlConn.getOutputStream());
String str = jsonParam.toString();
byte[] data = str.getBytes("UTF-8");
printout.write(data);
printout.flush();
printout.close ();
int HttpResult = urlConn.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
success = true;
WebView view=(WebView) this.findViewById(R.id.webView);
view.setWebChromeClient(new WebChromeClient());
view.setWebViewClient(new WebViewClient());
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(sUrl);
}else{
success = false;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(urlConn!=null)
urlConn.disconnect();
}
return success;
}
I just know that in android, url connection should run in separate thread. That's why I got the following error:
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
My question is, how do I use AsyncTask to avoid the error?
I saw there is doInBackground() which I can put the initialize() function there.
I saw also there is onPostExecute() event which I can check the result from the doInBackground(), but I don't understand yet how do I retrieve the return of initialize() which placed inside doInBackground()?
Bonus question, later I'd like to place all this job inside an intentservice. Do I need to stil use the asynctask? Does intentservice itself is an asynctask?

you can try some thing like this and also u can use a different thread
final Handler h = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
final File file = new File(path);
Log.i("path",path);
downloadFile(url[j], file);
h.post(new Runnable(){
#Override
public void run() {
txt.setText(""+jp);
jp++;
}
});
}
}
};
new Thread(r).start();
}
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
Log.i("len","" + contentLength);
Log.i("url1","Streaming from "+url+ "....");
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
Log.v("FileError" , e.toString());
return; // swallow a 404
} catch (IOException e) {
Log.v("FileError" , e.toString());
return; // swallow a 404
}
catch (Exception e) {
Log.v("FileError" , e.toString());
return; // swallow a 404
}
}
and also you cant access ui elements on different thread you have to use handler or run on ui thread.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
this.pd = ProgressDialog.show(this, "Loading..", "Please Wait...", true, false);
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected Void doInBackground(String... args) {
//do your stuff here }
}
}

Network traffic (and all other logic which takes some time to process) should always be handled by a background thread and never on the Main thread.
Use an ASyncTask to execute the logic.
private class YourTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// perform your network logic here
return "YourResult";
}
#Override
protected void onPostExecute(String result) {
// Update your screen with the results.
}
}
Call the ASyncTask in your code:
new YourTask().execute("");

Related

Android JSON Live updates

I can't figure out how to get live updates in android from a json api that updates every 2-3 seconds. I've managed to download the JSON code and then create some arrays and log them, but I the values from the json api change every 2-3 seconds and I have no idea how to redownload the JSON. Thanks in advance for your help!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try{
result = task.execute("thelinkIuse").get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
while (true) {
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (IOException e) {
e.printStackTrace();
return "Failed";
}
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray arr = new JSONArray(result);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
symbols.add(jsonPart.getString("symbol"));
bids.add(jsonPart.getString("bid"));
asks.add(jsonPart.getString("ask"));
}
Log.i("Symbols", String.valueOf(symbols));
Log.i("Bids", String.valueOf(bids));
Log.i("Asks", String.valueOf(asks));
} catch (JSONException e) {
e.printStackTrace();
Log.i("failed", "failed");
}
}
}
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try{
result =new DownloadTask().execute("thelinkIuse").get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
},0,5000);
This will call the asynctask every 5 seconds, thus fetching the updated JSON string
Im thinking you need some kind of polling mechanism. Look at Firebase Notifications because what you could do is have your server side code post an http request to the firebase server and that will trigger a server side push notification to your app in which you will have a receiver which will trigger the retrieval process
If you're absolutely sure about the updates occur every 2-3 seconds then you can periodically call the AsyncTask execute method. This is not considered a very good practice but can get your work done. Something on these lines:
private Timer autoRefresh;
autoRefresh=new Timer();
autoRefresh.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
String result = null;
try{
result = task.execute("thelinkIuse").get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
});
}
}, 0, your_time_in_miliseconds);

How to use runOnUiThread in a class?

My code is designed to read a .txt file from a URL, and then display the text inside my textview. the problem is, I am using this code in a class. and getting this error- "cannot resolve method runOnUiThread". How do I fix this??
public class mydownloaderclass {
// this method is called from MainActivity
public static void checkForUpdates(Context context) {
new Thread() {
#Override
public void run() {
String path ="http://host.com/info.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView text = (TextView) findViewById(R.id.TextView1);
text.setText(bo.toString());
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
I tried using asynctask
public class readtextfile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
try {
URL url = new URL("https://www.dropbox.com/myfile.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = null;
while ((line = in.readLine()) != null) {
//get lines
result += line;
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
Create a Handler instead to execute statements on Main Thread like this
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
//Write your RUN on UI Runnable code here
TextView text = (TextView) findViewById(R.id.TextView1);
text.setText(bo.toString());
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
} });
Try passing a view context. It can be the activity context where the text view is defined.
The runOnUiThread runs on the main looper so it required a UI context.
For that You can define a member field in the class where the Thread is defined and set it in the constructor. Or if the thread is in the activity itself. then simply set the context field in OnCreate and use it in the thread.
Hope this helps. :)
Let me know if this fixes it.
I would suggest you to use AsyncTask, android makes this class specially for doing some task on a working thread(doInBackgroung()) and then update UI in onPostExecute() method.

d How can I use progress bar while fetching data from database?

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
{
}
}
}

Why can't I return a string from an AsyncTask?

I am trying to read an online txt file from my Dropbox and put its content into a string with an Asynctask but I can't manage to return my string.
My Code:
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String path ="https://dl.dropboxusercontent.com/u/29289946/PCGAMEDONWLOADER/Slots/All%20Games/Rows_available/link2.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
String album = bo.toString();
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return album;
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.loadingtext);
txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
Now eclipse underlines "album" next to return, so I can't use it in further operations.
Thanks for your help.
Why you run the UI thread to assign the data to a string...you can use it in side your thread.
Simply do in your doInBackground method()like:
bo.write(buffer); // Write Into Buffer.
String album = bo.toString();
return album;
And here your main problem is you define your String variable locally inside runInMainThread() method. Then how you access it out of its surrounding area. If you don't want to change your program then just define the String globally like:
public String doInBackGround()String...params){
String album = "";
.....
....
And asign the value anywhere... like album=bo.toString(); and return ....
You initialized album in this function:
runOnUiThread(new Runnable() {
#Override
public void run() {
String album = bo.toString();
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
So it is only available in this scope. You could have seen this by checking what error Eclipse actually shows you.
It's because you declare your album String in your runOnUiThread, so it will not be known outside of it. Try to declare it in your onPostExecute like follow:
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String path ="https://dl.dropboxusercontent.com/u/29289946/PCGAMEDONWLOADER/Slots/All%20Games/Rows_available/link2.txt";
URL u = null;
//Declare it here as final
final String album=null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
album = bo.toString();
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return album;
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.loadingtext);
txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}

Android Thread / AsyncTask, ExceptionInInitializerError and RuntimeException on "runOnUiThread"

I need your help with two Errors I´m getting on
Creating a Thread, where I`m creating a file
After the file stuff, a AsyncTask getting executed to send the file to a server (multipart/form-data)
Thats how the first part looks like:
public void startResultTransfer(final int timestamp, final int duration, final String correction, final float textSize, final int age, final int switch_count, final Activity activity){
synchronized(DataTransmission.class){
new Thread() {
public void run() {
FileWriter fw = null;
//1.Check if file exists
File file = new File(FILE_PATH);
if(!file.exists()){
//File does not exists, when we have to generate the head-line
try {
fw = new FileWriter(FILE_PATH);
fw.append("timestamp\tduration\tcorrection\ttext_size\tage\tswitch_count"); //Headline
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//2. Write Result
try {
if(fw == null)
fw = new FileWriter(FILE_PATH);
fw.append("\n"+String.valueOf(timestamp)+"\t");
fw.append(""+String.valueOf(duration)+"\t");
fw.append(""+correction+"\t");
fw.append(""+String.valueOf(textSize)+"\t");
fw.append(""+String.valueOf(age)+"\t");
fw.append(""+String.valueOf(switch_count)+"\t");
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//3. File Transfer
if(isOnline(activity))
transferFileToServer(activity);
}
}.start();
}
}
The function "transferFileToServer" looks like this:
public synchronized void transferFileToServer(Activity activity){
String id = id(activity);
File file = new File(FILE_PATH);
if(id != null && file.exists()){
final String url = URL+id;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
TransmissionTask task = new TransmissionTask();
task.execute(url);
}
});
}
}
Now, I`m getting an "ExceptionInInitializerError" with the explanatory message
Caused by java.lang.RuntimeException Can't create handler inside thread that has not called Looper.prepare()"
at the line "activity.runOnUiThread".
In the first function I need to call "transferFileToServer" after some pre settings. But the function should be called unattached from the first function, too.
Should I maybe implement a MessageHandler for executing the AsyncTask at the end of Thread?
http://developer.android.com/reference/android/os/Looper.html
Or should I maybe Change the "AsyncTask" in the "transferFileToServer" function to a Thread, because I don`t do any UI operations?
Edit: The method started from the Async-Task
class TransmissionTask extends AsyncTask<String, Void, String> {
public TransmissionTask() {
}
#Override
protected String doInBackground(String... params) {
synchronized(DataTransmission.class){
try {
HttpURLConnection urlConn;
java.net.URL mUrl = new java.net.URL(params[0]);
urlConn = (HttpURLConnection) mUrl.openConnection();
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
String boundary = "---------------------------14737809831466499882746641449";
String contentType = "multipart/form-data; boundary="+boundary;
urlConn.addRequestProperty("Content-Type", contentType);
DataOutputStream request = new DataOutputStream(urlConn.getOutputStream());
request.writeBytes("\r\n--"+boundary+"\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\""+FILE_NAME+"\"\r\n");
request.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
File myFile = new File(FILE_PATH);
int size = (int) myFile.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(myFile));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.write(bytes);
request.writeBytes("\r\n--"+boundary+"--\r\n");
request.flush();
request.close();
InputStream responseStream = new BufferedInputStream(urlConn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null)
{
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
responseStream.close();
urlConn.disconnect();
return response;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
if(result.toLowerCase().contains("erfolgreich")){
//If successfull delete File
File file = new File(FILE_PATH);
file.delete();
}
}
}
}
Remove runOnUiThread:
public synchronized void transferFileToServer(Activity activity){
String id = id(activity);
File file = new File(FILE_PATH);
if(id != null && file.exists()){
final String url = URL+id;
TransmissionTask task = new TransmissionTask();
task.execute(url);
}
}
The main idea of AsyncTask to run background operation/logic without Threads or Handlers.
You don't need wrap AsyncTask with additional Thread and bind with UI Thread what you did
From your code:
public void startResultTransfer(/* ... */){
....
new Thread() {
.....
transferFileToServer(/* ... */); // its wrong!!!
....
}.start()
}
transferFileToServer starts your AsyncTask and you run it not in main UI Thread but in single Thread.
This is a problem.
Start your AsyncTask from Activity.

Categories

Resources