1. Are you ready for the Galaxy S20? Here is everything we know so far!

AsyncTask and Looper

Discussion in 'Android Development' started by markolino, Mar 25, 2020.

  1. markolino

    markolino Lurker
    Thread Starter

    Hello, i'm Mark and i'm writing from Italy.
    I have a problem with my application, because at Runtime i have an Exception.
    The structure of the project is this:
    MainActivity.java->workActivity.java that contains also myClass1 that extends AsyncTask .
    In the project i have another class called GetData that contains variable and other methods for Database.

    So if i click a button in workActivity then i generate:

    myClass1 asyncT = new myClass1 ();
    asyncT .execute("");

    So the code jump in myClass1 where i have:

    public class taskRicercaRicambio extends AsyncTask<String, String, Boolean>
    private GetData getData;
    private int counter;
    private List<myType> myList;

    protected void onPreExecute() {
    // instruction for GUI thread...like progressDialog...}

    protected Boolean doInBackground(String... strings) {
    int counter = 0;
    myList = new LinkedList<myType>();
    getData = new GetData(); // THIS LINE CAUSE EXCEPTION
    Thread t1 = new Thread(new Runnable() {
    public void run() {
    //... other instruction...
    try {
    } catch (InterruptedException e) {
    return true;

    protected void onPostExecute(Boolean s) {
    //..do something with UI thread.......}

    Why this line getData = new GetData(); give me an exception ?
    If i put it in onPreExecute() method all work perfectly. No error.
    But if not, i want to understand why the debugger show me :
    java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #2,5,main] that has not called Looper.prepare()

    Why i cannot instatiate an object of GetData Class in the background method ?
    Why is asking me for a looper ? I haven't any GUI component to update.

    I found the bug.
    In the doInBackground method i create a GetData object, but inside the constructor of GetData i create another object of type myClassBug and this class extends AppCompatActivity.
    As soon as i delete the extends, all works ok.

    I couldn't understand why he asked me a Looper if I don't have to update the UI... I suppose it's for this reason.
    Hope this helps other user !


    #1 markolino, Mar 25, 2020
    Last edited: Mar 26, 2020 at 9:40 AM

Share This Page