0

我已经阅读了一些关于此的主题,并且我确实已经采取了措施来解决它。我正在使用一个处理程序(这样我就不会在单独的线程上更新 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();
         }
        };
}

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

提前谢谢了

4

1 回答 1

1

你不能这样称呼:

errorMessage.setVisibility(View.GONE);

从后台线程。您也应该通过处理程序来完成。

于 2012-03-29T13:45:42.100 回答