我的哈希映射在 Firebase 数据库中没有被实现。

huangapple go评论88阅读模式
英文:

My hashmap is not getting implemented in firebase database

问题

我使用这个哈希映射从一个子节点(Users)传递用户名到另一个子节点(Notes)中的数据库。

在我的应用中,您可以创建和更新笔记。

我希望每次在数据库中创建或更新笔记时,都会添加一个用户名和笔记一起。用户名保存在用户子节点中。

但是,当笔记被创建时,用户名不会显示出来。但是当笔记被更新时,它会被添加到子节点中。

以下是代码:

fAuth = FirebaseAuth.getInstance();
fNotesDatabase = FirebaseDatabase.getInstance().getReference()
                .child("Notes").child(fAuth.getCurrentUser().getUid());
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
current_user_id = fAuth.getCurrentUser().getUid();

btnCreate.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    String title = etTitle.getText().toString().trim();
    String content = etContent.getText().toString().trim();
    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
      createNote(title, content);
      putUsername();
    } else {
      Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
    }
  }
});

private void putUsername() {
  UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
      String username = snapshot.child("username").getValue().toString();
      HashMap usernameMap = new HashMap();
      usernameMap.put("username", username);
      fNotesDatabase.child(noteID).updateChildren(usernameMap);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
    }
  });
}

我无法理解为什么笔记创建时不会添加用户名,但在笔记更新时会添加用户名。

我已经更新了第二个笔记,所以有一个用户名,但当只创建上面的笔记时,用户名不会显示出来。

编辑:

putData方法:

private void putData() {
    if (isExist) {
        fNotesDatabase.child(noteID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("content")) {
                    String title = dataSnapshot.child("title").getValue().toString();
                    String content = dataSnapshot.child("content").getValue().toString();

                    etTitle.setText(title);
                    etContent.setText(content);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

createNote方法:

private void createNote(String title, String content) {
    // ...
}
英文:

I'm using this hashmap to transfer the username from one child(Users) to another(Notes) in database.

In my app you can create as well as update notes.

I want that every time a note is created or updated in the database a username is added along with the note. the username is saved in the users child.

But when the note is created the username doesn't show up. But when the note is updated, it is added in the child.

here is the code:

fAuth = FirebaseAuth.getInstance();
fNotesDatabase = FirebaseDatabase.getInstance().getReference()
.child("Notes").child(fAuth.getCurrentUser().getUid());
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
current_user_id = fAuth.getCurrentUser().getUid();
btnCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title = etTitle.getText().toString().trim();
String content = etContent.getText().toString().trim();
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
createNote(title, content);
putUsername();
} else {
Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
}
}
});
private void putUsername() {
UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String username = snapshot.child("username").getValue().toString();
HashMap usernameMap = new HashMap();
usernameMap.put("username", username);
fNotesDatabase.child(noteID).updateChildren(usernameMap);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}

I'm not able to understand as how come the username is added when the note is updated but not when the note us created.

我的哈希映射在 Firebase 数据库中没有被实现。

I have updated the second note thats why there is a username but when is simply created the upper one there username is not showing.

EDIT

putData method :

     private void putData() {
if (isExist) {
fNotesDatabase.child(noteID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("content")) {
String title = dataSnapshot.child("title").getValue().toString();
String content = dataSnapshot.child("content").getValue().toString();
etTitle.setText(title);
etContent.setText(content);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}

createNote method:

     private void createNote(String title, String content) {
if (fAuth.getCurrentUser() != null) {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
if (isExist) {
Map updateMap = new HashMap();
updateMap.put("title", etTitle.getText().toString().trim());
updateMap.put("content", etContent.getText().toString().trim());
updateMap.put("timestamp", ServerValue.TIMESTAMP);
updateMap.put("date",saveCurrentDate);
fNotesDatabase.child(noteID).updateChildren(updateMap);
SendUsersToPostActivity();
Toast.makeText(this, "Article updated", Toast.LENGTH_SHORT).show();
} else {
final DatabaseReference newNoteRef = fNotesDatabase.push();
final Map noteMap = new HashMap();
noteMap.put("title", title);
noteMap.put("content", content);
noteMap.put("timestamp", ServerValue.TIMESTAMP);
noteMap.put("date",saveCurrentDate);
Thread mainThread = new Thread(new Runnable() {
@Override
public void run() {
newNoteRef.setValue(noteMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(NewNoteActivity.this, "Article Created", Toast.LENGTH_SHORT).show();
SendUsersToPostActivity();
} else {
Toast.makeText(NewNoteActivity.this, "ERROR: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mainThread.start();
}
}
}

答案1

得分: 0

很难确定,但我不清楚您在哪里设置putUsername依赖的noteID值。

总的来说,我建议将createNote更改为接收所有新便笺所需的数据,包括用户名:

btnCreate.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    String title = etTitle.getText().toString().trim();
    String content = etContent.getText().toString().trim();
    if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content) && fAuth.getCurrentUser() != null) {
      UsersRef.child(current_user_id).child("username").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
          String username = snapshot.getValue(String.class);

          createNote(title, content, current_user_id, username);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
          throw error.toException();
        }
      });
    } else {
      Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
    }
  }
});

private void createNote(String title, String content, String uid, String username) {
    Calendar calFordDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(calFordDate.getTime());

    Map updateMap = new HashMap();
    updateMap.put("title", title);
    updateMap.put("content", content);
    updateMap.put("timestamp", ServerValue.TIMESTAMP);
    updateMap.put("date", saveCurrentDate);
    updateMap.put("uid", uid);
    updateMap.put("username", username);

    final DatabaseReference noteRef = isExist ? fNotesDatabase.push() : fNotesDatabase.child(noteID);

    noteRef.updateChildren(noteMap).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Toast.makeText(NewNoteActivity.this, "Article " + (isExists ? "updated" : "created"), Toast.LENGTH_SHORT).show();
                SendUsersToPostActivity();
            } else {
                Toast.makeText(NewNoteActivity.this, "ERROR: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });
}

与您的代码相比,此代码的一些更改:

  • 在创建新便笺之前查找用户名。为此使用addListenerForSingleValueEvent,以确保每次按钮单击只执行一次。
  • 只加载用户配置文件的username子项,因为这是您使用的全部内容。
  • 使用传递给createNote的值,而不是从UI视图重新计算它们。
  • 只有一个写入数据库的操作,因为updateChildren也适用于创建初始数据。
  • 无需在新线程上运行Firebase的setValue调用,因为Firebase已经在主线程之外运行它。
  • 请不要将onCancelled留空,因为它可能会隐藏重要的错误消息。
英文:

It's hard to be certain, but I don't see where you set the noteID value that putUsername depends on.

In general though, I'd recommend changing createNote to take all the data that it needs for the new note, including the user name:

btnCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title = etTitle.getText().toString().trim();
String content = etContent.getText().toString().trim();
if (!TextUtils.isEmpty(title) &amp;&amp; !TextUtils.isEmpty(content) &amp;&amp; fAuth.getCurrentUser() != null) {
UsersRef.child(current_user_id).child(&quot;username&quot;).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
String username = snapshot.getValue(String.class);
createNote(title, content, current_user_id, username);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException()
}
});
} else {
Snackbar.make(view, &quot;Fill empty fields&quot;, Snackbar.LENGTH_SHORT).show();
}
}
});
private void createNote(String title, String content, String uid, String username) {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat(&quot;dd-MMMM-yyyy&quot;);
saveCurrentDate = currentDate.format(calFordDate.getTime());
Map updateMap = new HashMap();
updateMap.put(&quot;title&quot;, title);
updateMap.put(&quot;content&quot;, content);
updateMap.put(&quot;timestamp&quot;, ServerValue.TIMESTAMP);
updateMap.put(&quot;date&quot;,saveCurrentDate);
updateMap.put(&quot;uid&quot;,uid);
updateMap.put(&quot;username&quot;,username);
final DatabaseReference noteRef = isExist ? fNotesDatabase.push() : fNotesDatabase.child(noteID);
noteRef.updateChildren(noteMap).addOnCompleteListener(new OnCompleteListener&lt;Void&gt;() {
@Override
public void onComplete(@NonNull Task&lt;Void&gt; task) {
if (task.isSuccessful()) {
Toast.makeText(NewNoteActivity.this, &quot;Article &quot;+(isExists ? &quot;updated&quot; : &quot;created&quot;), Toast.LENGTH_SHORT).show();
SendUsersToPostActivity();
} else {
Toast.makeText(NewNoteActivity.this, &quot;ERROR: &quot; + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}

Some of the changes in this code versus yours:

  • Looks up the user name before creating the new note. Uses a addListenerForSingleValueEvent for this, to ensure we only do this once for every button click.
  • Only loads the username child of the user profile, since that's all you use.
  • Use the values you pass into createNote instead of recalculating them from the UI views.
  • Only has a single write to the database, as updateChildren works fine for creating the initial data too.
  • There is no need to run the Firebase setValue call on a new thread, as Firebase runs it off the main thread already.
  • Please don't leave onCancelled empty, as it may hide important error messages.

huangapple
  • 本文由 发表于 2020年8月24日 17:52:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63558649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定