从线程获取字符串值 [英] get a string value from a thread

查看:82
本文介绍了从线程获取字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我,如何从线程中获取Stringvalue到mainActivity?

can someone tell me, how do get a Stringvalue from a thread to the mainActivity?

我有一个这样的线程:

public class XMLHandler extends DefaultHandler {

XMLDataCollected data = new XMLDataCollected();

    ......
    ......

public String getInformation() {

    String information = "";

        if (data.getData().equals("residential")) {
            information = "Stadt";
        }           
        return information;
}   

}

在mainActivity中,我尝试将值设置为如下所示的文本视图:

in the mainActivity i tried to set the value into a textview like this:

textView.setText(xmlHandler.getInformation());

我毕竟不工作.我做错了什么?有什么解决方案和建议吗?预先感谢

i does not work after all. what i am doing wrong? any solutions and advices? thanks in advance

推荐答案

如果您有SeparateThread类,则需要创建一个接口说

If you have a SeparateThread class then you need to create one Interface say

public interface FetchValueListener{

public void sendValue(String value_to_send);

}

您的权限将实现此接口,因此sendValue(value_to_send)方法将添加到您的活动中.

And your acctivity will be implementing this interface and thus sendValue(value_to_send) method will be added to your activity.

下一步是当您创建THread类的对象时,您需要按如下所示在参数中传递该接口的对象:

Next step would be when you create the object of the THread class then you need to pass the object of that interface in the paramater as follows:

    public class myThreadClass{
    FetchValueListener mllistener;

    myThreadClass(FetchValueListener listenerObj){
         mllistener=listenerObj;
    }

    }

现在,当您想从线程向活动发送一些值时,只需调用

Now when you want to send some value to the activity from thread you can just simply call

mllistener.sendValue(value_you_wan_to_send);

在您的活动中,您将在sendValue()方法中获取该值.

And inside your actiivty you will get the value in the sendValue() method..

在该方法中,您需要使用处理程序将数据发布到可运行状态,以便可以对UI进行更改,例如 setText 等.如果直接尝试使用该方法设置文本视图的值,则会出现异常.

In that method you need to post the data to runnable using the handler so that you can make changes to the UI like setText etc..... If you directly try to set the value of text view in that method you will get an exception.

这篇关于从线程获取字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆