【问题标题】:Android Runnable class - cannot access property from run() methodAndroid Runnable 类 - 无法从 run() 方法访问属性
【发布时间】:2013-09-19 05:40:58
【问题描述】:
  class MyRunnable implements Runnable{
        public StringBuffer line2;
        public MyRunnable(StringBuffer _line){
             this.line2 = _line;
             Log.w("LINE", this.line2.toString());   // Return what it should
        }

        public void run(){
             console.append(this.line2.toString());   //Nothing happens here
        }
  }

这是我的代码。我有一个问题,当从 run() 方法访问 line2 时,它的长度为 0。

编辑:这是我的电话

        new Thread(new Runnable() {             
            @Override
            public void run() {
                StringBuffer line = new StringBuffer();
                while(true){
                    char a = UART.serialRead(UART.fd);

                    if(a != 0){                         
                        if (a == '\r' || a == '\n'){
                            MyRunnable obj = new MyRunnable(line);
                            handler.post(obj);
                            line.delete(0, line.length());
                            obj = null;
                        }else
                            line.append(a); 
                    }                   

                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        }).start();

知道我哪里错了吗?

【问题讨论】:

  • 0 长度有什么问题?您只需在 ctor 中传递空的 StrinBuffer
  • 嗯它不应该是0。我也清楚地看到我通过的行不是空的。
  • 你在 MyRunnable 类上调用线程了吗?
  • 是的,我正在调用线程。

标签: android runnable stringbuffer


【解决方案1】:

请验证您是否使用单参数构造函数实例化 MyRunnable 类。

【讨论】:

    【解决方案2】:

    尝试发布制作 MyRunnable obj = new MyRunnable(line.toString); end 在 MyRunnable 中得到一个字符串。我不确定 line 是否作为副本或对象传递,但在您的情况下不是引用。如果它的引用比你在 MyRunnable 中使用之前清除的行。

    【讨论】:

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