Android应用上的ViewRoot $ CalledFromWrongThreadException

时间:2012-03-29 13:44:28

标签: android multithreading viewroot

我已经阅读了一些相关的线索,我已经采取措施解决它。 我正在使用一个处理程序(这样我就不会在单独的线程上更新UI)到目前为止我无法理解为什么这仍然会发生。

public class MyApp extends Activity implements OnClickListener, Runnable {

    private ViewSwitcher switcher;
    private static final int REFRESH_SCREEN = 1;
    private boolean isValid = false;
    private ProgressDialog dialog;
    private TextView errorMessage;      

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(this);

        TextView errorMessage = (TextView)findViewById(R.id.txtErrorMessage);
        errorMessage.setVisibility(View.GONE);

        switcher = (ViewSwitcher) findViewById(R.id.profileSwitcher);
    }

    public void onClick(View v)  
    {
        isValid = false;
        dialog = ProgressDialog.show(ConcentraApp.this, "", "Loading. Please wait...", true);

        Thread thread = new Thread(this);
        thread.start();
    }

    public void run() {
        String username = ((TextView)findViewById(R.id.txtUsername)).getText().toString();
        String password = ((TextView)findViewById(R.id.txtPassword)).getText().toString();
        errorMessage = (TextView)findViewById(R.id.txtErrorMessage);
        errorMessage.setVisibility(View.GONE);

        /* ... contact web service and get response ..*/

        try {
            /* get result from web service */
            isValid = Boolean.parseBoolean(result);
            if(isValid)
            {
                handler.sendEmptyMessage(1);                
            }
            else
            {
                handler.sendEmptyMessage(0);    
            }

        } catch (Exception e) {
            handler.sendEmptyMessage(2);
            isValid = false;        
        }                                             
    }

    private Handler handler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
             if(msg.what == 1)
             {
                 errorMessage.setVisibility(View.VISIBLE);
                 errorMessage.setText("Correct login");
                 switcher.showNext();
             }
             else if(msg.what == 0)
             {
                 errorMessage.setVisibility(View.VISIBLE);
                 errorMessage.setText("Invalid login");
             }
             else
             {
                 errorMessage.setVisibility(View.VISIBLE);
                 errorMessage.setText("Internet error");
             }
             dialog.dismiss();
         }
        };
}

我对此非常陌生,所以如果我遗漏了一些明显的东西,我也不会感到惊讶。 没有线程就可以正常工作,但是进程对话框没有显示。

非常感谢提前

1 个答案:

答案 0 :(得分:1)

你不能这称呼:

errorMessage.setVisibility(View.GONE);

来自后台线程。你也应该通过处理程序来做。