关于一件我不理解的小事,我有一点问题。
这只是一个简单的请求:如何在线程中显示xml
?
有我的方法postData
来获取xml
,我将其显示在log.v
中,如下面的代码所示,但我无法将其显示为线索TextView
。
public class RecupXml_Activity extends Activity {
TextView campagne;
String user = "toto";
String password = "tata";
String theCampagneXml;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
campagne = (TextView) findViewById(R.id.campagneTest);
postData(user, password);
}
public void postData(final String login, final String password) {
Thread background = new Thread(new Runnable() {
URL url;
String buffer;
String theCampagneXml = null;
@Override
public void run() {
try {
URLConnection urlConnection;
String body = "login=" + URLEncoder.encode(login, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8");
url = new URL("http://3pi.tf/apps/sms/");
urlConnection = url.openConnection();
((HttpURLConnection) urlConnection).setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", "" + body.length());
OutputStreamWriter writer = null;
BufferedReader reader = null;
writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(body);
writer.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((buffer = reader.readLine()) != null) {
theCampagneXml = buffer;
}
Log.v("test", "xml = " + theCampagneXml);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
campagne.post(new Runnable() {
@Override
public void run() {
campagne.setText("salut voici ta campagne : " + theCampagneXml);
}
});
}
});
background.start();
}
}
它显示在我的Log
但未显示在TextView
中:/我有一个空的Activity
。
答案 0 :(得分:1)
问题是您在 UI-tread 上调用了postData()
,这意味着该方法还会在 UI-thread 上返回theCampagneXml
,而您的网络操作在 worker 线程上进行。以下代码包含一些更改和添加修复了问题:
public class MainActivity extends Activity {
TextView campagne;
String user = "toto";
String password = "tata";
String theCampagneXml; // new
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
campagne = (TextView) findViewById(R.id.text);
postData(user, password); // new
}
public void postData(final String login, final String password) { // note: the return type has been changed
Thread background = new Thread(new Runnable() {
URL url;
String buffer;
String theCampagneXml = null; // new
@Override
public void run() {
try {
// no changes here but declaring `theCampagneXml` as class member
}
campagne.post(new Runnable() {
@Override
public void run() {
campagne.setText("hello, here is your XML : "+ theCampagneXml);
}
});
}
});
background.start();
}
}
完成网络操作并初始化theCampagneXml
后,对在UI线程上运行的post()
使用TextView campagne
。
其他信息可在Processes and Threads。
中找到