• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

AsyncTask and Looper

markolino

Newbie
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>
//variable
private GetData getData;
private int counter;
private List<myType> myList;

@override
protected void onPreExecute() {
super.onPreExecute();
// instruction for GUI thread...like progressDialog...}

@override
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() {
@override
public void run() {
Thread.currentThread().setName("myName");
//... other instruction...
});
t1.start();
try {
t1.join(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(t1.isAlive()){
t1.interrupt();
}
return true;
}

@override
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.


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 !
 
Last edited:
Back
Top Bottom