NavigationView 引发空对象引用异常
Posted
技术标签:
【中文标题】NavigationView 引发空对象引用异常【英文标题】:NavigationView raises null object reference exception 【发布时间】:2021-12-14 20:20:36 【问题描述】:我在 android Studio 中做了一个 DrawerLayout,其中包含一个谷歌地图片段、一个 NavigationView 和一个 FrameLayout。
我的抽屉布局 xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_
android:layout_>
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation"
android:layout_
android:layout_
android:layout_gravity="start"
map:menu="@menu/nav_items"/>
<FrameLayout
android:id="@+id/frame"
android:layout_
android:layout_ />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_
android:layout_>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_
android:layout_
tools:context=".app" />
<Button
android:id="@+id/pop_button"
android:layout_
android:layout_
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:background="@drawable/button_back"
android:text="Pozovi"
map:layout_constraintBottom_toBottomOf="parent"
map:layout_constraintEnd_toEndOf="parent"
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintTop_toTopOf="@+id/map"
map:layout_constraintVertical_bias="0.9" />
<ImageButton
android:onClick="open_drawer"
android:layout_
android:layout_
android:src="@drawable/ic_menu"
map:layout_constraintBottom_toBottomOf="parent"
map:layout_constraintEnd_toEndOf="parent"
map:layout_constraintStart_toStartOf="parent"
map:layout_constraintTop_toTopOf="parent"
map:layout_constraintVertical_bias="0.01"
map:layout_constraintHorizontal_bias="0.01"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.drawerlayout.widget.DrawerLayout>
在我的 java 活动代码中,我添加了一个 onNavigationItemSelected 侦听器:
dLayout = findViewById(R.id.drawer_layout);
navView = (NavigationView) findViewById(R.id.navigation);
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item)
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
return true;
);
问题是这会引发以下错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.navigation.NavigationView.setNavigationItemSelectedListener(com.google.android.material.navigation.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
这是我完整的 java 类代码:
package com.example.soferapp;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.soferapp.databinding.ActivityAppBinding;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class app extends FragmentActivity implements OnMapReadyCallback
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference driver_data = database.getReference("Data").child("Drivers");
DatabaseReference user_data = database.getReference("Data").child("Users");
private GoogleMap mMap;
private ActivityAppBinding binding;
LocationManager locationManager;
LocationListener locationListener;
int permission_id = 1;
Button pop_button;
int num = 0;
private DrawerLayout mDrawerLayout;
List<String> list = new ArrayList<>();
EditText phone_number_input;
DrawerLayout dLayout;
LatLng bih_location = new LatLng(43.86073594535343, 17.771002261242077);
NavigationView navView;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
dLayout = findViewById(R.id.drawer_layout);
navView = (NavigationView) findViewById(R.id.navigation);
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item)
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
return true;
);
binding = ActivityAppBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
pop_button = findViewById(R.id.pop_button);
pop_button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(app.this,
R.style.BottomSheetDialogTheme);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bottom_window, (LinearLayout) findViewById(R.id.bottom_containter));
phone_number_input = bottomSheetView.findViewById(R.id.phone_number);
bottomSheetView.findViewById(R.id.call).setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
String phone_number = phone_number_input.getText().toString();
String key = user_data.push().getKey();
user_data.child(key).child("Phone_number").setValue(phone_number);
user_data.child(key).child("Location").setValue("My coordinates");
user_data.child(key).child("Key").setValue(key);
Toast.makeText(app.this, "Poslat je zahtjev za prevoz", Toast.LENGTH_SHORT).show();
bottomSheetDialog.dismiss();
);
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
);
@Override
public void onMapReady(GoogleMap googleMap)
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(bih_location, 7));
driver_data.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(DataSnapshot dataSnapshot)
googleMap.clear();
list.clear();
for(DataSnapshot ds : dataSnapshot.getChildren())
String driver_coordinates = ds.getValue(String.class);
list.add(driver_coordinates);
for(int i = 0; i < list.size(); i++)
String driver_location = list.get(i);
Double lat = Double.parseDouble(driver_location.split(",")[0]);
Double lon = Double.parseDouble(driver_location.split(",")[1]);
mMap.addMarker(new MarkerOptions().title("Vozač").position(new LatLng(lat, lon)).icon(BitmapDescriptorFactory.fromResource(R.drawable.car_icon)));
@Override
public void onCancelled(DatabaseError databaseError)
);
mMap = googleMap;
enableMyLocation();
private void enableMyLocation()
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
if (mMap != null)
mMap.setMyLocationEnabled(true);
//View locationButton = ((View) findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
//locationButton.setBackgroundColor(Color.parseColor("#20262b"));
else
ActivityCompat.requestPermissions(this, new String[]Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, permission_id);
enableMyLocation();
public void open_drawer(View view)
//dLayout.openDrawer(Gravity.LEFT);
第 78 行出现错误。我尝试做很多事情来解决这个问题,但没有任何效果。
【问题讨论】:
【参考方案1】:您应该在找到任何视图之前设置ContentView。所以像这样的顺序:
binding = ActivityAppBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
dLayout = findViewById(R.id.drawer_layout);
navView = (NavigationView) findViewById(R.id.navigation);
navView.setNavigationItemSelectedListener(
【讨论】:
以上是关于NavigationView 引发空对象引用异常的主要内容,如果未能解决你的问题,请参考以下文章
Sonata Admin Bundle:空实体引用在实体创建期间引发异常
UrlHelper 类在 Asp.net mvc 中引发空异常