So I have Firebase Database that looks like this:
{
"lists" : {
"-KZh-vvPcPGVqC22k2Bo" : {
"dateCreated" : "2016-12-23",
"listDescription" : "My Christmas Wish List for 2016",
"listTitle" : "William's Christmas List",
"user" : "ztGAx7eplGeZgdjqnegrtbfuyUy2"
}
},
"users" : {
"8pJJuscerZRGdwGGImnWlCKSEed2" : {
"email" : "example#example.com",
"name" : "Alyson"
},
"ztGAx7eplGeZgdjqnegrtbfuyUy2" : {
"email" : "example#example.com",
"name" : "William"
}
}
}
I am trying to only return the lists objects where the user field equals the UID of the logged in user. That way the logged in user gets all his lists. But I am having trouble querying the data that is in lists because of the unique key that is generated by push() which I use to append to lists whenever a user creates a new list object. How do I go about querying lists so that I get only the lists that match the UID of the signed in user? I have this so far
package com.fanciestw.listpro;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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;
public class allList extends AppCompatActivity {
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mList = mDatabase.getReference().child("lists");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_list);
mAuthStateListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null) {
Log.d("User Activity", "User Signed In");
} else {
Log.d("User Activity", "User Signed Out");
signout(getCurrentFocus());
}
}
};
mList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
List newList = dataSnapshot.getValue(List.class);
Log.d("List Returned", newList.listTitle + " " + newList.listDescription);
updateList();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
updateList();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
Log.d("allList Activity", "onStart");
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
public void onStop(){
super.onStop();
Log.d("allList Activity", "onStop");
if(mAuthStateListener != null) mAuth.removeAuthStateListener(mAuthStateListener);
}
public void addNewList(View view){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add New List");
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.add_new_list_form, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogView);
// Set up the buttons
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = ((EditText)dialogView.findViewById(R.id.add_list_title)).getText().toString();
String desc = ((EditText)dialogView.findViewById(R.id.add_list_desc)).getText().toString();
Log.d("New List Details", title + ", " + desc);
//TODO::Store created list with title and desc in database
List newList = new List(title, desc, mAuth.getCurrentUser().getUid());
String newListID = mList.push().getKey();
mList.child(newListID).setValue(newList);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void updateList(){
//Want to get lists where lists.user == firebaseAuth.getCurrentUser().UID();
}
public void signout(View view){
mAuth.signOut();
Intent intent = new Intent(this, login.class);
startActivity(intent);
}
}
Declare
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private String userId = null;
Initialize
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
userId = mCurrentUser.getUid().toString();
String UIDstring = (String) dataSnapshot.child("users").getValue();
Determine
if (userId.equals(UIDstring)) {
//true
} else {
// false
}
Related
I am currently having a trouble on deleting a specific data from my firebase. So basically I have recyclerview wherein my datas are displayed and I have a button in each data display there and that's EDIT button. Whenever I try to click the EDIT button it should intent me to another activity with the same data displayed in the recyclerview and there's a another button displayed there and that's DELETE button. But whenever I try to click the delete button, it deletes all the data from the child. I only need to DELETE the selected ID/Data that is passing when intent occurs.
Edit.
EditResearch.java
package com.example.citeresearchrepository.AdminPackage;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class EditResearchActivity extends AppCompatActivity {
EditText editfilehandler_et,editrepo_title,editrepo_description,editrepo_currentdate;
Button editrepo_savebtn;
ImageView backbtn_editresearch;
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
StorageReference storageReference;
String researchtitle,researchdate,researchname,researchdescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_research);
editfilehandler_et = findViewById(R.id.editfilehandler_et);
editrepo_title = findViewById(R.id.editrepo_title);
editrepo_description = findViewById(R.id.editrepo_description);
editrepo_currentdate = findViewById(R.id.editrepo_currentdate);
editrepo_savebtn = findViewById(R.id.editrepo_savebtn);
backbtn_editresearch = findViewById(R.id.backbtn_editresearch);
Intent intent = getIntent();
researchtitle = intent.getStringExtra("researchtitle");
researchdate = intent.getStringExtra("researchdate");
researchname = intent.getStringExtra("researchname");
researchdescription = intent.getStringExtra("researchdescription");
databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRepository");
storageReference = FirebaseStorage.getInstance().getReference();
editfilehandler_et.setText(researchname);
editrepo_title.setText(researchtitle);
editrepo_currentdate.setText(researchdate);
editrepo_description.setText(researchdescription);
editrepo_savebtn.setEnabled(false);
editfilehandler_et.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectPDF();
}
});
/* Update Files */
backbtn_editresearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AdminResearchRepoActivity.class));
}
});
}
private void selectPDF(){
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "PDF FILE SELECTED"), 12);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==12 && resultCode == RESULT_OK && data!=null && data.getData()!=null){
editrepo_savebtn.setEnabled(true);
editfilehandler_et.setText(data.getDataString().substring(data.getDataString().lastIndexOf("/") + 1));
editrepo_savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePreviousImage();
uploadResearch(data.getData());
}
});
}
}
private void deleteSelectedRow(){
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("ResearchRepository");
databaseReference.removeValue();
}
private void uploadResearch(Uri data) {
final String filecapture = editfilehandler_et.getText().toString();
final String researchtitle = editrepo_title.getText().toString();
final String researchdescription = editrepo_description.getText().toString();
final String researchtimeline = editrepo_currentdate.getText().toString();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("File Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("ResearchRepository" +System.currentTimeMillis() + ".pdf");
reference.putFile(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while(!uriTask.isComplete());
Uri uri = uriTask.getResult();
ResearchRepository researchRepository = new ResearchRepository(filecapture,researchtitle,researchdescription,researchtimeline,uri.toString());
databaseReference.child(databaseReference.push().getKey()).setValue(researchRepository);
Toast.makeText(EditResearchActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
editfilehandler_et.setText("");
editrepo_title.setText("");
editrepo_currentdate.setText("");
editrepo_description.setText("");
startActivity(new Intent(getApplicationContext(), AdminResearchRepoActivity.class));
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount();
progressDialog.setMessage("File Uploading..."+(int)progress+"%");
}
});
}
private void deletePreviousImage(){
StorageReference reference = FirebaseStorage.getInstance().getReference().child(researchtitle);
reference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(EditResearchActivity.this, "Previous File Deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditResearchActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
AdminResearchRepoActivity.java
package com.example.citeresearchrepository.AdminPackage;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.citeresearchrepository.AdminAdapter.AdminRepoAdapter;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import com.example.citeresearchrepository.ViewHolder.AdminResearchRepositoryViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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.ValueEventListener;
import java.util.ArrayList;
public class AdminResearchRepoActivity extends AppCompatActivity {
ImageView adminrepo_backbtn;
RecyclerView reporecycler;
FloatingActionButton addresearch_btn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
AdminRepoAdapter adminRepoAdapter;
ArrayList<ResearchRepository> researchRepositoryArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_research_repo);
// Buttons
adminrepo_backbtn = findViewById(R.id.backbtn_adminrepo);
addresearch_btn = findViewById(R.id.addresearch_btn);
addresearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddResearchActivity.class));
}
});
adminrepo_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
// Recycler
reporecycler = findViewById(R.id.reporecycler);
reporecycler.setLayoutManager(new LinearLayoutManager(this));
// Firebase Connection
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("ResearchRepository");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
researchRepositoryArrayList = new ArrayList<ResearchRepository>();
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
ResearchRepository researchRepository = dataSnapshot.getValue(ResearchRepository.class);
researchRepositoryArrayList.add(researchRepository);
}
adminRepoAdapter = new AdminRepoAdapter(AdminResearchRepoActivity.this,researchRepositoryArrayList);
reporecycler.setAdapter(adminRepoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminResearchRepoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
AdminRepoAdapter.java
package com.example.citeresearchrepository.AdminAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.citeresearchrepository.AdminPackage.EditResearchActivity;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class AdminRepoAdapter extends RecyclerView.Adapter<AdminRepoAdapter.AdminViewHolder> {
Context context;
ArrayList<ResearchRepository> researchRepositories;
public AdminRepoAdapter(Context c, ArrayList<ResearchRepository> repositories){
context = c;
researchRepositories = repositories;
}
#NonNull
#Override
public AdminViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminViewHolder(LayoutInflater.from(context).inflate(R.layout.admineditrepo_row,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminViewHolder holder, final int position) {
holder.researchtitle_view.setText(researchRepositories.get(position).getResearchtitle());
holder.researchdate_view.setText(researchRepositories.get(position).getResearchtimeline());
holder.researchname_view.setText(researchRepositories.get(position).getFilecapture());
holder.researchdescription_view.setText(researchRepositories.get(position).getResearchdescription());
holder.btnpdf_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, EditResearchActivity.class);
intent.putExtra("researchtitle",researchRepositories.get(position).getResearchtitle());
intent.putExtra("researchdate",researchRepositories.get(position).getResearchtimeline());
intent.putExtra("researchname",researchRepositories.get(position).getFilecapture());
intent.putExtra("researchdescription",researchRepositories.get(position).getResearchdescription());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return researchRepositories.size();
}
class AdminViewHolder extends RecyclerView.ViewHolder{
public TextView researchtitle_view,researchdate_view,researchname_view,researchdescription_view,researchtitle_url;
public Button btnpdf_edit;
public AdminViewHolder (#NonNull View itemView) {
super(itemView);
researchtitle_view = itemView.findViewById(R.id.researchtitle_view);
researchdate_view = itemView.findViewById(R.id.researchdate_view);
researchname_view = itemView.findViewById(R.id.researchname_view);
researchdescription_view = itemView.findViewById(R.id.researchdescription_view);
researchtitle_url = itemView.findViewById(R.id.researchtitle_view);
btnpdf_edit = itemView.findViewById(R.id.btnpdf_edit);
}
}
}
ResearchRepository.class
package com.example.citeresearchrepository.Model;
public class ResearchRepository {
public String filecapture;
public String researchtitle;
public String researchdescription;
public String researchtimeline;
public String url;
public ResearchRepository() {
}
public ResearchRepository(String filecapture, String researchtitle, String researchdescription, String researchtimeline, String url) {
this.filecapture = filecapture;
this.researchtitle = researchtitle;
this.researchdescription = researchdescription;
this.researchtimeline = researchtimeline;
this.url = url;
}
public String getFilecapture() {
return filecapture;
}
public void setFilecapture(String filecapture) {
this.filecapture = filecapture;
}
public String getResearchtitle() {
return researchtitle;
}
public void setResearchtitle(String researchtitle) {
this.researchtitle = researchtitle;
}
public String getResearchdescription() {
return researchdescription;
}
public void setResearchdescription(String researchdescription) {
this.researchdescription = researchdescription;
}
public String getResearchtimeline() {
return researchtimeline;
}
public void setResearchtimeline(String researchtimeline) {
this.researchtimeline = researchtimeline;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Here's my realtime-database : https://i.stack.imgur.com/lML0i.png
I just wanna delete the red box.
From what I see you are getting an instance to only the ResearchRepository node instead of the specific child node that you want to delete. You need to keep track of the unique IDs you are pushing on to the ResearchRepository node and pass it in the intent as well;
Add the code to pass the unique ID of the ResearchRepository child you want to delete.
Then do this in your new activity where the delete code is present.
String childToDelete; //retrieve the value from the intent
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRepository").child(childToDelete);
databaseReference.removeValue();
This should do it if that is your purpose.
Edit 1:-
I got your point. Please follow the approach I will be showing now and it will work for you.
Edit your class as shown below:-
AdminRepoAdapter.java
public class AdminRepoAdapter extends RecyclerView.Adapter<AdminRepoAdapter.AdminViewHolder> {
Context context;
Map<String,ResearchRepository> researchRepositories;
ArrayList<ResearchRepository> researchRepositoriesHolder;
public AdminRepoAdapter(Context c, Map<String,ResearchRepository> repositories){
context = c;
researchRepositories = repositories;
researchRepositoriesHolder = new ArrayList<>(researchRepositories.values());
}
#NonNull
#Override
public AdminViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminViewHolder(LayoutInflater.from(context).inflate(R.layout.admineditrepo_row,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminViewHolder holder, final int position) {
holder.researchtitle_view.setText(researchRepositoriesHolder.get(position).getResearchtitle());
holder.researchdate_view.setText(researchRepositoriesHolder.get(position).getResearchtimeline());
holder.researchname_view.setText(researchRepositoriesHOlder.get(position).getFilecapture());
holder.researchdescription_view.setText(researchRepositoriesHolder.get(position).getResearchdescription());
holder.btnpdf_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map.Entry<String,ResearchRepository> entry = null; //Just for initialization
for (Map.Entry<String,ResearchRepository> var : researchRepositories.entrySet()) {
if(var.getValue() == researchRepositoriesHolder.get(position)){
entry = var;
break;
}
}
Intent intent = new Intent(context, EditResearchActivity.class);
intent.putExtra("researchtitle",entry.getValue().getResearchtitle());
intent.putExtra("researchdate",entry.getValue().getResearchtimeline());
intent.putExtra("researchname",entry.getValue().getFilecapture());
intent.putExtra("researchdescription",entry.getValue().getResearchdescription());
intent.putExtra("childNodeKey",entry.getKey());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return researchRepositoriesHolder.size();
}
class AdminViewHolder extends RecyclerView.ViewHolder{
public TextView researchtitle_view,researchdate_view,researchname_view,researchdescription_view,researchtitle_url;
public Button btnpdf_edit;
public AdminViewHolder (#NonNull View itemView) {
super(itemView);
researchtitle_view = itemView.findViewById(R.id.researchtitle_view);
researchdate_view = itemView.findViewById(R.id.researchdate_view);
researchname_view = itemView.findViewById(R.id.researchname_view);
researchdescription_view = itemView.findViewById(R.id.researchdescription_view);
researchtitle_url = itemView.findViewById(R.id.researchtitle_view);
btnpdf_edit = itemView.findViewById(R.id.btnpdf_edit);
}
}
}
AdminResearchRepoActivity.java
public class AdminResearchRepoActivity extends AppCompatActivity {
ImageView adminrepo_backbtn;
RecyclerView reporecycler;
FloatingActionButton addresearch_btn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
AdminRepoAdapter adminRepoAdapter;
Map<String, ResearchRepository> researchRepositoryMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_research_repo);
// Buttons
adminrepo_backbtn = findViewById(R.id.backbtn_adminrepo);
addresearch_btn = findViewById(R.id.addresearch_btn);
addresearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddResearchActivity.class));
}
});
adminrepo_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
// Recycler
reporecycler = findViewById(R.id.reporecycler);
reporecycler.setLayoutManager(new LinearLayoutManager(this));
// Firebase Connection
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("ResearchRepository");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
researchRepositoryMap = (Map)snapshot.getValue()
adminRepoAdapter = new AdminRepoAdapter(AdminResearchRepoActivity.this,researchRepositoryMap);
reporecycler.setAdapter(adminRepoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminResearchRepoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
In this way when you pass a Intent from your AdminRepoAdapter to EditResearchActivity you will have the key stored as 'childNodeKey' in your intent.
You can then follow the procedure I mentioned before the edit to delete using the key you got from here.
I have some weird situation:
I have 3 activities - MainFeed, From where I can post some image with description and then comment on it,
PostActivity, From where I actually upload an image and write some words and then it automatically updated in MainFeed
CommentActivity, From where I just write a comment to relevant post.
The problem is - when I am just scrolling through posts and click to write comment and write one - everything is being updated fine, but once I upload new POST, and then comment on any post, when I click on Update comment button I just moved to Postactivity... I need to click android back button and then I can see all my comments.
As I understand, the postactivity is not closed with finish() method.
Any help, please!!
package com.example.android.bluesky.Posts;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.bluesky.Login.LoginActivity;
import com.example.android.bluesky.Login.RegisterActivity;
import com.example.android.bluesky.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
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.squareup.picasso.Picasso;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import de.hdodenhof.circleimageview.CircleImageView;
import static java.nio.file.Paths.get;
public class CommentsActivity extends AppCompatActivity
{
private ImageView PostCommentButton,BackButton;
private EditText CommentInputText;
private RecyclerView CommentsList;
private String Post_Key, current_user_id;
private long countPosts;
private DatabaseReference UsersRef,PostsRef;
private FirebaseAuth mAuth;
private String currentUserID, CommentRandomKey,post_user_uid_for_comment;
private int PostIntKeyFromMain;
private String comment_user_uid;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
Post_Key=getIntent().getExtras().get("Post_Key").toString();
PostIntKeyFromMain =getIntent().getIntExtra("PostIntKey",5);
post_user_uid_for_comment=getIntent().getExtras().get("post_user_uid_for_comment").toString(); //Coming from mainfeed - commentPostButton
Toast.makeText(this, "received: "+post_user_uid_for_comment, Toast.LENGTH_SHORT).show();
UsersRef= FirebaseDatabase.getInstance().getReference().child("users");
mAuth=FirebaseAuth.getInstance();
current_user_id=mAuth.getCurrentUser().getUid();
currentUserID = mAuth.getCurrentUser().getUid();
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts").child(Post_Key).child("comments");
BackButton=(ImageView) findViewById(R.id.backArrow) ;
CommentsList = (RecyclerView) findViewById(R.id.comment_list);
CommentsList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager= new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
CommentsList.setLayoutManager(linearLayoutManager);
CommentInputText=(EditText) findViewById(R.id.comment_input);
PostCommentButton=(ImageView) findViewById(R.id.post_comment_button1);
BackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(CommentsActivity.this,MainFeedActivity.class);
intent.putExtra("PostIntKeyFromComment", PostIntKeyFromMain);
startActivity(intent);
finish();
}
});
PostCommentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
String userFullname=dataSnapshot.child("name").getValue().toString().toLowerCase()+"."+dataSnapshot.child("lastname").getValue().toString();
String userProfileimage=dataSnapshot.child("profileimage").getValue().toString();
ValidateComment(userFullname,userProfileimage);
CommentsList.smoothScrollToPosition(0);
CommentInputText.setText("");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
protected void onStart()
{
super.onStart();
PostsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
countPosts = dataSnapshot.getChildrenCount();
countPosts=100000-countPosts;
} else {
countPosts = 100000;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query SortCommentsInDecendingOrder = PostsRef.orderByChild("counterC");
FirebaseRecyclerAdapter<Comments,CommentsViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Comments, CommentsViewHolder>
(
Comments.class,
R.layout.all_comments_layout,
CommentsViewHolder.class,
SortCommentsInDecendingOrder
) {
#Override
protected void populateViewHolder(CommentsViewHolder viewHolder, Comments model, int position)
{
final String CommentKey = getRef(position).getKey();
//viewHolder.setUsername(model.getUsername());
viewHolder.setComment(model.getComment());
viewHolder.setDate(model.getDate());
viewHolder.setTime(model.getTime());
viewHolder.setLastname(model.getLastname());
viewHolder.setProfileimage(model.getProfileimage());
}
};
CommentsList.setAdapter(firebaseRecyclerAdapter);
}
public static class CommentsViewHolder extends RecyclerView.ViewHolder
{
View mView;
String currentUserID;
public CommentsViewHolder(View itemView) {
super(itemView);
mView=itemView;
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public void setLastname(String lastname)
{
TextView myUserName=(TextView) mView.findViewById(R.id.comment_username1);
myUserName.setText("# " + lastname);
}
public void setComment(String comment)
{
TextView myComment=(TextView) mView.findViewById(R.id.comment_text);
myComment.setText(comment);
}
public void setDate(String date)
{
TextView myDate=(TextView) mView.findViewById(R.id.comment_date);
myDate.setText(date);
}
public void setTime(String time)
{
TextView myTime=(TextView) mView.findViewById(R.id.comment_time);
myTime.setText(time);
}
public void setProfileimage(String profileimage) {
CircleImageView myProfileImage = (CircleImageView) mView.findViewById(R.id.comment_profile_image);
Picasso.get().load(profileimage).into(myProfileImage);
}
}
private void ValidateComment(String userFullname, String userProfileimage, String userCountryimage,String userPartyimage )
{
String commentText=CommentInputText.getText().toString();
if(TextUtils.isEmpty(commentText))
{
Toast.makeText(this, "Please write text", Toast.LENGTH_SHORT).show();
}
else
{
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
final String saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calForTimeSS = Calendar.getInstance();
SimpleDateFormat currentTimeSS = new SimpleDateFormat("HH:mm:ss");
final String saveCurrentTimeSS = currentTimeSS.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
final String saveCurrentTime = currentTime.format(calForDate.getTime());
final String RandomKey =current_user_id+ saveCurrentDate + saveCurrentTimeSS;
CommentRandomKey=RandomKey;
HashMap commentsMap = new HashMap();
commentsMap.put("uid",current_user_id);
commentsMap.put("comment",commentText);
commentsMap.put("date",saveCurrentDate);
commentsMap.put("time",saveCurrentTime);
commentsMap.put("lastname",userFullname);
commentsMap.put("counterC", countPosts);
commentsMap.put("profileimage", userProfileimage);
PostsRef.child(RandomKey).updateChildren(commentsMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful())
{
Toast.makeText(CommentsActivity.this, "You have commented successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(CommentsActivity.this, "Error occured, try again...", Toast.LENGTH_SHORT).show();
}
}
});
CommentsList.smoothScrollToPosition(0);
// Toast.makeText(CommentsActivity.this, ""+CurrentCommentKey, Toast.LENGTH_SHORT).show();
}
}
}
package com.example.android.bluesky.Posts;
import java.lang.Math;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.android.bluesky.R;
import com.example.android.bluesky.Utils.SquareImageView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
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.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class PostActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ProgressDialog loadingBar;
//private ImageButton SelectPostImage;
private SquareImageView SelectPostImage;
private FloatingActionButton DonePostButton;
private FloatingActionButton UpdatePostButton;
private EditText PostDescription;
private long countPosts;
ImageView PartyImage;
private static final int Gallery_Pick = 1;
private Uri ImageUri;
private String Description;
//referense to store in firebase storage
private StorageReference PostsImagesReference;
private DatabaseReference UsersRef, PostsRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, saveCurrentTime,saveCurrentTimeS, postRandomName, downloadUrl, current_user_id;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
//This two lines is to get current user from database
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
PostsImagesReference = FirebaseStorage.getInstance().getReference();
UsersRef = FirebaseDatabase.getInstance().getReference().child("users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
UserPhotosRef=FirebaseDatabase.getInstance().getReference().child("user_photos");
PhotosRef=FirebaseDatabase.getInstance().getReference().child("photos");
DonePostButton = (FloatingActionButton) findViewById(R.id.done_post_button);
SelectPostImage = (SquareImageView) findViewById(R.id.select_post_image);
UpdatePostButton = (FloatingActionButton) findViewById(R.id.update_post_button);
PostDescription = (EditText) findViewById(R.id.post_description);
PartyImage=(ImageView) findViewById(R.id.user_party_flag);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Update post");
UpdatePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSelectImageClick(SelectPostImage);
// OpenGallery();
}
});
//UpdatePostButton.setOnClickListener(new View.OnClickListener() {
DonePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ValidatePostInfo();
}
});
}
public void onSelectImageClick(View view) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setActivityTitle("My Crop")
//.setCropShape(CropImageView.CropShape.RECTANGLE)
.setCropMenuCropButtonTitle("Done")
//.setMaxCropResultSize(1000, 1000)
.setMinCropWindowSize(2000, 2000)
.setMinCropResultSize(2000, 2000)
.setRequestedSize(800, 800)
.setAspectRatio(1,1)
.setCropMenuCropButtonIcon(R.drawable.ic_checkmark)
.start(this);
//.startActivityForResult(galleryIntent,Gallery_Pick);
// / .start(getContext(),this);
}
private void ValidatePostInfo() {
//This Description var is using only in this method, there is another one for global use
Description = PostDescription.getText().toString();
if (ImageUri == null) {
Toast.makeText(this, "Please select post image", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Description)) {
Toast.makeText(this, "Please say something about your image", Toast.LENGTH_SHORT).show();
} else {
loadingBar.setTitle("Add new post");
loadingBar.setMessage("Please wait, while we are updating your new post...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
//Code for storing image in firebase storage and database
StoringImageToFirebaseStorage();
}
}
private void StoringImageToFirebaseStorage() {
//assigning random uid for image based on date and time
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
saveCurrentTime = currentTime.format(calForDate.getTime());
Calendar calForTimeS = Calendar.getInstance();
SimpleDateFormat currentTimeS = new SimpleDateFormat("HH:mm:ss");
saveCurrentTimeS = currentTime.format(calForDate.getTime());
postRandomName = saveCurrentDate + saveCurrentTimeS;
StorageReference filepath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
//Now let's store the image to firebase storage
filepath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
downloadUrl = task.getResult().getDownloadUrl().toString();
Toast.makeText(PostActivity.this, "Image uploaded successfully to Storage", Toast.LENGTH_SHORT).show();
SavingPostInformationToDatabase();
} else {
String message = task.getException().getMessage();
Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
private void SavingPostInformationToDatabase()
{
PostsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
countPosts = dataSnapshot.getChildrenCount();
// countForPhotos="photo_"+countPosts;
} else {
countPosts = 0;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Two lines of code to retreive and assign to var the users fullname and uid of it profile image
String userFullName = "#" + dataSnapshot.child("name").getValue().toString().toLowerCase() + "." + dataSnapshot.child("lastname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
//Creating database for storing user posts data including users data
HashMap postsMap = new HashMap();
postsMap.put("uid", current_user_id);
postsMap.put("description", Description);
postsMap.put("postimage", downloadUrl);
postsMap.put("profileimage", userProfileImage);
postsMap.put("fullname", userFullName);
postsMap.put("counter", countPosts);
//Updating database of users post photo only
UserPhotosRef.child(current_user_id).child(current_user_id + postRandomName).updateChildren(postsMap_users_photo);
PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(PostActivity.this, "The post is updated successfully!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
finish();
} else {
Toast.makeText(PostActivity.this, "Error occurred while updating your post!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
} else {
String userFullName = dataSnapshot.child("lastname").getValue().toString();
Toast.makeText(PostActivity.this, "You have a problem!!! " + userFullName, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
SelectPostImage.setImageURI(result.getUri());
Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG)
.show();
Uri resultUri = result.getUri();
ImageUri = resultUri;
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
private void SendUserToMainActivity() {
Intent intent = new Intent(PostActivity.this, MainFeedActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
The issue was with sendActivity inside Firebase initialization...
I i am working with firebase realtime database.. I retrieved data and everything but my main problem is that the data is not being displayed unless i press back button.. I went through stacks everywhere it suggested to notifyDataSetChanged(); which i did before, but still no luck. As i am using GridLayout i cant use the adapter in the addListeneOnDatachange function as it shows error saying that it is not allowed to add the adapter there for my RecyclerViewAdapter.
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
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.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> listCourse;
TextView btnSignOut, UserName;
/*---- Firebase Database stuff ----*/
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
RecyclerView myrv = findViewById(R.id.recyclerviewcourse);
myrv.setLayoutManager(new GridLayoutManager(this,2));
// CourseCode();
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
myRef = rootRef.child("Users");
/*------------------------------------------------------------------*/
listCourse = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse myAdapter = new RecyclerViewAdapterCourse(this,listCourse);
myAdapter.notifyDataSetChanged();
myrv.setAdapter(myAdapter);
}
}
You need to call myAdapter.notifyDataSetChanged() every time the data changes. In your case this means you need to call it at the end of the onDataChanged(DataSnapShot dataSnapShot) function.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
myAdapter.notifyDataSetChanged()
}
I have an app that asks a series of questions. These questions are stored on the firebase db. I am trying to change the child node "Status" from the click of the button. The button being pressed for testing is button "AnswerA".
To date i have managed to change all "Status" nodes to the button press but i only want to change one at a time as the questions are being asked.
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You are looping though all questions and performing the same logic on all of them. You want to select only the question you are interested in, e.g.:
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals()) { // TODO: How you chose the child from your index
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
Adding full playing activity for review,
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
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.ValueEventListener;
import com.hiverecord.kee01.hiverecord.Common.Common;;
import com.hiverecord.kee01.hiverecord.Model.Question;
import com.hiverecord.kee01.hiverecord.Model.QuestionList;
import com.hiverecord.kee01.hiverecord.Model.User;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 5000; //5sec
final static long TIMEOUT = 60000; //70 sec
int progressValue = 0;
CountDownTimer mCountDown;
int index=0,
thisQuestion=0,
totalQuestion,
correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA,btnB;
TextView txtQuestionNum,question_text;
FirebaseDatabase database;
DatabaseReference test;
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
database = FirebaseDatabase.getInstance();
test = database.getReference("Questions"); //get the reference
//Views
txtQuestionNum = findViewById(R.id.txtTotalQuestion);
question_text = findViewById(R.id.question_text);
question_image = findViewById(R.id.question_image);
progressBar = findViewById(R.id.progressBar);
btnA = findViewById(R.id.btnAnswerA);
btnB = findViewById(R.id.btnAnswerB);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion)
{
Button clickedButton = (Button) view;
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals(Common.questionList.get(index).getKey())){
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correctAnswer++;
showQuestion(++index); //next question
}
});
}
else {
Map<String, Object> userUpdates = new HashMap<>();
//userUpdates.put("AnswerA", "");
//userUpdates.put("AnswerB", "NO");
test.updateChildren(userUpdates);
//choose answer false
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
showQuestion(++index);
}
}
}
private void showQuestion(int index) {
if(index < totalQuestion)
{
thisQuestion++;
txtQuestionNum.setText(String.format("%d/%d",thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue=0;
if(Common.questionList.get(index).getIsImageQuestion().equals("true"))
{
//if is image
Picasso.with(getBaseContext())
.load(Common.questionList.get(index).getQuestion())
.into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.VISIBLE);
}
else
{
question_text.setText(Common.questionList.get(index).getQuestion());
//If question is text, we will set image to invisible
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
mCountDown.start(); //Start timer
}
else
{
//if it is a final question
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT,INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}
Solution:
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//logcat and show the index
Log.i("Button A Index accessed", index + "");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get DataSnapShot of Children in ref Questions
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals("0" + index)) {
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
this is my first post here, so any guidance at all is appreciated.
I'm having an issue when others download my app. It causes the App to crash on launch. It works perfectly when I install updates and seems to be an issue stemming from users not having a Firebase UID created when first launching.
Here is Main Activity Code:
package com.example.android.cellavino;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.cellavino.PojoDirectory.UI2.UserDetailsPojo;
import com.example.android.cellavino.UserInterface.WineAdapter;
import com.example.android.cellavino.UserInterface2.WineDetails.CreateNewWine;
import com.example.android.cellavino.UserInterface2.CreateTasting.MyTastings;
import com.example.android.cellavino.UserInterface2.EditProfile.EditProfile;
import com.example.android.cellavino.UserInterface2.JoinTasting.JoinTasting;
import com.example.android.cellavino.UserInterface2.WineDetails.MyWinesList;
import com.example.android.cellavino.Utils.Constants;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.storage.FirebaseStorage;
import java.util.Arrays;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
public String mUsername;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mWineDatabaseReference;
private DatabaseReference mUserDatabaseReference;
private DatabaseReference mMyWinesReference;
private ChildEventListener mChildEventListener;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private FirebaseStorage mFirebaseStorage;
private WineAdapter mWineAdapter;
private ListView mWineListView;
private RecyclerView mWineRecyclerView;
private RecyclerView.Adapter mAdapter;
private ProgressBar mProgressBar;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mNavigationDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private ListView mWineInformation;
private TextView mWineName;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ListView mDrawerList;
private String[] mMenuOptions;
private Uri userProfilePic;
private TextView mUsernameTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.my_wines_list);
//setContentView(R.layout.activity_container);
//getSupportFragmentManager().beginTransaction().replace(R.id.container, new MyWinesListFragment()).commit();
//Initialise Firebase
Firebase.setAndroidContext(this);
mUsername = ANONYMOUS;
//mTitle = mDrawerTitle = getTitle();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
//WineDatabase in Firebase initialisation
mWineDatabaseReference = mFirebaseDatabase.getReference().child("Wine Details");
mUserDatabaseReference = mFirebaseDatabase.getReference().child("Users");
mMyWinesReference = mFirebaseDatabase.getReference().child("Users").child("myWines");
//initialising the views
//ListView mWineListView = (ListView) findViewById(R.id.wineListView);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//user is signed in
onSignedInInialise(user.getDisplayName());
} else {
//user is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
}
};
//add code that will bring up the Add_Wine screen when a user clicks on the floating action button for addwine.
FloatingActionButton addWineFab = (FloatingActionButton) findViewById(R.id.addWineFab);
addWineFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, CreateNewWine.class);
startActivity(intent);
}
});
//initialise view_my_wines button click listener
Button viewMyWinesButton = (Button) findViewById(R.id.view_my_wines);
viewMyWinesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyWinesList.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button editProfileButton = (Button) findViewById(R.id.edit_profile);
editProfileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, EditProfile.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button createTastingButton = (Button) findViewById(R.id.create_tasting);
createTastingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyTastings.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button joinTastingButton = (Button) findViewById(R.id.join_tasting);
joinTastingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, JoinTasting.class);
startActivity(intent);
}
});
FirebaseUser user = mFirebaseAuth.getCurrentUser();
String userName = user.getDisplayName();
if (user != null) {
TextView mUsernameTextView = (TextView) findViewById(R.id.user_name);
mUsernameTextView.setText(userName);
} else {
TextView mUsernameTextView = (TextView) findViewById(R.id.user_name);
mUsernameTextView.setVisibility(View.GONE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
FirebaseUser user = mFirebaseAuth.getCurrentUser();
String uid = user.getUid();
String userName = user.getDisplayName();
String userEmail = user.getEmail();
Uri userProfilePic = user.getPhotoUrl();
createUserInFirebaseHelper(uid, userName, userEmail);
Toast.makeText(MainActivity.this, "Hello " + userName + "!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Sign in cancelled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void createUserInFirebaseHelper(String uid, String userName, String userEmail) {
final String mUserName = userName;
final String mUserEmail = userEmail;
final Firebase userDetailLocation = new Firebase(Constants.FIREBASE_URL_LOCATION_USERS).child(uid);
//See if there is already a user (for example, if they already logged in with an associated google account
userDetailLocation.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
// If there is no user, make one
if (dataSnapshot.getValue() == null) {
//Set raw version of date to the ServerValue.TIMESTAMP value and save into dateCreatedMap
HashMap<String, Object> timestampJoined = new HashMap<>();
timestampJoined.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP);
UserDetailsPojo newUser = new UserDetailsPojo(mUserName, mUserEmail, timestampJoined);
userDetailLocation.setValue(newUser);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d(LOG_TAG, getString(R.string.log_error_occurred) + firebaseError.getMessage());
}
});
}
//When the app comes back from background state etc
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
//When the app goes to background state
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
detachDatabaseReadListener();
//mWineAdapter.clear();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
// return true;
//}
switch (item.getItemId()) {
case R.id.sign_out_menu:
//sign out
AuthUI.getInstance().signOut(this);
return true;
/*
case R.id.menu_add_wine:
//add wine
Intent intent = new Intent(MainActivity.this, AddWine.class);
startActivity(intent);
return true;
case R.id.view_my_wines:
//view the working wine list Andrews Wines
Intent intent2 = new Intent(MainActivity.this, MyWinesList.class);
startActivity(intent2);
return true;
case R.id.test_option:
//view the test screens for Andrews Wines
Intent intent3 = new Intent(MainActivity.this, Login.class);
startActivity(intent3);
return true;
*/
default:
return super.onOptionsItemSelected(item);
}
}
private void onSignedInInialise(String username) {
mUsername = username;
//attachDatabaseReadListener();
//this code adds a new user name each time it logs in.
//mUserDatabaseReference.push().setValue(username);
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
//mWineAdapter.clear();
detachDatabaseReadListener();
}
/*
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
WineDetails wineDetails = dataSnapshot.getValue(WineDetails.class);
//mWineAdapter.add(wineDetails);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mWineDatabaseReference.addChildEventListener(mChildEventListener);
}
}
*/
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mWineDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
private void initializeScreen(View rootView) {
mWineInformation = (ListView) rootView.findViewById(R.id.wine_list_item_details);
mWineName = (TextView) rootView.findViewById(R.id.wine_name);
}
}
How can I adjust it so it checks to see if a user has a profile and if not directs them to the login page?
Thanks in advance.
I figured it out. I was calling getDisplayName() prior to checking authentication.
Thanks for the pointers in how to post a question. I waited 6 months before posting one as I wasn't really sure how/what to ask. Now I know. :)