java - 为什么android studio在初始化Buttons、EditText和SwitchCompats时会出现NullPointerException?
问题描述
我是 android studio 的初学者,正在开发一个类似于 Uber 应用程序的项目。我在 Welcome 活动中陷入了几个小时的错误,每当编译器到达初始化 EditText 的行,然后在 EditText 上调用 setFocusable() 方法然后 NullPointerException被扔在那条线上。我尝试评论那部分代码。但是,当在代码的后面部分初始化另一个按钮并调用 onClickListener 时,会再次引发 NullPointerException。当两者都被注释时,在使用 SwitchCompat 时会引发 NullPointerException。简而言之,android studio 没有初始化任何字段。它在每个字段上抛出 NullPointerException。我也尝试过使用 ButterKnife 库但徒劳无功。下面是welcome_activity.xml,您可以在其中看到正确命名的ID。建议和指导表示赞赏。
那就是活动 Welcome.java
package com.anonymous.uberedmt;
private Button btnGo;
private EditText places;
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
callPermissions();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} catch (Exception e) {
Log.d("Error: ", "nkn");
}
polyLineList = new ArrayList<>();
//Places Autocomplete
**places = findViewById( R.id.edt_Place);
Places.initialize(getApplicationContext(), "API-KEY");
places.setFocusable(false);**
places.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Initialize Place-Field List
List<Place.Field> fieldList = Arrays.asList(Place.Field.ADDRESS, Place.Field.LAT_LNG, Place.Field.NAME);
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fieldList).build(Welcome.this);
startActivityForResult(intent, PLACES_REQUEST_CODE);
}
});
**btnGo = findViewById(R.id.btn_Go);**
btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
destination = places.getText().toString();
destination = destination.replace(" ", "+"); //Replace space with plus to fetch data
Log.d("ShARRY", destination);
getDirection();
}
});
**location_switch = findViewById(R.id.location_switch);
location_switch.setOnClickListener(new View.OnClickListener() {**
@Override
public void onClick(View v) {
if (location_switch.isChecked()) {
startLocationUpdates();
displayLocation();
Snackbar.make(mapFragment.getView(), "You are Online", Snackbar.LENGTH_SHORT).show();
} else {
stopLocationUpdates();
if(mCurrent != null)
mCurrent.remove();
mMap.clear();
handler = new Handler();
handler.removeCallbacks(drawPathRunnable);
Snackbar.make(mapFragment.getView(), "You are Offline", Snackbar.LENGTH_SHORT).show();
}
}
});
}
}
这是activity_welcome.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:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_panel"
android:orientation="horizontal">
<EditText
**android:id="@+id/edt_Place"**
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="5"
android:layout_margin="10dp"
android:hint="@string/enter_pickup_location"/>
<Button
**android:id="@+id/btn_Go"**
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginTop="10dp"
android:text="@string/go"/>
</LinearLayout>
<fragment
android:id="@+id/map"
android:layout_below="@+id/layout_panel"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.anonymous.uberedmt.Welcome"
tools:layout="@layout/activity_welcome" />
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="horizontal"
android:weightSum="10">
<androidx.appcompat.widget.SwitchCompat
**android:id="@+id/location_switch"**
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:layoutDirection="rtl"
android:padding="4dp"
android:textOff="@drawable/ic_location_off"
android:textOn="@drawable/ic_location_on" />
<Button
**android:id="@+id/btn_find_user"**
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="7"
android:text="@string/find_user" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
这是 build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.anonymous.uberedmt"
minSdkVersion 26
targetSdkVersion 29
versionCode 1
versionName "1.0"
multiDexEnabled = true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-analytics:17.4.3'
implementation 'com.google.firebase:firebase-auth:19.3.1'
implementation 'com.google.firebase:firebase-database:19.3.0'
implementation 'com.google.firebase:firebase-firestore:21.4.3'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.firebase:firebase-messaging:20.2.1'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'androidx.multidex:multidex:2.0.1'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.legacy:legacy-support-core-utils:1.0.0'
implementation 'com.rengwuxian.materialedittext:library:2.1.4'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.github.d-max:spots-dialog:1.1@aar'
implementation 'com.firebase:geofire-java:3.0.0'
implementation 'com.nabinbhandari.android:permissions:3.8'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.android.libraries.places:places:2.3.0'
implementation 'de.hdodenhof:circleimageview:3.1.0'
}
这是项目级 gradle 文件:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven{
url 'http://maven.google.com'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3'
classpath 'com.google.gms:google-services:4.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.anonymous.uberedmt, PID: 28835
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.anonymous.uberedmt/com.anonymous.uberedmt.Welcome}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.widget.SwitchCompat.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.widget.SwitchCompat.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.anonymous.uberedmt.Welcome.onCreate(Welcome.java:255)
at android.app.Activity.performCreate(Activity.java:8086)
at android.app.Activity.performCreate(Activity.java:8074)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3755)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
I/Process: Sending signal. PID: 28835 SIG: 9
解决方案
推荐阅读
- amazon - Quicksight 日期选择器
- javascript - 即使添加了等待,Lambda 函数也不会运行其他异步函数
- node.js - 如何有一个有条件地必须为空的字段?
- python - 附加到字典内的列表会删除以前的值
- sql-server - 在链接服务器上执行存储过程以使用本地计算机上的对象
- python - 优化 tensorflow 装饰函数(Python)中的实现效率
- mysql - 按 IS NULL 排序是否使用 MySQL 中的索引
- javascript - 如何在javascript中使循环等待代码执行x周期?
- elasticsearch - 无法在弹性搜索中聚合
- python - 如何列出不同域的openstack用户组?