Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法从另一个线程触摸视图,如何使其成为可能?_Java_Android_Handler_Settext - Fatal编程技术网

Java 无法从另一个线程触摸视图,如何使其成为可能?

Java 无法从另一个线程触摸视图,如何使其成为可能?,java,android,handler,settext,Java,Android,Handler,Settext,我不明白为什么我不能设置文本到我的文本视图电视。 获取: 我试过很多方法来纠正它。 正如你所看到的,我试过Handler,因为我对烤面包也有同样的问题。现在toast可以工作,但setText不能:(( 请有人帮助我,我应该如何配置此处理程序 public class calculate extends Activity implements OnClickListener { private myService myService; //bound service instance

我不明白为什么我不能设置文本到我的文本视图电视。 获取:

我试过很多方法来纠正它。 正如你所看到的,我试过Handler,因为我对烤面包也有同样的问题。现在toast可以工作,但setText不能:(( 请有人帮助我,我应该如何配置此处理程序

public class calculate extends Activity implements OnClickListener {
    private myService myService; //bound service instance
    private boolean serviceStarted;
    View show_map;
    View data;
    View start;
    View stop;
    public TextView tv;
    private Location loc;
    private boolean initiated=false;
    private float distance=0;
    UIHandler uiHandler;
    route_calc rc;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calculate);
    tv=(TextView)findViewById(R.id.textView1);
    show_map=findViewById(R.id.button1);
    show_map.setOnClickListener(this);
    data=findViewById(R.id.button2);
    data.setOnClickListener(this);
    start=findViewById(R.id.button3);
    start.setOnClickListener(this);
    stop=findViewById(R.id.button4);
    stop.setVisibility(View.INVISIBLE);
    stop.setOnClickListener(this);
    HandlerThread uiThread = new HandlerThread("UIHandler");
    uiThread.start();
    uiHandler = new UIHandler( uiThread.getLooper());

}

public void onDestroy(){
    super.onDestroy();
}


@Override
public void onClick(View v) {
    Intent i;
    switch(v.getId()){
    case R.id.button1:
        i=new Intent(this,Map.class);
        startActivity(i);
        break;
    case R.id.button2:
        i=new Intent(this,data.class);
        startActivity(i);
        break;
    case R.id.button3:
        startService();

        break;
    case R.id.button4:
        stopService();
        break;
    }

}

//connection between this activity and service myService
ServiceConnection myServConn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        myService = null;
    }
    @Override
    public void onServiceConnected(ComponentName arg0, IBinder binder) {
        myService = ((myService.MyBinder)binder).getMyService();
    }
};

private void startService() {
    Intent intent = new Intent(this, myService.class); 
    startService(intent);
    //Bind MyService here
    bindService(intent, myServConn, BIND_AUTO_CREATE);
    stop.setVisibility(View.VISIBLE);
    serviceStarted = true;
    rc = new route_calc();
    rc.start();
}

private void stopService() {
    if(serviceStarted) {
        Intent intent = new Intent(this, myService.class);
        //Unbind MyService here
        unbindService(myServConn);
        stopService(intent);
        stop.setVisibility(View.INVISIBLE);

        serviceStarted = false;
    }
}

void showToast(String s){
    handleUIRequest(s);
}

void setText(){
    handleUISetText();
}

class route_calc extends Thread{
    Location begin;
    public void run() {
        float temp;


        while(!initiated){
            try{

                loc=myService.getLocation();

            }
            catch(Exception e){

            }

            if(loc!=null){
                begin=loc;
                initiated=true;
                showToast("zadzialalo");
            }

        }
        while(true){
            loc=myService.getLocation();
            temp=begin.distanceTo(loc);
            distance=distance+temp;
            tv.setText("przejechales "+distance+" m");
            System.err.println(distance);
            begin=loc;
            try {
                this.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

}


private final class UIHandler extends Handler
{
    public static final int DISPLAY_UI_TOAST = 0;
    public static final int TV_SET_TEXT = 1;

    public UIHandler(Looper looper)
    {
        super(looper);
    }


    public void handleMessage(Message msg)
    {
        switch(msg.what)
        {
        case UIHandler.DISPLAY_UI_TOAST:
        {
            Context context = getApplicationContext();
            Toast t = Toast.makeText(context, (String)msg.obj, Toast.LENGTH_LONG);
            t.show();
        }

        case UIHandler.TV_SET_TEXT:
        {

            tv.setText("przejechałeś "+distance+" m");
        }
        default:
            break;
        }
    }
}

protected void handleUIRequest(String message)
{
    Message msg = uiHandler.obtainMessage(UIHandler.DISPLAY_UI_TOAST);
    msg.obj = message;
    uiHandler.sendMessage(msg);
}

protected void handleUISetText(){
    Message msg=uiHandler.obtainMessage(UIHandler.TV_SET_TEXT);
    uiHandler.sendMessage(msg);
}

}

你似乎把你的整个活动都放在这里,它还包括一项服务,你没有试图缩小你的问题范围

在调用showToast的route_calc线程中,这可能是您的问题之一,您应该从处理程序调用showToast(或任何其他UI函数)

大概是这样的:

在线程上执行任何需要的操作:

   new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        someHeavyStuffHere(); //Big calculations or file download here.
                        handler.sendEmptyMessage(SUCCESS);
                    }
                    catch (Exception e)
                    {
                        handler.sendEmptyMessage(FAILURE);
                    }
                }
            }).start();
数据准备好后,告诉处理程序将其放在视图中并显示:

protected Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == SUCCESS)
            {
                setCalculatedDataToaView(); // the data you calculated from your thread can now be shown in one of your views.
            }
            else if (msg.what == FAILURE)
            {
                errorHandlerHere();//could be your toasts or any other error handling...
            }
        }
    };

非常感谢。这很有帮助:)你解决了我的整个问题。
protected Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == SUCCESS)
            {
                setCalculatedDataToaView(); // the data you calculated from your thread can now be shown in one of your views.
            }
            else if (msg.what == FAILURE)
            {
                errorHandlerHere();//could be your toasts or any other error handling...
            }
        }
    };