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

How to Store in Global Variable from local variable?

在最后一个 Toast 时,它会打印空白 Toast.Why? 我将局部变量传递给全局变量并打印出来。为什么 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!!!!!!!!

}

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

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

此外,如果接收时出现错误,您的全局变量可能为空

您还可以使用函数更新全局变量,然后在其中调用 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();

}