![](/img/trans.png)
[英]JAVA - how to use Enum as public static final String in different classes?
[英]How to scope a variable to use as a public static final string?
这段代码位于onCreate中,并从txt文件读取IP地址:
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httppost = new HttpGet("http://readdeo.uw.hu/uploads/IP.txt");
HttpResponse response;
response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line.trim());
// txv.setText(total);
}} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
如何使此String中的“ total” StringBuilder变量用于其他方法?
private static final String SERVER_IP = "IP_ADDRESS";
您可以将IP地址添加为某个类中的字段,然后设置其值:
class YourClass {
String mIpAddress;
...
void yourMethod() {
...
ipAddress = total;
}
}
然后,您应该考虑在初始化mIpAddress
之前有人访问mIpAddress
时会发生什么。
您可以通过处理程序解决此问题。
首先,您可以使用以下代码,例如
private int static final RESULT_IP_ADDRESS = 100;
Message msg = mHandler.obtainMessage(RESULT_IP_ADDRESS);
msg.getData().putString("IP_ADDRESS_KEY", total.toString());
msg.sendToTarget();
class MyHandler extends Handler{
@override
public void handleMessage(Message msg) {
switch(msg.what) {
case RESULT_IP_ADDRESS:
String total = msg.getData().getString("IP_ADDRESS_KEY");
// call your method with total data
break;
default:
break;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.