【问题标题】:Android- Crashes when i try to display something to the textboxAndroid-当我尝试向文本框显示内容时崩溃
【发布时间】:2015-08-26 04:23:26
【问题描述】:
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 指加速度计的值 - 该方法应该在单击按钮时开始 - 计数器变量用于计算特定移动 - 我认为这可能是线程问题,但我不确定

【问题讨论】:

  • 你的崩溃日志在哪里?

标签: java android multithreading crash


【解决方案1】:

您无法从另一个线程访问 UI 元素。尝试像这样在 UI 线程中运行代码。将tv.setText(counter) 替换为以下代码。

YourActivity.this.runOnUiThread((new Runnable() {
    public void run() {
        tv.setText(counter);
    }
});

【讨论】:

    【解决方案2】:

    从不同线程更新 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多