Reputation: 139
I want to make this structure in my Cloud Firestore of a Post: I want to make this structure in my Cloud Firestore of a Post:
Users
|
|-> UserId
|
|-> OneUserPosts
|
|->PostId
|
|-> PostContent
Comment 1
Comment 2
Below is the activity where i want to create a post: How can i give id to my post ?
public class Add_Post extends AppCompatActivity {
EditText posttext;
FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__post);
user = FirebaseAuth.getInstance().getCurrentUser();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
getSupportActionBar().setDisplayShowHomeEnabled(true);
try {
actionBar.setTitle("Write Your Post");
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}catch (NullPointerException e){}
posttext = findViewById(R.id.PostTextTextMultiLine);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.addpostmenu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.POST:
savepost();
break;
}
return super.onOptionsItemSelected(item);
}
private void savepost() {
String Post = posttext.getText().toString();
if (Post.length()<5){
Toast.makeText(this, "Please enter at least 10 words ", Toast.LENGTH_SHORT).show();
}
else{
try {
CollectionReference postref = FirebaseFirestore.getInstance()
.collection("Users").document(user.getUid()).collection("OneUserPost");
postref.add(new posttextlist(Post));
Toast.makeText(this, "Successfully Posted", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(this,MainActivity.class));
}catch (NullPointerException e){}
}
}
}
Please solve my problem. I searched everywhere but i didn't get answer. Please solve my problem. I searched everywhere but i didn't get answer.
Upvotes: 1
Views: 55
Reputation: 138869
When you are using the following line of code:
postref.add(new posttextlist(Post));
CollectionReference's add(Object data):
Adds a new document to this collection with the specified data, assigning it a document ID automatically.
If don't need this behavior, then you should use DocumentReference's set(Object data):
Overwrites the document referred to by this DocumentReference.
So your code should like this:
CollectionReference postref = FirebaseFirestore.getInstance()
.collection("Users").document(user.getUid())
.collection("OneUserPost");
String id = postref.getId(); //Do what you need to do with this id
postref.document(id).set(new posttextlist(Post));
Upvotes: 2