Kelton_O Kelton_O - 2 months ago 18
Android Question

Download task throws exception with no internet

I have an app that downloads the current unix timestamp from the internet. The code for the download task is as follows.

public class DownloadTask extends AsyncTask<String, Void, String> {


@Override
protected String doInBackground(String... urls) {

String result = "";
URL url;
HttpURLConnection urlConnection = null;

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 (Exception e) {

e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();

}

return null;
}


I run this code in onCreate

DownloadTask task = new DownloadTask();
String result = null;

try {

result = task.execute("http://www.currenttimestamp.com/").get();

Pattern p = Pattern.compile("current_time = (.*?);");
Matcher m = p.matcher(result);
m.find();
String unixTime = (m.group(1));
timeStamp = Integer.parseInt(unixTime);
endTimeMaths = endTime/1000;

} catch (InterruptedException e) {

e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();

} catch (ExecutionException e) {

e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();

}

timeDelta = timeStamp-endTimeMaths;

Log.i("TimeDelta", timeDelta+"");


//If dem boys cheatin
if (timeDelta < 1){
Toast.makeText(SplashActivity.this, "You cheatin boi?", Toast.LENGTH_SHORT).show();
reward=false;
} else if (timeDelta >= 300){
reward = true;
Toast.makeText(SplashActivity.this, "Here is your reward for being gone", Toast.LENGTH_SHORT).show();
}

}


The Exception is as follows

09-04 21:26:42.853 8459-8493/com.firefluxentertainment.retroclicker E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.firefluxentertainment.retroclicker, PID: 8459
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at com.firefluxentertainment.retroclicker.SplashActivity$DownloadTask.doInBackground(SplashActivity.java:155)
at com.firefluxentertainment.retroclicker.SplashActivity$DownloadTask.doInBackground(SplashActivity.java:119)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761)


Since all the code is in try catch braces I have no idea why it would be crashing. Any help is very much appreciated!

Answer

This is because you are trying to show toast in a non-UI thread. There are multiple solutions to your problem :

  • Create a handler in the Activity and pass it along to DownloadTask. Simply send a message in Handler and show the toast.

  • Another solution is to send the context in DownloadTask and show the toast as

     context.runOnUIThread(new Runnable() {
        public void run(){
           Toast.showToast("your message here")
        }
     )
    
  • You can send the result of your task in onPostExecute() and show Toast there.

Comments