1

I'm new at Android programming and I'm coding a game but I'm having a problem when trying to add an object to an ArrayList.

I have the class Obstacle:

public class Obstacle extends AndroidApplication {
    private int posX;
    private int posY;

    public Obstacle(int posX, int posY) {
        setPosX(posX);
        setPosY(posY);
    }

    public void setPosX(int objectPosX) {...}

    public int getPosX() {...}

    public void setPosY(int objectPosY) {...}

    public int getPosY() {...}
}

When trying to do this in another class:

obstacles.add(new Obstacle(randomBetween(50, 150), 100));

I get this error:

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

I did some research and I found that probably I'm trying to access Android UI toolkit from outside the UI thread. I don't know how is it possible since apparently I didn't do anything unusual, but...

I learned that I can call the function runOnUiThread in order to access the UI thread, but I dont know exactly how to do it in my code. Is it something like this?

new Thread()
{
    public void run()
    {
        myactivity.this.runOnUiThread(new runnable()
        {
            public void run()
            {
                obstacles.add(new Obstacle(randomBetween(50, 150), 100));
            }
        });
    }
}.start();

I would appreciate any help.

undisp
  • 711
  • 3
  • 11
  • 34
  • Why would u extend AndroidApplication ? And why call runOnUIThread Inside a Thread ? – MeGoodGuy Dec 22 '15 at 22:38
  • I didn't start from scratch, that part was on the template class but I found that the only way I can do super.resume(); or super.pause(); is by extending AndroidApplication. The last piece of code that I have in my question is just that... a question. I took it from [here](http://stackoverflow.com/a/30681078/2699664) and am wondering how to adapt it to my code. – undisp Dec 22 '15 at 22:44
  • 2
    Your Obstacle is not an AndroidApplication. First create your Main wich extends Application, with onCreate, UI, etc.. Then u create an Obstacle object (which doesnt extends anything) and u add a List in you Main class. – MeGoodGuy Dec 22 '15 at 23:03
  • You are right. I was confusing two classes when I answered your first question. Obstacle is really not an AndroidApplication. Removing that solved my problem. One of those errors made by distraction... Thanks, man. – undisp Dec 22 '15 at 23:15

0 Answers0