简体   繁体   English

如何确定变量的范围以用作公共静态最终字符串?

[英]How to scope a variable to use as a public static final string?

This code is in the onCreate and reading an IP address from a txt file: 这段代码位于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();
}

How can i make it to use the "total" StringBuilder variable in this String for other methods? 如何使此String中的“ total” StringBuilder变量用于其他方法?

private static final String SERVER_IP = "IP_ADDRESS";

You can add the IP address as a field in some class and then set its value: 您可以将IP地址添加为某个类中的字段,然后设置其值:

class YourClass {
    String mIpAddress;

    ...

    void yourMethod() {
        ...
        ipAddress = total;
    }
}

And then you should think about what happens when somewhere else someone accesses mIpAddress before it is initialized. 然后,您应该考虑在初始化mIpAddress之前有人访问mIpAddress时会发生什么。

you can fix this issue by handler. 您可以通过处理程序解决此问题。

first, you can use below code, such as 首先,您可以使用以下代码,例如

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM