android - 添加网络检测代码后FAB的空指针异常(即使定义好)
问题描述
我添加了一些代码来检测是否有互联网连接(请在下面找到它),它运行良好,但是当我只想在有互联网连接时显示 mainactivity 时,应用程序会抛出 fab 空指针异常。这是我的日志:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.material.manohar.vblogs/com.material.manohar.vblogs.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2779)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2857)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1590)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6499)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!isConnected(MainActivity.this)) buildDialog(MainActivity.this).show();
else {
setContentView(R.layout.activity_main);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","xxxxx@gmail.com", null));
String subject = "Suggest/Feedback -- VB";
String message = "";
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(intent, "Choose an Email client :"));
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi=cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile=cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((mobile!= null && mobile.isConnectedOrConnecting()) || (wifi!= null && wifi.isConnectedOrConnecting())) return true;
else return false;
}
else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet Connection");
builder.setMessage("You need to have Mobile Data or wifi to access the app. Press ok to Exit");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder;
}
//Rest code is nav drawer functionalities which we get by selecting nav drawer activity layout.
野兔是我的 activity_main.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
包含 fab 视图的 app_bar_main.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:titleTextAppearance="@style/TitleBarTextAppearance"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
解决方案
仔细查看您的代码,特别是这部分:
if(!isConnected(MainActivity.this)) buildDialog(MainActivity.this).show();
else {
setContentView(R.layout.activity_main);
}
您仅setContentView()
在有连接时才调用,但无论如何您都在初始化和编辑视图。如果您没有互联网,您的 if 语句将运行buildDialog().show()
,_然后继续到您的其余部分onCreate()
。
要解决这个问题,只需将其他所有内容放在onCreate()
elsesetContentView()
块中:
if(!isConnected(MainActivity.this)) buildDialog(MainActivity.this).show();
else {
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","xxxxx@gmail.com", null));
String subject = "Suggest/Feedback -- VB";
String message = "";
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(intent, "Choose an Email client :"));
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
推荐阅读
- ghidra - 清除几个功能(带选项)
- javascript - 什么是“未捕获 RangeError:超出最大调用堆栈大小”
- c# - Azure Pipeline 在 dotnet 构建中失败,需要升级到最新的 .net 核心版本
- php - 如何从 WooCommerce 结帐中清除特定的计费字段值
- javascript - 带有 Puppeteer 的 Web Scraping Loop:“等待仅在异步函数中有效”
- python - Excel python openpyxl方法
- java - \u000b 和其他与 docx4j 不兼容的控制 Unicode 字符?
- c++ - 在动态内存区域中初始化 char 数组(在构造函数中)时出现问题
- typescript - webpack ts-loader 不排除文件
- python - Pip 默认为用户安装,因为普通站点包不可写