Runnable上的参数

时间:2014-11-18 12:34:06

标签: java android parameters runnable

我正在尝试将“entityFinal”传递给 run()方法,但由于它是可运行的,因此我无法使用任何参数。

runOnUiThread 上的“responseView.setText”被评论,因为我的android工作室始终打印我的responseView为空,我无法理解为什么它,因为我正在使用正确查看xml。

有人可以给我一个暗示吗?我测试了很多东西,asyncTask,多线程,但这是我“差点”工作的唯一方法。

先谢谢你。

xml:

  <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/Blank"
            android:id="@+id/textView"
            android:layout_below="@+id/button2"
            android:layout_alignLeft="@+id/button2"
            android:layout_alignStart="@+id/button2"
            android:layout_marginTop="50dp"/>

Java文件代码:

 final TextView responseView = (TextView) activity.findViewById(R.id.textView);
                   new Thread(){
                       public void run(){
                           try{
                             HttpResponse httpResponse = httpclient.execute(httppost);
                             final HttpEntity entity = httpResponse.getEntity();
                             final String entityFinal = entity.getContent().toString();
                           }catch(IOException e){
                               System.out.println(e.getMessage());
                           }
                           activity.runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   //responseView.setText(entityFinal);
                                   System.out.println(responseView);
                               }
                           });
                       }
                   }.start();

2 个答案:

答案 0 :(得分:0)

在您的情况下,移动

activity.runOnUiThread(new Runnable() {
     @Override
     public void run() {
       //responseView.setText(entityFinal);
       System.out.println(responseView);
    }
);

进入try块就足够了。通常,您总是可以使用构造函数实现Runnable的类,该构造函数采用任意数量/类型的参数。例如

public class MyRunnable implements Runnable {

     private final String mString;
     public MyRunnable(String string) {
          mString = string;
     }

     @Override
     public void run() { 
         System.out.println(mString);
     }
}

答案 1 :(得分:0)

您可以这样使用:

new Thread(
    new Runnable() {
        @Override
        public void run() {
           System.out.println(responseView);
        }
    }).start();