请参考以下代码,该代码从 PHP 脚本中获取一些信息,并将其显示在我的手机上:
package room.temperature;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class RoomTemperatureActivity extends Activity {
String result = null;
StringBuilder sb=null;
TextView TemperatureText, DateText;
ArrayList<NameValuePair> nameValuePairs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TemperatureText = (TextView) findViewById(R.id.temperature);
DateText = (TextView) findViewById(R.id.date);
nameValuePairs = new ArrayList<NameValuePair>();
}
@Override
public void onResume() {
super.onResume();
//setValues();
for (int i = 0; i < 10; i++) {
setValues();
}
}
public void setValues() {
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/tempscript.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine());
is.close();
result=sb.toString();
}
catch(Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
System.out.println(result);
String[] values = result.split("&");
TemperatureText.setText(values[0]);
DateText.setText(values[1]);
}
}
当我注释掉 for 循环并且只调用setValues()
一次时,这段代码效果很好。但是,一旦我引入循环,main.xml
(或屏幕上的任何内容)在循环完成之前不会加载。我认为它与活动生命周期有关,但无论我尝试将代码放在哪里,它都无法正常工作。本质上,我希望这些值在我每次调用时都保持更新setValues()
。10 次迭代循环仅用于测试概念。