简体   繁体   English

Android studio null object 参考错误

[英]Android studio null object reference error

This is the error I am facing Caused by: 'java.lang.NullPointerException' Attempt to invoke virtual method 'java.lang.String() on a null object reference at com.example.stdio9.MainActivity.getProfileImage(MainActivity.java:230) at com.example.stdio9.MainActivity.onCreate(MainActivity.java:84) This is the error I am facing Caused by: 'java.lang.NullPointerException' Attempt to invoke virtual method 'java.lang.String() on a null object reference at com.example.stdio9.MainActivity.getProfileImage(MainActivity.java: 230) 在 com.example.stdio9.MainActivity.onCreate(MainActivity.java:84)

This is my java code这是我的 java 代码

package com.example.stdio9;

import static com.google.android.gms.auth.api.signin.GoogleSignIn.getClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stdio9.fragment.ExploreFragment;
import com.example.stdio9.fragment.HomeFragment;
import com.example.stdio9.fragment.LibraryFragment;
import com.example.stdio9.fragment.SubscriptionsFragment;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
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 com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    BottomNavigationView bottomNavigationView;
    FrameLayout frameLayout;
    private Fragment selectorFragment;

    ImageView user_profile_image;

    GoogleSignInClient mGoogleSignInClient;
    private static final int RC_SIGN_IN = 100;

    FirebaseAuth auth;
    FirebaseUser user;

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

        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setTitle("");

        bottomNavigationView = findViewById(R.id.bottom_navigation);
        frameLayout = findViewById(R.id.frame_layout);

        auth = FirebaseAuth.getInstance();
        user = auth.getCurrentUser();

        user_profile_image = findViewById(R.id.user_profile_image);
        getProfileImage();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();

        mGoogleSignInClient = GoogleSignIn.getClient(MainActivity.this,gso);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.home:
                        selectorFragment = new HomeFragment();
                        break;

                    case R.id.explore:
                        selectorFragment = new ExploreFragment();
                        break;

                    case R.id.publish:
                        Toast.makeText(MainActivity.this, "Upload a video", Toast.LENGTH_SHORT).show();
                        break;

                    case R.id.subscriptions:
                        selectorFragment = new SubscriptionsFragment();
                        break;

                    case R.id.library:
                        selectorFragment = new LibraryFragment();
                        break;

                }

                if (selectorFragment != null) {
                    getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, selectorFragment).commit();
                }

                return true;

            }
        });

        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, new HomeFragment()).commit();

        user_profile_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(user !=null){
                    Toast.makeText(MainActivity.this, "User Already Signed In", Toast.LENGTH_SHORT).show();
                }else{
                    showDialog();
                }

            }
        });


    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setCancelable(true);

        ViewGroup viewGroup = findViewById(android.R.id.content);
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_signin_dialogue,viewGroup,false);

        builder.setView(view);

        TextView txt_google_signIn = view.findViewById(R.id.txt_google_signIn);
        txt_google_signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn();
            }
        });
        builder.create().show();
    }

    private void signIn() {
        Intent intent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(intent,RC_SIGN_IN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == RC_SIGN_IN){
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);

            try{
                GoogleSignInAccount account = task.getResult(ApiException.class);

                AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
                auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()){
                            FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

                            HashMap<String,Object> map = new HashMap<>();
                            map.put("username",account.getDisplayName());
                            map.put("email",account.getEmail());
                            map.put("profile",String.valueOf(account.getPhotoUrl()));
                            map.put("uid", firebaseUser.getUid());
                            map.put("search",account.getDisplayName().toLowerCase());

                            DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users");
                            reference.child(firebaseUser.getUid()).setValue(map);
                        }
                        else{
                            Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
            catch(Exception e){
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.notification:
                Toast.makeText(this, "Notification", Toast.LENGTH_SHORT).show();
                break;

            case R.id.search:
                Toast.makeText(this, "Search", Toast.LENGTH_SHORT).show();
                break;

            default:
                return super.onOptionsItemSelected(item);

        }
        return false;
    }

    private void getProfileImage(){
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users");
        reference.child(user.getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.exists()){
                    String p =snapshot.child("profile").getValue().toString();

                    Picasso.get().load(p).placeholder(R.drawable.ic_baseline_account_circle).into(user_profile_image);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();

            }
        });
    }
}

My XML code:我的 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"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/appBar">

        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/toolbar"
            android:background="@color/white"
            app:menu="@menu/toolbar_menu">

            <ImageView
                android:layout_width="70dp"
                android:layout_height="50dp"
                android:src="@drawable/icon1"
                android:adjustViewBounds="true"
                android:id="@+id/icon"/>

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

            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:src="@drawable/ic_baseline_account_circle"
                android:layout_marginStart="190dp"
                android:id="@+id/user_profile_image"/>

        </RelativeLayout>

        </androidx.appcompat.widget.Toolbar>



    </com.google.android.material.appbar.AppBarLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/appBar"
        android:layout_above="@+id/bottom_navigation"
        android:id="@+id/frame_layout"/>


    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        app:menu="@menu/bottom_menu"
        android:layout_alignParentBottom="true"
        app:itemTextColor="@color/black"
        app:itemIconTint="@color/black"
        app:itemRippleColor="@color/cardview_dark_background"
        android:id="@+id/bottom_navigation"
        app:labelVisibilityMode="labeled"/>

</RelativeLayout>

Error in this particular lines
 reference.child(user.getUid()).addValueEventListener(new ValueEventListener() {

and `getProfileImage();

I am new to android can someone please help...will really appretiate我是 android 的新手,有人可以帮忙......真的很感激

If it's referring to the line:如果它指的是该行:

reference.child(user.getUid()).addValueEventListener(new ValueEventListener()

then it's telling you that either "reference" or "user" is null, and you're note checking for it.然后它告诉您“参考”或“用户”是 null,并且您注意检查它。 So, you need to do something like:因此,您需要执行以下操作:

if(reference == null || user == null) return;

right before that line, or alternatively, put in some logic to handle the case of either of those being NULL就在那条线之前,或者,输入一些逻辑来处理其中任何一个是 NULL 的情况

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试在 android studio firebase mainactivity 中的空对象引用上调用虚方法 boolean java.lang.String.equals(java.lang.Object) - Attempt to invoke virtual method boolean java.lang.String.equals(java.lang.Object) on a null object reference in android studio firebase mainactivity 尝试在空对象引用上调用虚拟方法“…………” - Attempt to invoke virtual method '.........' on a null object reference android firebase crashlytics 无法在 null ZA8CFDE6331BD59EB2AC966F8911Z4B6 上调用方法 all() - android firebase crashlytics Cannot invoke method all() on null object 当 object 添加到 firebase - Android Studio 时,应用程序崩溃与 GC - App crash with GC When an object added to firebase - Android Studio 所需参考处不存在 object - No object exists at the desired reference Flutter: PlatformException(error, Invalid document reference. Document references must have an even number of segments, but<x> 有 1,空)</x> - Flutter: PlatformException(error, Invalid document reference. Document references must have an even number of segments, but <x> has 1, null) Firebase function error: Cannot convert undefined or null to object at Function.keys (<anonymous> )</anonymous> - Firebase function error: Cannot convert undefined or null to object at Function.keys (<anonymous>) 谷歌一键登录 null 参考 - Google One Tap Sign In null reference 如何修复在 Android Studio 中运行 iOS 模拟器期间运行 pod install 的错误? - How to fix error running pod install during running iOS simulator in Android Studio? TypeError: 'Reference' object 在 java 脚本中不可迭代 - TypeError: 'Reference' object is not iterable in java script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM