可变' snackbar'可能尚未初始化

时间:2016-02-04 12:14:29

标签: java android

我收到此错误消息,指出Variable "snackbar" might not have been initialized

以下是我的 MainActivity.java 代码的一部分:

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

    if (info != null && info.isConnected()) {
        final Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "WiFi change detected; updating information...", Snackbar.LENGTH_LONG)
            .setAction("DISMISS", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    snackbar.dismiss();
                }
            });
            snackbar.setActionTextColor(Color.BLUE);
            snackbar.show();

            getWifi();
    }
}
}

我已阅读已接受的Stack Overflow回复here,并建议我在snackbar之后立即初始化public class NetworkChangeReceiver extends BroadcastReceiver。所以,我将代码更改为:

/* no changes here */
@Override
public void onReceive(Context context, Intent intent) {
    Snackbar snackbar = null;

    /* no changes here */
    if (...) {
        snackbar = Snackbar.make(...);
    }

    /* no changes here */
}

但这会给我一个错误Variable "snackbar" is accessed from within inner class, needs to be declared final和一个警告Method invocation "snackbar.dismiss()" may produce "java.lang.NullPointerException"

有关如何解决此问题的任何建议?谢谢!

2 个答案:

答案 0 :(得分:9)

拆分你的链式方法调用:

snackbar

这样,OnClickListener在您创建{{1}}之前就已明确分配。

答案 1 :(得分:-5)

作为

的解决方法
  

Variable "snackbar" is accessed from within inner class, needs to be declared final

您可以将该变量设为最终的单元素数组