当我点击适配器中的一个布局时,我正在运行一个事务,但是当我点击该布局时,事务成功运行。但它会在我的RecyclerView
中创建另一个项目。我尝试在事务内部使用notifydatasetChanged(),但是会导致错误:
CalledFromWrongThreadException: Only the original thread that created a view
hierarchy can touch its views.
然后我尝试将 notifyDataSetChanged() 放在事务之外,但它没有起作用。以下是我的操作步骤:
holder.follow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
DatabaseReference mWorkDatabase =
FirebaseDatabase.getInstance().getReference()
.child("WorkforWorkMen").child(work_id).child("follower");
mWorkDatabase.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData
mutableData) {
if(holder.followText.getText().equals("Follow")) {
holder.followText.setText("Following");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String current_user =
mAuth.getCurrentUser().getUid();
DatabaseReference mFollowingDatabase =
FirebaseDatabase.getInstance().getReference()
.child("WorkFollowing").child(current_user).child(work_id);
final Map fol = new HashMap();
fol.put("follower",work_id);
mFollowingDatabase.setValue(fol);
mutableData.setValue
(Integer.parseInt(mutableData.getValue().toString()) + 1);
}
else {
holder.followText.setText("Follow");
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String current_user =
mAuth.getCurrentUser().getUid();
DatabaseReference mFollowingDatabase =
FirebaseDatabase.getInstance().getReference()
.child("WorkFollowing").child(current_user).child(work_id);
mFollowingDatabase.setValue(null);
mutableData.setValue(Integer
.parseInt(mutableData.getValue().toString()) - 1);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError,
boolean b, DataSnapshot dataSnapshot) {
Toast.makeText(context,"error on complete"+
String.valueOf(databaseError), Toast.LENGTH_SHORT).show();
Log.i("eror here", "onComplete:
"+String.valueOf(databaseError));
}
});
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "here",
Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
}
});
我觉得当我把数据添加到列表中时,关注者数量的变化导致它添加了一个新项目,但我不确定。
private void loadMessages(){
if(keys.size() == 0){
messagesList.clear();
Toast.makeText(getContext(), " size zero no results found",
Toast.LENGTH_SHORT).show();
}
else {
messagesList.clear();
for (int i = 0; i < 5; i++) {
if (i>=keys.size()){
Toast.makeText(getContext(), "list is less than 5 item",
Toast.LENGTH_SHORT).show();
}
else {
listPos = i;
String id = keys.get(i);
mWorkDatabase.child(id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String messageKey = dataSnapshot.getKey();
NewWork message = dataSnapshot.getValue(NewWork.class);
itemPos++;
messagesList.add(message);
mAdapter.notifyDataSetChanged();
mRecyclerView2.scrollToPosition(messagesList.size() - 1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
}