Home > Mobile >  Android studio null object reference error
Android studio null object reference error

Time:08-18

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 my java code

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 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

CodePudding user response:

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. 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

  • Related