尝试通过BottomNavigationView开始活动时出现异常。
当onCreate()
出现异常时,它一直工作到现在,突然突然开始抛出异常,问题似乎出在BottomNavigationView上,我继续尝试删除每一行并运行我的代码以找出问题所在,因此,当我删除第40行:app:menu="@menu/navigation"
时,它可以工作,但是它又抛出了另一个异常(如下所述),尽管事实上该特定行对于查看。
我在网上发现,如果在build.gradle中,实现('com.android.support:design'
)和('com.android.support:appcompat-v7'
)应该是相同的版本,则它们是完全相同的版本,尽管Android Studio显示了我对appcompat的实现错误。
MainAppActivity.java
package com.example.myapplication;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.myapplication.Users.User;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.firestore.GeoPoint;
import java.util.List;
public class MainAppActivity extends AppCompatActivity {
public static final String TAG = "MainApp";
public static final int REQUEST_CODE_LAST_LOCATION = 123;
Fragment selectedFragment;
private Activity mainActivity = this;
private Location thisLocation;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private boolean shouldStartLocationUpdates = false;
private FusedLocationProviderClient fusedLocationProviderClient;
private MyDBService myService;
private MyDBService.MyLocalBinder binder;
private Boolean isBound;
private ServiceConnection serviceConnection;
private ProgressBar progressBar;
private TextView progressLbl;
private List<User> nearbyUsers;
private User currentUser;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
FrameLayout mainFrame = findViewById(R.id.mainFrame);
Bundle bundle = new Bundle();
switch (item.getItemId()) {
case R.id.nav_home:
mainActivity.setTitle(R.string.online);
selectedFragment = new OnlineFragment();
bundle.putBinder("binder", binder);
if(!shouldStartLocationUpdates){
startLocationUpdates();
}
break;
case R.id.nav_chat:
mainActivity.setTitle(R.string.messages);
selectedFragment = new MessagesFragment();
bundle.putBinder("binder", binder);
if(shouldStartLocationUpdates){
stopLocationUpdates();
}
break;
case R.id.nav_favs:
mainActivity.setTitle(R.string.favourites);
selectedFragment = new FavouritesFragment();
bundle.putBinder("binder", binder);
if(shouldStartLocationUpdates){
stopLocationUpdates();
}
break;
}
selectedFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame, selectedFragment).commit();
return true;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_app);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (MyDBService.MyLocalBinder) service;
myService = binder.getService();
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
}
};
Intent intent = new Intent(MainAppActivity.this, MyDBService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
Log.i(TAG, "Location: " + location.getLatitude() + " " + location.getLongitude());
thisLocation = location;
SharedPreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
String id = sharedPreferences.getString("firestore_uid_db", null);
sharedPreferences.edit().putString("location", thisLocation.getLatitude() + "," + thisLocation.getLongitude()).commit();
}
if (selectedFragment == null) {
selectedFragment = new OnlineFragment();
Bundle bundle = new Bundle();
bundle.putBinder("binder", binder);
selectedFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame, selectedFragment).commit();
}
}
};
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
progressBar = findViewById(R.id.progressBarFragments);
progressLbl = findViewById(R.id.progressLbl);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
getLocation();
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_CODE_LAST_LOCATION);
}else {
createLocationRequest();
startLocationUpdates();
new UpdateDBField().execute(thisLocation);
}
}
private void createLocationRequest() {
if (locationRequest == null)
locationRequest = LocationRequest.create();
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@SuppressLint("MissingPermission")
private void startLocationUpdates() {
shouldStartLocationUpdates = true;
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
private void stopLocationUpdates() {
shouldStartLocationUpdates = false;
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
@Override
public void onPause() {
super.onPause();
stopLocationUpdates();
}
@Override
public void onStop() {
super.onStop();
stopLocationUpdates();
// Unbind from the service
if (isBound) {
unbindService(serviceConnection);
isBound = false;
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdates();
}
@Override
public void onResume() {
super.onResume();
if (shouldStartLocationUpdates)
startLocationUpdates();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_LAST_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
}
}
}
public class UpdateDBField extends AsyncTask<Location, Integer, Void>{
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
progressLbl.setVisibility(View.VISIBLE);
}
@Override
protected void onProgressUpdate(Integer... ints) {
switch (ints[0]){
case 1:
progressLbl.setText("Getting location updates...");
break;
case 2:
progressLbl.setText("Preparing users' info...");
break;
case 3:
progressLbl.setText("Preparing nearby users...");
break;
}
}
@Override
protected Void doInBackground(Location... locations) {
publishProgress(1);
Log.d(TAG, "doInBackground: published 1");
updateLocationInDB(locations[0]);
publishProgress(2);
Log.d(TAG, "doInBackground: published 2");
defineCurrentUser();
publishProgress(3);
Log.d(TAG, "doInBackground: published 3");
defineNearbyUsers();
return null;
}
private void updateLocationInDB(Location location1) {
if(location1 == null){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
updateLocationInDB(thisLocation);
}else{
myService.updateLocationFieldInUsersTokens("latlng", new GeoPoint(location1.getLatitude(), location1.getLongitude()));
}
}
private void defineCurrentUser() {
currentUser = myService.getCurrentUser();
if(currentUser == null){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
defineCurrentUser();
}
}
private void defineNearbyUsers() {
nearbyUsers = myService.getNearbyUsers();
if(nearbyUsers == null){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
defineNearbyUsers();
}
}
@Override
protected void onPostExecute(Void aVoid) {
progressBar.setVisibility(View.GONE);
progressLbl.setVisibility(View.GONE);
}
}
}
BottomNavigationView
(R.id.activity_main_app)
的XML 代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainAppActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/navigation"
android:id="@+id/mainFrame">
</FrameLayout>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/progressBarFragments"
android:visibility="gone"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="progress..."
android:textAlignment="center"
android:layout_alignTop="@id/progressBarFragments"
android:layout_marginTop="70dp"
android:visibility="gone"
android:id="@+id/progressLbl"/>
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
android:layout_alignParentBottom="true"
app:menu="@menu/navigation"/>
</RelativeLayout>
build.gradle(Module:app)
显示错误 enter image description here
All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0, 27.1.1, 27.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0 and com.android.support:customtabs:27.1.1 less... (⌘F1)
Inspection info:There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion). Issue id: GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
菜单/navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/nav_home"
android:icon="@drawable/ic_online"
android:title="@string/online" />
<item
android:id="@+id/nav_chat"
android:icon="@drawable/ic_chat_light_24dp"
android:title="@string/messages" />
<item
android:id="@+id/nav_favs"
android:icon="@drawable/ic_star_light_24dp"
android:title="@string/favourites" />
</menu>
膨胀异常(第一期)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 21765
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainAppActivity}: android.view.InflateException: Binary XML file line #32: Binary XML file line #32: Error inflating class android.support.design.widget.BottomNavigationView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.view.InflateException: Binary XML file line #32: Binary XML file line #32: Error inflating class android.support.design.widget.BottomNavigationView
Caused by: android.view.InflateException: Binary XML file line #32: Error inflating class android.support.design.widget.BottomNavigationView
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.myapplication.MainAppActivity.onCreate(MainAppActivity.java:98)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setImportantForAccessibility(int)' on a null object reference
at android.support.v4.view.ViewCompat.setImportantForAccessibility(ViewCompat.java:1027)
at android.support.design.internal.BottomNavigationItemView.<init>(BottomNavigationItemView.java:93)
E/AndroidRuntime: at android.support.design.internal.BottomNavigationItemView.<init>(BottomNavigationItemView.java:77)
at android.support.design.internal.BottomNavigationItemView.<init>(BottomNavigationItemView.java:73)
at android.support.design.internal.BottomNavigationMenuView.getNewItem(BottomNavigationMenuView.java:571)
at android.support.design.internal.BottomNavigationMenuView.buildMenuView(BottomNavigationMenuView.java:507)
at android.support.design.internal.BottomNavigationPresenter.updateMenuView(BottomNavigationPresenter.java:62)
at android.support.design.widget.BottomNavigationView.inflateMenu(BottomNavigationView.java:254)
at android.support.design.widget.BottomNavigationView.<init>(BottomNavigationView.java:187)
at android.support.design.widget.BottomNavigationView.<init>(BottomNavigationView.java:114)
... 28 more
在TextView
出现问题之前正确声明BottomNavigationView
并正常工作时抛出NullPointerException(删除第40行app:menu="@menu/navigation"
之后产生第二个问题)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 23247
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainAppActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setVisibility(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setVisibility(int)' on a null object reference
at com.example.myapplication.MainAppActivity$UpdateDBField.onPreExecute(MainAppActivity.java:240)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:648)
at android.os.AsyncTask.execute(AsyncTask.java:595)
at com.example.myapplication.MainAppActivity.getLocation(MainAppActivity.java:175)
at com.example.myapplication.MainAppActivity.onCreate(MainAppActivity.java:148)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
答案 0 :(得分:0)
我看到了。我认为您的问题出在onPreExecute()
类代码的UpdateDBField
部分中。可能是
progressBar.setVisibility(View.VISIBLE);
progressLbl.setVisibility(View.VISIBLE);
为空。确保从xml设置正确的视图ID,以避免出现空指针异常。
编辑:
检查代码的这一部分:
progressBar = findViewById(R.id.progressBarFragments);
progressLbl = findViewById(R.id.progressLbl);
根据您的progressBarFragments
方法,检查用于此活动的xml文件中是否存在您的progressLbl
和R.layout.activity_main_app
ID。{p}
答案 1 :(得分:0)
通过清理项目解决了问题。
Android Studio工具栏>生成>清理项目
答案 2 :(得分:0)
尝试用相同版本替换build.gradle中的这些行,这可能会解决您的问题。
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.jakewharton:butterknife:8.8.1'
implementation 'com.android.support:support-v4:27.1.1'