用Firebase创建一个计数器

时间:2018-06-26 14:57:58

标签: android firebase firebase-realtime-database

我有一个recyclerview,可将mysql数据库中的数据加载到应用程序视图中。我在这个rec​​yclerview的每个元素上尝试一个“赞”按钮,为此,我使用了 Firebase实时数据库。我的代码没有显示错误,但是当我单击“赞”按钮时,我的应用程序突然停止了

这是我的recyclerview适配器。

public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private DatabaseReference mDatabase;
public ImageView starView;
public TextView numStarsView;
private Context context;
private LayoutInflater inflater;
List<Data> data = Collections.emptyList();
Data current;
int currentPos = 0;

// create constructor to innitilize context and data sent from MainActivity
public Adapter(Context context, List<Data> data) {
    this.context = context;
    inflater = LayoutInflater.from(context);
    this.data = data;
}

public void bindToPost(Data current, View.OnClickListener starClickListener) {
    numStarsView.setText(String.valueOf(current.starCount));

    starView.setOnClickListener(starClickListener);
}
// Inflate the layout when viewholder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.container, parent, false);
    MyHolder holder = new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    mDatabase = FirebaseDatabase.getInstance().getReference().child("stars");
    final DatabaseReference postRef = mDatabase;
    final String postKey = postRef.getKey();
    final Data current = data.get(position);
    // Get current position of item in recyclerview to bind data and assign values from list
    MyHolder myHolder = (MyHolder) holder;
    myHolder.textFishName.setText(current.catName);
    myHolder.textSize.setText(current.sizeName);
    myHolder.textSize.setVisibility(View.GONE);
    myHolder.textType.setText(current.fishName);
    myHolder.textType.setTextColor(Color.BLACK);
    myHolder.textPrice.setText("" + current.price + "");
    myHolder.textPrice.setVisibility(View.GONE);
    myHolder.textPrice.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

    if (current.stars.containsKey(getUid())) {
        starView.setImageResource(R.drawable.ic_toggle_star_24);

    } else {
        starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
    }
    // Bind Post to ViewHolder, setting OnClickListener for the star button
    bindToPost(current, new View.OnClickListener() {
        @Override
        public void onClick(View starView) {
            // Need to write to both places the post is stored
            DatabaseReference globalPostRef = mDatabase.child("posts").child(postRef.getKey());
            DatabaseReference userPostRef = mDatabase.child("user-posts").child(current.uid).child(postRef.getKey());

            // Run two transactions
            onStarClicked(globalPostRef);
            onStarClicked(userPostRef);
        }
    });
    //load image into imageview using glide
    Glide.with(context).load("http://192.168.43.196/vibe2/images/" + current.fishImage)
            .placeholder(R.drawable.ic_menu_camera)
            .error(R.drawable.ic_menu_camera)
            .into(myHolder.ivFish);

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}


class MyHolder extends RecyclerView.ViewHolder {

    TextView textFishName;
    ImageView ivFish;
    TextView textSize;
    TextView textType;
    TextView textPrice;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        starView = itemView.findViewById(R.id.star);
        numStarsView = itemView.findViewById(R.id.post_num_stars);
        textFishName = (TextView) itemView.findViewById(R.id.textFishName);
        ivFish = (ImageView) itemView.findViewById(R.id.ivFish);
        textSize = (TextView) itemView.findViewById(R.id.textSize);
        textType = (TextView) itemView.findViewById(R.id.textType);
        textPrice = (TextView) itemView.findViewById(R.id.textPrice);
    }
}

public String getUid() {
    return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
// [START post_stars_transaction]
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}

这是我的日志:

 java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
                                                                        at com.google.firebase.database.DatabaseReference.child(Unknown Source)
                                                                        at cm.mavis.myapplication.Adapter$1.onClick(Adapter.java:92)
                                                                        at android.view.View.performClick(View.java:4475)
                                                                        at android.view.View$PerformClick.run(View.java:18796)
                                                                        at android.os.Handler.handleCallback(Handler.java:730)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                        at android.os.Looper.loop(Looper.java:137)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5455)
                                                                        at java.lang.reflect.Method.invokeNative(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:525)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
                                                                        at dalvik.system.NativeStart.main(Native Method)

任何帮助将不胜感激。

0 个答案:

没有答案