I am trying to load an image in the background as someone works through my app. The logic I wrote is this:
public class ImageLoader extends AsyncTask <Context, Void, Bitmap>{
private String URL;
private int type;
ImageLoader(String Url, int Type)
{
URL = Url;
type = Type;
}
@Override
protected Bitmap doInBackground(Context... arg0) {
AssetManager assetMgr = arg0[0].getAssets();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(assetMgr.open(URL));
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute(result);
if (type == 1)
Inst1 = result;
else if (type == 2)
Inst2 = result;
else if (type == 3)
Inst3 = result;
}
}
However when I try to start a new thread like this:
task = new ImageLoader("Instructions_2.png", 3);
task.execute(gameContext);
But within the program I get the error Looper.prepare must be called, followed by the logic looper.quit()
However I seem to break the program when I add Looper.prepare(), and there is no looper.quit() to call.
Am I creating the task correctly?
EDIT:
This is the error log from when I try to run:
task = new ImageLoader(gameContext, "Instructions_3.png", 3);
I have a switch case statement that I put the image loader declaration outside of. Essentially my code is:
ImageLoader task;
switch(foo)
{
case 0:
...
task = new ImageLoader(gameContext, "Instructions_0.png", 3);
task.execute();
break;
case 1:
...
task = new ImageLoader(gameContext, "Instructions_1.png", 3));
task.execute();
break;
...
}
And the error log (error occurs every time I hit the task = new ImageLoader(...);
line
07-20 14:23:34.276: E/AndroidRuntime(16741): FATAL EXCEPTION: Thread-10
07-20 14:23:34.276: E/AndroidRuntime(16741): java.lang.ExceptionInInitializerError
07-20 14:23:34.276: E/AndroidRuntime(16741): at com.petronicarts.stormthecastle.MainGamePanel.update(MainGamePanel.java:2578)
07-20 14:23:34.276: E/AndroidRuntime(16741): at com.petronicarts.stormthecastle.MainThread.run(MainThread.java:63)
07-20 14:23:34.276: E/AndroidRuntime(16741): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
07-20 14:23:34.276: E/AndroidRuntime(16741): at android.os.Handler.<init>(Handler.java:121)
07-20 14:23:34.276: E/AndroidRuntime(16741): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
07-20 14:23:34.276: E/AndroidRuntime(16741): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
07-20 14:23:34.276: E/AndroidRuntime(16741): at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
07-20 14:23:34.276: E/AndroidRuntime(16741): ... 2 more