如何从局部变量存储全局变量?

时间:2016-01-19 04:54:29

标签: android return nested-function outer-classes

在最后的Toast,它将打印空白Toast。为什么? 我将局部变量传递给全局变量,然后将其打印出来。为什么Java不允许这样?这是什么解决方案?

这是代码......

String sb_temp=" ";  //global variable


public void getsortedsignal()
{

    final WifiManager wm=(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    if(wm.isWifiEnabled()==false) {
        Toast.makeText(getApplicationContext(), "Wifi Is Disabled.. Please Enable it", Toast.LENGTH_LONG).show();
        wm.setWifiEnabled(true);
    }

    registerReceiver(new BroadcastReceiver() {


        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder sb = new StringBuilder();

            wm.startScan();

            scanResults = wm.getScanResults();

            //Making it in Asencending Order
            Comparator<ScanResult> comparator = new Comparator<ScanResult>() {
                @Override
                public int compare(ScanResult lhs, ScanResult rhs) {
                    return (lhs.level > rhs.level ? -1 : (lhs.level == rhs.level ? 0 : 1));
                }
            };

            Collections.sort(scanResults, comparator);

            //Exact 5 Ap's Values
            for (int i = 0; i < 5; i++) {

                sb.append(scanResults.get(i).SSID + "--").toString();
                sb.append(scanResults.get(i).BSSID + "--").toString();
                sb.append((-1 * scanResults.get(i).level) + "\n").toString();
            }


            sb_temp=sb.toString();

            //Toast.makeText(getApplicationContext(), sb_temp, Toast.LENGTH_SHORT).show();

        }

    }, new IntentFilter(WifiManager.RSSI_CHANGED_ACTION));

    Toast.makeText(getApplicationContext(), sb_temp, Toast.LENGTH_SHORT).show();   //Problem is Here!!!!!!!!

}

2 个答案:

答案 0 :(得分:0)

您正在注册receiver将立即调用Toast,但接收器不会,它必须接收某些内容才能显示toast。将Toast移除到BroadcastReceiver内。

答案 1 :(得分:0)

问题出在全局变量更新之前,调用Toast。 接收发生在后台线程上,而Toast正在主线程上显示。如果你想显示吐司,那么你可以把Toast放在接收器本身。

此外,如果在接收

时出现错误,则您的全局变量可能为null

此外,您可以使用函数更新全局变量,然后在其中调用toast。像:

    for (int i = 0; i < 5; i++) {

        sb.append(scanResults.get(i).SSID + "--").toString();
        sb.append(scanResults.get(i).BSSID + "--").toString();
        sb.append((-1 * scanResults.get(i).level) + "\n").toString();
    }


    updateGloablString(sb);

...

private void updateGlobalString(String sb){
 sb_temp=sb.toString();
Toast.makeText(getApplicationContext(), sb_temp, Toast.LENGTH_SHORT).show();

}