![](/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.