简体   繁体   中英

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:

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?

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:

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.

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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