0

I am not understanding why I am getting this error. Thanks for the help! The app is crashing after opening HomeActivity.java I have also added google-services.json file in app directory of project

ERROR

2022-04-10 12:04:48.272 4186-4186/com.example.budgetapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.budgetapp, PID: 4186
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at com.example.budgetapp.HomeActivity.lambda$readData$0$com-example-budgetapp-HomeActivity(HomeActivity.java:65)
        at com.example.budgetapp.HomeActivity$$ExternalSyntheticLambda8.onEvent(D8$$SyntheticClass)
        at com.google.firebase.firestore.Query.lambda$addSnapshotListenerInternal$2$com-google-firebase-firestore-Query(Query.java:1206)
        at com.google.firebase.firestore.Query$$ExternalSyntheticLambda2.onEvent(D8$$SyntheticClass)
        at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0$com-google-firebase-firestore-core-AsyncEventListener(AsyncEventListener.java:42)
        at com.google.firebase.firestore.core.AsyncEventListener$$ExternalSyntheticLambda0.run(D8$$SyntheticClass)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

HomeActivity.java

package com.example.budgetapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.firebase.FirebaseApp;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class HomeActivity extends AppCompatActivity {

    FirebaseFirestore myDB;
    FirebaseApp myApp;

    EditText edtData;
    ListView listView;
    List<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // InitViews
        edtData = findViewById(R.id.edt_hint);
        listView = findViewById(R.id.lv);

        // Init FirebaseApp
        myApp = FirebaseApp.initializeApp(this);

        // Init FireStore
        myDB = FirebaseFirestore.getInstance();
        readData();
    }

    void readData() {
        myDB.collection("tasks").addSnapshotListener((documentSnapshots, e) -> {
            if (e != null)
                toastResult(e.getMessage());
            list.clear();
            if (documentSnapshots != null) {
                for (DocumentSnapshot doc : documentSnapshots) {
                    list.add(doc.getString("task_name"));
                }
            }
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(),
                    R.layout.simple_list_item,
                    R.id.text1,
                    list);
            listView.setAdapter(arrayAdapter);
        });
    }

    public void onAddClicked(View view) {
        hideKeyboard(this);
        if (edtData.getText().toString().length() > 0) {
            Map<String, Object> data = new HashMap<>();
            data.put("task_name", edtData.getText().toString());
            myDB.collection("tasks")
                    .add(data)
                    .addOnSuccessListener(documentReference -> toastResult("Data added successfully"))
                    .addOnFailureListener(e -> toastResult("Error while adding the data : " + e.getMessage()));

        } else {
            edtData.setError("Value Required");
        }
    }

    public void onReadClicked(View view) {
        hideKeyboard(this);
        DocumentReference documentReference = myDB.collection("myData").document("1");
        documentReference.get().addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                edtData.setText(Objects.requireNonNull(task.getResult().get("data")).toString());
            }
        });
    }

    public void onUpdateClicked(View view) {
        hideKeyboard(this);
        if (edtData.getText().toString().length() > 0) {
            Map<String, Object> data = new HashMap<>();
            data.put("data", edtData.getText().toString());
            myDB.collection("myData").document("1").update(data)
                    .addOnSuccessListener(aVoid -> toastResult("Data updated successfully"))
                    .addOnCompleteListener(task -> toastResult("Data update Completed"))
                    .addOnFailureListener(e -> toastResult("Error while updating the data : " + e.getMessage()));
        } else {
            edtData.setError("Value Required");
        }
    }

    public void onDeleteClicked(View view) {
        hideKeyboard(this);
        myDB.collection("myData").document("1").delete()
                .addOnSuccessListener(aVoid -> toastResult("Data deleted successfully"))
                .addOnFailureListener(e -> toastResult("Error while deleting the data : " + e.getMessage()));
    }

    public void toastResult(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public static void hideKeyboard(HomeActivity activity) {
        View view = activity.findViewById(android.R.id.content);
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            assert imm != null;
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

}

activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".HomeActivity">

    <EditText
        android:id="@+id/edt_hint"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edt_hint"
        android:importantForAutofill="no"
        android:inputType="text" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onAddClicked"
            android:text="@string/btn_add"
            style="?android:attr/buttonBarButtonStyle"
            tools:ignore="UsingOnClickInXml" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onReadClicked"
            android:text="@string/btn_read"
            style="?android:attr/buttonBarButtonStyle"
            tools:ignore="UsingOnClickInXml" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onUpdateClicked"
            android:padding="5dp"
            android:text="@string/btn_update"
            style="?android:attr/buttonBarButtonStyle"
            tools:ignore="UsingOnClickInXml" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onDeleteClicked"
            android:text="@string/btn_delete"
            style="?android:attr/buttonBarButtonStyle"
            tools:ignore="UsingOnClickInXml" />
    </LinearLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:id="@+id/lv"/>

</LinearLayout>

simple_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:textColor="@color/blue"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:minHeight="?android:attr/listPreferredItemHeightSmall" />

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.budgetapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BudgetApp">
        <activity
            android:name=".RegisterActivity"
            android:exported="false" />
        <activity
            android:name=".HomeActivity"
            android:exported="false" />
        <activity
            android:name=".LoginActivity"
            android:exported="false" />
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

build.gradle (Project:Budget_App)

buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10'
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.2' apply false
    id 'com.android.library' version '7.1.2' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle (Module:Budget_App:app)

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.budgetapp"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

        implementation 'androidx.appcompat:appcompat:1.4.1'
        implementation 'com.google.android.material:material:1.5.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
        implementation 'com.google.firebase:firebase-firestore:24.1.0'
        implementation 'com.google.firebase:firebase-auth:21.0.3'
        testImplementation 'junit:junit:4.13.2'
        androidTestImplementation 'androidx.test.ext:junit:1.1.3'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    }

0 Answers0