Почему android studio выдает исключение NullPointerException при инициализации кнопок, EditText и SwitchCompats? - PullRequest
0 голосов
/ 21 июня 2020
• 1000 вызывается EditText, тогда в этой строке создается исключение NullPointerException. Я пробовал комментировать эту часть кода. Но когда в более поздней части кода инициализируется другая кнопка и вызывается onClickListener, снова генерируется исключение NullPointerException. Снова, когда оба комментируются, при использовании SwitchCompat выдается исключение NullPointerException. Короче говоря, android studio не инициализирует какое-либо поле. Он бросает исключение NullPointerException в каждое поле. Я также пробовал использовать библиотеку ButterKnife, но безуспешно. Ниже - welcome_activity. xml, где вы можете увидеть, что идентификаторы названы правильно. Приветствуются предложения и рекомендации.

Это активность Добро пожаловать. 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>

Вот сборка. 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
...