-1

[Sorry for bad english]

Hello everyone, Here im trying to do something inside an async task and the app crashes when running it. When it reaches the return line the app dies.

Here is my code

private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params){
        velocidadMedia = (distanciaTotal)/(tiempoTotal);
        track = new TrackItem(  sdf.format(new Date()),
                Double.toString((int) distanciaTotal),
                Double.toString((int) tiempoTotal),
                Double.toString((int) velocidadMedia));
        String IDFromServer = databaseReference.push().getKey();
        track.setKey(IDFromServer);
        databaseReference.child(IDFromServer).setValue(track);
        Toast.makeText(getContext(),"Track Creado!", Toast.LENGTH_LONG).show();
        return null;
    }

}

It might be useful to know this async task is inside a fragment.

Android studio is giving me this in the error log:

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I tried using the onPostExecute method with no instructions in it but did not solve the issue.

Raja Jawahar
  • 6,742
  • 9
  • 45
  • 56

3 Answers3

4

You cannot call the Toast.makeText() from a background thread. You can only call from the UI/Main thread. Move the Toast.makeText() call to onPostExecute().

Nikunj
  • 3,937
  • 19
  • 33
Jayson Chacko
  • 2,388
  • 1
  • 11
  • 16
1

from: Can't create handler inside thread that has not called Looper.prepare()

You're calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example.

Look up Communicating with the UI Thread in the documentation. In a nutshell:

// Set this up in the UI thread.

mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message message) {
        // This is where you do your work in the UI thread.
        // Your worker tells you in the message what to do.
    }
};

void workerThread() {
    // And this is how you call it from the worker thread:
    Message message = mHandler.obtainMessage(command, parameter);
    message.sendToTarget();
}

Other options:

You could use an AsyncTask, that works well for most things running in the background. It has hooks that you can call to indicate the progress, and when it's done.

You could also use Activity.runOnUiThread().

Rafael Lima
  • 3,079
  • 3
  • 41
  • 105
0

You cannot display the toast message in doInBackground()

Toast.makeText(getContext(),"Track Creado!", Toast.LENGTH_LONG).show();
Kaushik
  • 6,150
  • 5
  • 39
  • 54
kundan kamal
  • 674
  • 7
  • 16