Android-当我尝试向文本框显示内容时崩溃

时间:2015-08-26 04:23:27

标签: java android multithreading crash

public void onClick_Start(View v) {
    //stores the weight value entered by user
    final EditText sWeight = (EditText) findViewById(R.id.editTextWeight);
    Log.v("EditText", sWeight.getText().toString());
    String w = sWeight.getText().toString();
    Weight_double = Double.parseDouble(w);
    //sets to true because start was clicked
    start = true;
    counter = 0;
    final int x1 = (int)lowX;
    final int y1 = (int)lowY;
    final int z1 = (int)lowZ;

    new Thread(new Runnable() {
        public void run() {
            int x2;
            int y2;
            int z2;
            int x3 = 10000;

           while(start)
           {
               x2 = (int)lowX;
               y2 = (int)lowY;
               z2 = (int)lowZ;
               if(x2 != x3)
               {
                   if(x2 == x1&& y2 ==y1 && z2 == z1) {
                       counter++;
                       tv.setText(counter);
                   }
               }
               x3 = x2;
           }
        }
    }).start();
}

-X,Y和Z表示加速度计的值 - 该方法应该从点击按钮开始 - 计数器变量用于计算特定的移动   - 我认为这可能是一个线程问题,但我不确定

1 个答案:

答案 0 :(得分:0)

从不同的线程更新UI的另一种方法是使用处理程序来访问主线程。

        final String counterText = String.valueOf(counter); 
        //Variable accessed from inner class must be declared final 

        Handler mHandler = new Handler(YourActivity.this.getMainLooper());

               Runnable mRunnable = new Runnable() {
                    @Override
                    public void run() {
                       /* Update UI Elements here */
                       tv.setText(counterText);
                    }
               };

         mHandler.post(mRunnable);