Intento ejecutar mi programa pero obtengo este error. He intentado todo, pero sigo recibiendo este error. No sé por qué sucede esto porque estoy comprobando en HomeActivity.java si le gusta o no a la publicación para evitar el NullPointerException

Error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setImageResource(int)' on a null object reference
        at com.sm.socialmeme.HomeActivity$1.onDataChange(HomeActivity.java:94)
        at com.google.firebase.database.Query$1.onDataChange(Query.java:189)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7562)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Mi base de datos en tiempo real de firebase

HomeActivity.java:

package com.sm.socialmeme;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity {

    // Global variables \\
    DatabaseReference mRef;
    List<PostModel> postList;
    RecyclerView.Adapter recyclerAdapter;
    RecyclerView recyclerView;
    ProgressBar progressBar;
    static String post_id;

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

        final DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");
        final FirebaseAuth mAuth = FirebaseAuth.getInstance();
        final FirebaseUser user = mAuth.getCurrentUser();
        final ImageButton new_post = findViewById(R.id.new_post_btn);
        final ImageButton settings = findViewById(R.id.settingsButton);
        ImageButton like_btn = findViewById(R.id.likeBtn);
        recyclerView = findViewById(R.id.recyclerView);
        mRef = FirebaseDatabase.getInstance().getReference().child("posts");
        progressBar = findViewById(R.id.progressBar4);
        progressBar.setVisibility(View.VISIBLE);
        postList = new ArrayList<>();
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        if (user == null) {
            finish();
            startActivity(new Intent(HomeActivity.this, MainActivity.class));
        }

            mRef.addListenerForSingleValueEvent(new ValueEventListener(){
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        PostModel post = new PostModel();
                        post_id = snapshot.child("id").getValue().toString();
                        post.setImgUrl(snapshot.child("imgUrl").getValue().toString());
                        post.setName(snapshot.child("name").getValue().toString());
                        post.setLikes(snapshot.child("likes").getValue().toString());

                        // check if post is liked from current user or not \\
                        if (snapshot.child("likesList").exists()){
                            if (snapshot.child("likesList").child(user.getDisplayName()).exists()) {
                                // post is liked \\
                                like_btn.setImageResource(R.drawable.like_emoji);
                            }
                        }else{
                            // post is not liked \\
                            like_btn.setImageResource(R.drawable.like_emoji_before);
                        }

                        postList.add(post);

                        // notify adapter when a new item was added \\
                        if (recyclerAdapter != null){
                            recyclerAdapter.notifyDataSetChanged();
                        }
                    }
                    progressBar.setVisibility(View.GONE);
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError){
                    Toast.makeText(HomeActivity.this, "Error: " + databaseError, Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                }
            });

            recyclerAdapter = new RecyclerAdapter(HomeActivity.this,postList);
            recyclerView.setAdapter(recyclerAdapter);
            recyclerAdapter.notifyDataSetChanged();


        settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeActivity.this, SettingsActivity.class));
            }
        });

        new_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeActivity.this, UploadPhotoActivity.class));
            }
        });
    }

    public void clearList(){
        if (postList != null){
            postList.clear();
            if (recyclerAdapter != null){
                recyclerAdapter.notifyDataSetChanged();
            }
        }
        postList = new ArrayList<>();
    }
}

NOTA: hago que like_btn sea global pero no funciona de nuevo.

-1
George Sepetadelis 7 feb. 2021 a las 12:22

2 respuestas

La mejor respuesta

Simplemente acceda a su botón desde recyclerAdapter.java

0
George Sepetadelis 12 mar. 2021 a las 21:34

¿Su archivo post_item.xml está adjunto a la vista Recycler? en caso afirmativo, debe utilizar el escucha de clics.

1
sunny vishwakarma 11 feb. 2021 a las 12:38