如何将变量用作公共静态最终字符串?

时间:2013-08-10 23:51:19

标签: java android scope

此代码位于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";

2 个答案:

答案 0 :(得分:0)

您可以将IP地址添加为某个类中的字段,然后设置其值:

class YourClass {
    String mIpAddress;

    ...

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

然后你应该考虑在其他人在初始化之前访问mIpAddress的其他地方会发生什么。

答案 1 :(得分:0)

您可以通过处理程序解决此问题。

首先,您可以使用以下代码,例如

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