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

给你一囗甜甜゛ 提交于 2020-01-06 05:07:11

问题


I am using simple thread to execute the httpGet to server when a button is clicked, but I get this after execution.

Button b_back = (Button) findViewById(R.id.bback);
b_back.setOnClickListener(this);
Button b_sign_up = (Button) findViewById(R.id.signup_button);
b_sign_up.setOnClickListener(this);

@Override
public void onClick(View arg0) 
{
    // TODO Auto-generated method stub
    switch (arg0.getId()) 
    {
        case R.id.bback:
            Intent i = new Intent(this, MainSwitch.class);
            finish();
            startActivity(i);
            break;

            // More buttons go here (if any) ...

        case R.id.signup_button:
            if(username.getText().toString().equalsIgnoreCase("") ||
               password.getText().toString().equalsIgnoreCase("") ||
               email.getText().toString().equalsIgnoreCase(""))
            {
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setMessage("Please fill in all the gaps!");
                dialog.show();
            }
            else
            {
                //****** Call method that sends the information to server.
                Thread background = new Thread (new Runnable() 
                {
                    public void run()
                    {
                        // Call the time consuming method
                        handler.sendEmptyMessage(0);
                    }
                });
                background.start();
            }
    }
}

private Handler handler = new Handler() 
{
    @Override
    public void handleMessage(Message msg) 
    {
        Toast.makeText(getApplicationContext(),
                       "Done thread",
           Toast.LENGTH_SHORT).show();

    }
};

回答1:


The errorline you get:

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

is typically linked to problems where you try to do stuff to UI-elements on a non-UI-thread.

I suppose that by stating // Call the time consuming method you have left out some of your code. The fact that this time consuming method runs on a regulare Thread means it cannot interact with UI-elements.

If you post more code (and also which specify the line where the error occurs) we can probably provide more info on how to solve it.



来源:https://stackoverflow.com/questions/6880662/java-lang-runtimeexception-cant-create-handler-inside-thread-that-has-not-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!