The items not appear in recyclerview - android

I face a problem when I send a comment, that comment does not appear in RecyclerView, I have to go back and reopen Activity again to see my reply.
BlogSingleActivity.java
public class BlogSingleActivity extends AppCompatActivity {
private String mPost_key = null;
DatabaseReference mDatabase;
private ImageView mBlogSingleImage;
private TextView mBlogSingleTitle;
private TextView mBlogSingleDesc;
private TextView mBlogSingleUsername, mNumbersOfComments;
private TextView mBlogSingleDate;
private DatabaseReference ReplayDatabase;
private RecyclerView mReplayBlogList;
private TextView emptyView;
FirebaseRecyclerAdapter<Blog, BlogViewHolder> mAdapter;
private EditText mReplayText;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private DatabaseReference mDatabaseUser;
private Uri mImagUri = null;
private static final int GALLERY_REQUEST = 2;
private StorageReference mStorage;
private ImageButton mselectImage;
Button sendBTN;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_single);
mPost_key = getIntent().getExtras().getString("blog_id");
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
ReplayDatabase = FirebaseDatabase.getInstance().getReference().child("Replay");
mBlogSingleDesc = findViewById(R.id.singleBlogDesc);
mBlogSingleTitle = findViewById(R.id.post_Tittle);
mBlogSingleImage = findViewById(R.id.singleBlogImage);
mBlogSingleUsername = findViewById(R.id.singleBlogUsername);
mBlogSingleDate = findViewById(R.id.singleBlogDate);
mNumbersOfComments = findViewById(R.id.numberofcomments);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mReplayBlogList = findViewById(R.id.replay_blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mReplayBlogList.setLayoutManager(layoutManager);
mReplayBlogList.setNestedScrollingEnabled(false);
emptyView = findViewById(R.id.empty_view);
chickitem();
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
mReplayText = findViewById(R.id.ReplayField);
mStorage = FirebaseStorage.getInstance().getReference();
mselectImage = findViewById(R.id.replayImageSelect);
sendBTN = findViewById(R.id.send_BTN);
getfirebaseData();
mProgress = new ProgressDialog(this);
mselectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
sendBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startReplay();
getfirebaseData();;
disappearKeyboard();
mReplayText.getText().clear();
mselectImage.setImageResource(R.mipmap.add_btn);
mselectImage.setBackgroundColor(getResources().getColor(R.color.image_background_color));
}
});
mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String post_title = (String) dataSnapshot.child("tittle").getValue();
String post_desc = (String) dataSnapshot.child("desc").getValue();
String post_image = (String) dataSnapshot.child("image").getValue();
String post_username = (String) dataSnapshot.child("username").getValue();
Object post_date = dataSnapshot.child("date").getValue();
Blog timeStamp = new Blog();
timeStamp.setDate(post_date);
if (timeStamp.getDate() != null) {
String datee = timeStamp.getDate().toString();
long time = Long.parseLong(datee);
String timeAgo = TimeAgo.getTimeAgo(time);
mBlogSingleDate.setText(timeAgo);
}
mBlogSingleTitle.setText(post_title);
mBlogSingleDesc.setText(post_desc);
mBlogSingleUsername.setText(post_username);
Picasso.with(BlogSingleActivity.this)
.load(post_image)
.into(mBlogSingleImage);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void disappearKeyboard() {
InputMethodManager inputManager =
(InputMethodManager) this.
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private void startReplay() {
{
final String replay_val = mReplayText.getText().toString().trim();
//send date to firebase database
if (!TextUtils.isEmpty(replay_val) && mImagUri != null) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
StorageReference filepath = mStorage.child("Replay_Images").child(mImagUri.getLastPathSegment());
filepath.putFile(mImagUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (mAuth.getCurrentUser() != null) {
#SuppressWarnings("VisibleForTests") final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replayimage").setValue(downloadUrl.toString());
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
});
} else if ((!TextUtils.isEmpty(replay_val))) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
if (mAuth.getCurrentUser() != null) {
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
}
}
private void getfirebaseData() {
mAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.replay_row,
BlogViewHolder.class,
ReplayDatabase.child(mPost_key)
) {
#Override
protected void populateViewHolder(final BlogViewHolder viewHolder, final Blog model, int position) {
viewHolder.setReplay(model.getReplay());
viewHolder.setReplayname(model.getReplayname());
viewHolder.setReplaydate(model.getReplaydate());
viewHolder.setReplayimage(getApplicationContext(), model.getReplayimage());
}
};
mReplayBlogList.setAdapter(mAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageView replay_imagee;
TextView recive_replay, post_replayname, post_replaydate;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setReplay(String replay) {
recive_replay = mView.findViewById(R.id.replay_text);
recive_replay.setText(replay);
}
public void setReplayname(String replayname) {
post_replayname = mView.findViewById(R.id.replayer_name_field);
post_replayname.setText(replayname);
}
public void setReplaydate(Object relaydate) {
post_replaydate = mView.findViewById(R.id.post_replaydate);
Blog timeStamps = new Blog();
timeStamps.setDate(relaydate);
if (timeStamps.getDate()!=null){
String dateee = timeStamps.getDate().toString();
long times = Long.parseLong(dateee);
String timeAgoo = TimeAgo.getTimeAgo(times);
post_replaydate.setText(timeAgoo);
}
}
public void setReplayimage(final Context ctx, final String replayimage) {
replay_imagee = mView.findViewById(R.id.replay_image);
Picasso.with(ctx).load(replayimage).networkPolicy(NetworkPolicy.OFFLINE).into(replay_imagee, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(replayimage).into(replay_imagee);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mImagUri = result.getUri();
mselectImage.setImageURI(mImagUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void chickitem() {
final AtomicInteger count = new AtomicInteger();
ReplayDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long numChildren = dataSnapshot.child(mPost_key).getChildrenCount();
if (numChildren == 0) {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("لا توجد تعليقات");
mReplayBlogList.setVisibility(View.INVISIBLE);
mNumbersOfComments.setText("لا توجد تعليقات");
} else {
mNumbersOfComments.setText("" + numChildren);
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("التعليقات...");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
getfirebaseData();
}
#Override
public void onResume(){
super.onResume();
getfirebaseData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The screen looks like .
There are two comments. To see these comment I have to go back and reopen this Activity.

I'm not 100% sure about this, but I think you're missing the mReplayBlogList.notifyDataSetChanged(); after the line mReplayBlogList.setAdapter(mAdapter); in getfirebaseData().
Maybe you could give it a try. Let me know if it solved :)

Related

Showing specific button to current user in Android

My app has a post layout which have an edit button and the send button. All i want to do is to show only edit button if current user is viewing his/her post and not the send button. Just like a stackoverflow post, you can't edit other's post and can't send a message to yourself. I have tried boolean methods but still no solution. Thanks.
Activity that have showButtonsForCurrentUser() method ;
public class ViewPostActivity extends AppCompatActivity {
private static final String TAG = "ViewPostActivity";
//widgets
private TextView mTitle, mDescription, mPrice, mLocation;
//vars
private String mPostId;
private String userId;
private Post mPost;
private PostImages mPostImages;
private ViewPager viewPager;
private ImageView editPostIcon;
private WormDotsIndicator wormDotsIndicator;
public ViewAdapter viewAdapter;
public DatabaseReference reference;
public FirebaseUser currentUser;
public ArrayList<String> IMAGES = new ArrayList<>();
public ArrayList<Uri> mImageUris = new ArrayList<>();
private SquareImageView postImageView;
private User user;
//Dialog and Sheet vars
private Dialog deleteDialog;
private Button deleteBtnDialog;
private Button deleteBtnSheet;
private Button updateBtn;
private Button sendBtn;
private TextView titleTv, messageTv;
private ImageView closeIcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_post);
mPostId = getIntent().getStringExtra(getString(R.string.arg_post_id));
mTitle = (TextView) findViewById(R.id.post_title);
mDescription = (TextView) findViewById(R.id.post_description);
mPrice = (TextView) findViewById(R.id.post_price);
mLocation = (TextView) findViewById(R.id.post_location);
postImageView = findViewById(R.id.post_image);
sendBtn = findViewById(R.id.send_msg);
viewPager = findViewById(R.id.view_pager_images);
editPostIcon = findViewById(R.id.edit_post_btn);
wormDotsIndicator = findViewById(R.id.dotsindicator);
editPostIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBottomSheetDialog();
}
});
getPostInfo();
showButtonsForCurrentUser();
////MyPosts Layout/////
deleteBtnDialog = findViewById(R.id.dialog_btn);
deleteDialog = new Dialog(this);
////MyPosts Layout/////
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ViewPostActivity.this, MessageActivity.class);
intent.putExtra("userId", userId);
startActivity(intent);
}
});
}
public void showButtonsForCurrentUser(){
currentUser = FirebaseAuth.getInstance().getCurrentUser();
//sendBtn and editPostIcon are set to GONE.
if (currentUser.equals(userId)){
sendBtn.setVisibility(View.VISIBLE);
}else{
editPostIcon.setVisibility(View.VISIBLE);
}
}
private void getPostInfo(){
Log.d(TAG, "getPostInfo: getting the post information.");
reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child(getString(R.string.node_posts))
.orderByKey()
.equalTo(mPostId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
if(singleSnapshot != null){
mPost = singleSnapshot.getValue(Post.class);
Log.d(TAG, "onDataChange: found the post: " + mPost.getTitle());
mTitle.setText(mPost.getTitle());
mDescription.setText(mPost.getDescription());
String price = "FREE";
if(mPost.getPrice() != null){
price = "$" + mPost.getPrice();
}
mPrice.setText(price);
String location = mPost.getCity();
mLocation.setText(location);
userId = mPost.getUser_id();
if (mPost.getImage() != null){
wormDotsIndicator.setVisibility(View.INVISIBLE);
postImageView.setVisibility(View.VISIBLE);
Picasso.get().load(mPost.getImage()).into(postImageView);
}else {
IMAGES = mPost.getPostImages();
for (int i = 0; i <IMAGES.size(); i++){
Uri myUri = Uri.parse(IMAGES.get(i));
mImageUris.add(myUri);
}
viewAdapter = new ViewAdapter(getApplication(), IMAGES);
viewPager.setAdapter(viewAdapter);
wormDotsIndicator.setViewPager(viewPager);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showBottomSheetDialog() {
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(ViewPostActivity.this, R.style.BottomSheetDialogTheme);
LinearLayout linearLayout = findViewById(R.id.bottom_sheet_update_container);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bottom_sheet_update, linearLayout);
updateBtn = bottomSheetView.findViewById(R.id.update_btnn);
deleteBtnSheet = bottomSheetView.findViewById(R.id.delete_btnn);
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent updateActivityIntent = new Intent(ViewPostActivity.this, UpdateActivity.class);
if (IMAGES != null){
updateActivityIntent.putStringArrayListExtra("IMAGES", IMAGES);
updateActivityIntent.putParcelableArrayListExtra("IMAGEURIS", mImageUris);
}else {
String singlePhotoUrl = mPost.getImage();
updateActivityIntent.putExtra("Single Photo url", singlePhotoUrl);
}
updateActivityIntent.putExtra("Başlık", mTitle.getText());
updateActivityIntent.putExtra("Açıklama", mDescription.getText());
updateActivityIntent.putExtra("Fiyat", mPrice.getText());
updateActivityIntent.putExtra("mPostId", mPostId);
startActivity(updateActivityIntent);
bottomSheetDialog.dismiss();
}
});
deleteBtnSheet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDeleteDialog();
}
});
}
public void showDeleteDialog(){
deleteDialog.setContentView(R.layout.positive_dialog);
closeIcon = deleteDialog.findViewById(R.id.close_dialog);
deleteBtnDialog = deleteDialog.findViewById(R.id.dialog_btn);
titleTv = deleteDialog.findViewById(R.id.titleTv);
messageTv = deleteDialog.findViewById(R.id.message_dialog);
closeIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteDialog.dismiss();
}
});
deleteDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
deleteDialog.show();
deleteBtnDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deletePost(mPostId);
finish();
overridePendingTransition( 0, 0);
startActivity(getIntent());
overridePendingTransition( 0, 0);
deleteDialog.dismiss();
}
});
}
private void deletePost(String deletePostId){
Bundle args = new Bundle();
args.putString(getString(R.string.arg_post_id), deletePostId);
Query deleteQuery = reference.child("posts").orderByChild("post_id").equalTo(deletePostId);
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot delData: dataSnapshot.getChildren()){
delData.getRef().removeValue();
Intent backIntent = new Intent(ViewPostActivity.this, SearchActivity.class);
startActivity(backIntent);
}
Toast.makeText(ViewPostActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ViewPostActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
private void status(String status){
currentUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
protected void onResume() {
super.onResume();
status("online");
}
#Override
protected void onPause() {
super.onPause();
status("offline");
}
}
what are the values for mPostId?
I would log the userID and currentuser values thats being retrieved, to check if there is no issue your query. The boolean part should work

The menu didn't appear and listview unclickable

Thank you for helping me. The menu didn't appear and the list view in the recycler view is unclickable.
This is the menu part.
public class QuizListActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_list);
mAuth = FirebaseAuth.getInstance();
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerBView);
new FirebaseDatabaseHelper().readQuiz(new FirebaseDatabaseHelper.DataStatus() {
#Override
public void DataIsLoaded(List<Quiz> quizzes, List<String> keys) {
new RecyclerConfig().setConfig(mRecyclerView, QuizListActivity.this, quizzes, keys);
}
#Override
public void DataIsInserted() {
}
#Override
public void DataIsUpdated() {
}
#Override
public void DataIsDeleted() {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
FirebaseUser user = mAuth.getCurrentUser();
getMenuInflater().inflate(R.menu.quizlistmenu, menu);
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onCreateOptionsMenu(menu);
}
public boolean onPrepareOptionsMenu(Menu menu)
{FirebaseUser user = mAuth.getCurrentUser();
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.new_book:
startActivity(new Intent(this, NewQuestionActivity.class));
return true;
case R.id.user_approval:
startActivity(new Intent(this, Approval.class));
return true;
case R.id.signout:
mAuth.signOut();
invalidateOptionsMenu();
RecyclerConfig.logout();
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the menu.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/new_book"
android:title="New Question" />
<item
android:id="#+id/user_approval"
android:title="Registered User" />
<item
android:id="#+id/signout"
android:title="Sign Out" />
</menu>
This is the Recycler part.
public class RecyclerConfig
{
FirebaseAuth mAuth;
private static FirebaseUser user;
private Context mContext;
private QuizAdapter mQuizAdapter;
public void setConfig(RecyclerView mRecyclerView, Context context, List<Quiz> quizzes, List<String> keys)
{
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
mContext = context;
mQuizAdapter = new QuizAdapter(quizzes, keys);
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mRecyclerView.setAdapter(mQuizAdapter);
}
class QuizItemView extends RecyclerView.ViewHolder
{
private TextView mquestion,mans1,mans2,mans3,mans4,mcorrect,mcategoryid;
private String key;
public QuizItemView(ViewGroup parent)
{
super(LayoutInflater.from(mContext)
.inflate(R.layout.quizlistitem, parent, false));
mquestion = (TextView) itemView.findViewById(R.id.questiontv);
mans1 = (TextView) itemView.findViewById(R.id.ans1tv);
mans2 = (TextView) itemView.findViewById(R.id.ans2tv);
mans3 = (TextView) itemView.findViewById(R.id.ans3tv);
mans4 = (TextView) itemView.findViewById(R.id.ans4tv);
mcorrect = (TextView) itemView.findViewById(R.id.correcttv);
mcategoryid = (TextView) itemView.findViewById(R.id.categorytv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(user!=null) {
Intent intent = new Intent(mContext, QuizDetailActivity.class);
intent.putExtra("key", key);
intent.putExtra("question", mquestion.getText().toString());
intent.putExtra("answer1", mans1.getText().toString());
intent.putExtra("answer2", mans2.getText().toString());
intent.putExtra("answer3", mans3.getText().toString());
intent.putExtra("answer3", mans4.getText().toString());
intent.putExtra("answer3", mcorrect.getText().toString());
intent.putExtra("categoryid", mcategoryid.getText().toString());
mContext.startActivity(intent);
}
/*else
{
mContext.startActivity(new Intent(mContext, SignInActivity.class));
}*/
}
});
}
public void bind(Quiz quizzes, String key)
{
mquestion.setText(quizzes.getQuestion());
mans1.setText(quizzes.getAnswer1());
mans2.setText(quizzes.getAnswer2());
mans3.setText(quizzes.getAnswer3());
mans4.setText(quizzes.getAnswer4());
mcorrect.setText(quizzes.getCorrect());
mcategoryid.setText(quizzes.getCategoryid());
this.key = key;
}
}
class QuizAdapter extends RecyclerView.Adapter<QuizItemView>
{
private List<Quiz> mQuizList;
private List<String> mKeys;
public QuizAdapter(List<Quiz> mQuizList, List<String> mKeys) {
this.mQuizList = mQuizList;
this.mKeys = mKeys;
}
#NonNull
#Override
public QuizItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new QuizItemView(parent);
}
#Override
public void onBindViewHolder(#NonNull QuizItemView holder, int position) {
holder.bind(mQuizList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mQuizList.size();
}
}
public static void logout()
{
user = null;
}
}
This is the login / register part.
public class SignInActivity extends AppCompatActivity {
MaterialEditText edtNewEmail,edtNewPassword,edtnewName, edtnewAge, edtnewAddress, edtStatus; // for register
MaterialEditText edtEmail,edtPassword; //for Signin
Button btnRegister,btnSignIn;
FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mAuth = FirebaseAuth.getInstance();
//Firebase
database = FirebaseDatabase.getInstance();
users = database.getReference("User");
edtEmail = (MaterialEditText)findViewById(R.id.edtEmail);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn = (Button)findViewById(R.id.signInBtn);
btnRegister = (Button)findViewById(R.id.regBtn);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn(edtEmail.getText().toString(),edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user).exists())
{
if(!user.isEmpty())
{
User login = dataSnapshot.child(user).getValue(User.class);
if(login.getPassword().equals(pwd))
{
Common.currentUser = login;
if(login.getStatus().equals("Admin"))
{
mAuth.signInWithEmailAndPassword(edtEmail.getText().toString(),
edtPassword.getText().toString());
Toast.makeText(SignInActivity.this, "User signed in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignInActivity.this,QuizListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); return;
}
else if(login.getStatus().equals("User") && login.getApproval().equals("Y"))
{
Intent homeactivity = new Intent(SignInActivity.this,Home.class);
startActivity(homeactivity);
finish();
}
else if(login.getStatus().equals("User") && login.getApproval().equals("N"))
{
Intent adminactivity = new Intent(SignInActivity.this,Home.class);
startActivity(adminactivity);
finish();
}
}
else
Toast.makeText(SignInActivity.this,"Login Failed",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this,"Please fill in",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(SignInActivity.this,"User doesn't exist",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SignInActivity.this);
alertDialog.setTitle("Sign Up");
//alertDialog.setMessage("Please fill full information");
LayoutInflater inflater = this.getLayoutInflater();
View activity_register = inflater.inflate(R.layout.activity_register,null);
//edtNewUserName = (MaterialEditText)activity_register.findViewById(R.id.edtNewUserName);
edtNewEmail = (MaterialEditText)activity_register.findViewById(R.id.edtNewEmail);
edtNewPassword = (MaterialEditText)activity_register.findViewById(R.id.edtNewPassword);
edtnewName = (MaterialEditText)activity_register.findViewById(R.id.edtnewName);
edtnewAge = (MaterialEditText)activity_register.findViewById(R.id.edtnewAge);
edtnewAddress = (MaterialEditText)activity_register.findViewById(R.id.edtnewAddress);
edtStatus = (MaterialEditText)activity_register.findViewById(R.id.edtStatus);
alertDialog.setView(activity_register);
//alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user = new User(edtNewEmail.getText().toString(),
edtNewPassword.getText().toString(),edtnewName.getText().toString(),
edtnewAge.getText().toString(),edtnewAddress.getText().toString(),edtStatus.getText().toString(),
"N");
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getEmail()).exists())
Toast.makeText(SignInActivity.this,"User already exist.",Toast.LENGTH_LONG).show();
else
{
if(dataSnapshot.child(user.getStatus()).exists() && user.getStatus() == "Admin")
{
mAuth.createUserWithEmailAndPassword(edtNewEmail.getText().toString(),
edtNewPassword.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
}
}
});
}
else {
users.child(user.getEmail())
.setValue(user);
Toast.makeText(SignInActivity.this, "User registered.", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
The login and register works well then after login the list recycler view is shown accurately but the menu didn't appear and the recycler view is unclickable.
For the menu, it previously stated that a null reference or something.
For your first question, which is why menu didn't appear because you didn't initialize the FirebaseUser. You need to initiliaze it at method onCreate.
at Class.
private FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_list);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
}
next, at your onCreateOptionsMenu.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.quizlistmenu, menu);
if(user!=null) {
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
menu.getItem(2).setVisible(true);
}
return super.onCreateOptionsMenu(menu);
}

Can not delete item that is selected, only deletes the last item added

I'm trying to delete the selected item in my RecyclerView, but when I click on my delete Button it just deletes the last item added. And after I delete the last item added I can not delete anymore. What am I missing?
MainActivity
public class MainWishActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView wishList;
private androidx.appcompat.widget.Toolbar mToolbar;
private ImageButton ibaddnewwishlist;
private CircleImageView NavProfileImage;
private TextView NavProfileFirstName, NavProfileLastName;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef, WishListRef;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wish);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID);
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(" Dine Ønskelister");
drawerLayout = (DrawerLayout)findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainWishActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
ibaddnewwishlist = (ImageButton)findViewById(R.id.ib_addnewwishlist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
wishList = (RecyclerView)findViewById(R.id.rv_wishlist);
wishList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.civ_navprofilepicture);
NavProfileFirstName = (TextView)navView.findViewById(R.id.tv_headerfirstname);
NavProfileLastName = (TextView) navView.findViewById(R.id.tv_headerlastname);
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
if (dataSnapshot.hasChild("fornavn")){
String firstname = dataSnapshot.child("fornavn").getValue().toString();
NavProfileFirstName.setText(firstname);
}
if (dataSnapshot.hasChild("etternavn")) {
String lastname = dataSnapshot.child("etternavn").getValue().toString();
NavProfileLastName.setText(lastname);
}
if (dataSnapshot.hasChild("profilbilde")){
String image = dataSnapshot.child("profilbilde").getValue().toString();
Picasso.with(MainWishActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}
else{
Toast.makeText(MainWishActivity.this, "Profil navn finnes ikke...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
ibaddnewwishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToWishListActivity();
}
});
DisplayUsersWishLists();
}
private void DisplayUsersWishLists() {
FirebaseRecyclerAdapter<WishListClass, WishListViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishListClass, WishListViewHolder>
(
WishListClass.class,
R.layout.wish_list_single_layout,
WishListViewHolder.class,
WishListRef
) {
#Override
protected void populateViewHolder(WishListViewHolder viewHolder, WishListClass model, final int position) {
final String Key = getRef(position).getKey();
viewHolder.setFornavn(model.getFornavn());
viewHolder.setDate(model.getDate());
viewHolder.setTitle(model.getTitle());
viewHolder.setProfilbilde(getApplicationContext(), model.getProfilbilde());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent profileIntent = new Intent(MainWishActivity.this, UserWishItemActivity.class);
profileIntent.putExtra("Key", Key);
startActivity(profileIntent);
}
});
}
};
wishList.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListViewHolder extends RecyclerView.ViewHolder{
View mView;
public WishListViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setFornavn (String fornavn){
TextView wishlist_name = (TextView) mView.findViewById(R.id.tv_firstnamelist);
wishlist_name.setText(fornavn);
}
public void setProfilbilde (Context ctx, String profilbilde){
CircleImageView image = (CircleImageView) mView.findViewById(R.id.civ_profilepicturelist);
Picasso.with(ctx).load(profilbilde).into(image);
}
public void setDate (String date){
TextView wishlist_date = (TextView) mView.findViewById(R.id.tv_publisheddatelist);
wishlist_date.setText(" " + date);
}
public void setTitle (String title){
TextView wishlist_title = (TextView) mView.findViewById(R.id.tv_wishlisttitle);
wishlist_title.setText(title);
}
}
private void SendUserToWishListActivity(){
Intent addNewPostIntent = new Intent(MainWishActivity.this, AddWishListActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null){
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
private void CheckUserExistence(){
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
SendUserToUserInfoAcitivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToUserInfoAcitivity(){
Intent setupIntent = new Intent(MainWishActivity.this, UserInfoActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainWishActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserToFindFriendsActivity(){
Intent findfriendsIntent = new Intent(MainWishActivity.this, FindFriendsActivity.class);
findfriendsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(findfriendsIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector (MenuItem item){
switch (item.getItemId()){
case R.id.navbtn_addwishlist:
SendUserToWishListActivity();
break;
case R.id.navbtn_profile:
Toast.makeText(this, "Profil", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_home:
Toast.makeText(this, "Hjem", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_friends:
Toast.makeText(this, "Venner", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_findfriends:
SendUserToFindFriendsActivity();
break;
case R.id.navbtn_settings:
Toast.makeText(this, "Instillinger", Toast.LENGTH_SHORT).show();
break;
case R.id.navbtn_logout:
mAuth.signOut();
SendUserToLoginActivity();
break;
}
}
SecondActivity
public class UserWishItemActivity extends AppCompatActivity {
private TextView tvwishlisttitle;
private EditText etwishitem;
private Button btnaddwishitem;
private RecyclerView wishListitems;
private String currentUserID, databaseUserID;
private String Key, postRandomName;
private DatabaseReference WishListUsersClickRef, UsersRef, WishItemsRef, wishListRef,WishItemsRef1;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_add_wish_item);
Key = getIntent().getExtras().get("Key").toString();
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
WishItemsRef = FirebaseDatabase.getInstance().getReference().child("Ønsker");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister").child(currentUserID).child(Key);
tvwishlisttitle = (TextView)findViewById(R.id.tv_userwishlisttitle);
etwishitem = (EditText)findViewById(R.id.et_wishitem);
btnaddwishitem = (Button)findViewById(R.id.btn_addwishitem);
btnaddwishitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
wishListitems = (RecyclerView)findViewById(R.id.rv_wishlistitems);
wishListitems.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wishListitems.setLayoutManager(linearLayoutManager);
WishListUsersClickRef = FirebaseDatabase.getInstance().getReference("Ønskelister").child(currentUserID).child(Key);
WishListUsersClickRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String title = dataSnapshot.child("title").getValue().toString();
databaseUserID = dataSnapshot.child("uid").getValue().toString();
tvwishlisttitle.setText(title);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DisplayWishListItems();
}
private void DisplayWishListItems() {
FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder > firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<WishItemClass, WishListItemsViewHolder>
(
WishItemClass.class,
R.layout.wish_list_item_layout,
WishListItemsViewHolder.class,
WishItemsRef.child(Key)
) {
#Override
protected void populateViewHolder(final WishListItemsViewHolder viewHolder, final WishItemClass model, final int position) {
viewHolder.setWishitemname(model.getWishitemname());
viewHolder.m1View.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UserWishItemActivity.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.endreslettjobb_dialog, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle(model.getWishitemname());
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
final Button btndelete = (Button)dialogView.findViewById(R.id.btn_delete);
btndelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WishItemsRef.removeValue();
}
});
return false;
}
});
}
};
wishListitems.setAdapter(firebaseRecyclerAdapter);
}
public static class WishListItemsViewHolder extends RecyclerView.ViewHolder{
View m1View;
public WishListItemsViewHolder(#NonNull View itemView) {
super(itemView);
m1View = itemView;
}
public void setWishitemname (String wishitemname){
TextView wishitem_name = (TextView) m1View.findViewById(R.id.tv_wishitemname);
wishitem_name.setText(wishitemname);
}
public void setUid (String uid){
}
}
private void CreateWishlist() {
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = etwishitem.getText().toString().trim();
etwishitem.setText("");
wishListRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("wishitemname", wishlist);
WishItemsRef.child(Key).child(postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
AddItemActivity
private Spinner spwishlisttitle;
private Button btnsavewishlist;
private DatabaseReference UsersRef, wishListRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, currentUserID, postRandomName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_wish_list);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Brukere");
wishListRef = FirebaseDatabase.getInstance().getReference().child("Ønskelister");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
spwishlisttitle = (Spinner) findViewById(R.id.sp_wishlisttitle);
btnsavewishlist = (Button) findViewById(R.id.btn_savewishlist);
btnsavewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateWishlist();
}
});
}
private void CreateWishlist() {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
postRandomName = String.valueOf(new Date().getTime());
final String wishlist = spwishlisttitle.getSelectedItem().toString().trim();
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String userFirstname = dataSnapshot.child("fornavn").getValue().toString();
String userProfileImage = dataSnapshot.child("profilbilde").getValue().toString();
HashMap postMap = new HashMap();
postMap.put("uid", currentUserID);
postMap.put("date", saveCurrentDate);
postMap.put("title", wishlist);
postMap.put("profilbilde", userProfileImage);
postMap.put("fornavn", userFirstname);
wishListRef.child(currentUserID).child(currentUserID + postRandomName).updateChildren(postMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(AddWishListActivity.this, "Ønskeliste opprettet", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AddWishListActivity.this, "Error ocurred", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(AddWishListActivity.this, MainWishActivity.class);
startActivity(mainIntent);
}
}
I have edited my question with my code.
Hope this is helpful.

My Firebase On-device indexing is not working

I am following the Codelab tutorial on firebase of the FriendlyChat app. I have reached the Indexing section. I have implemented the code as required but I do not see the app indexing work when I search google on the emulator.
Here is the manifest section.
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="friendlychat.firebase.google.com"
android:scheme="http"
android:pathPrefix="/message"/>
</intent-filter>
Here is the MainActivity.java
The tutorial is on this page https://codelabs.developers.google.com/codelabs/firebase-android/#8
Could the problem be that I am using the emulator?
Here is the MainActivity.java
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
public static class MessageViewHolder extends RecyclerView.ViewHolder {
TextView messageTextView;
ImageView messageImageView;
TextView messengerTextView;
CircleImageView messengerImageView;
public MessageViewHolder(View v) {
super(v);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messageImageView = (ImageView) itemView.findViewById(R.id.messageImageView);
messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
}
}
private static final String TAG = "MainActivity";
public static final String MESSAGES_CHILD = "messages";
private static final int REQUEST_INVITE = 1;
private static final int REQUEST_IMAGE = 2;
private static final String LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 10;
public static final String ANONYMOUS = "anonymous";
private static final String MESSAGE_SENT_EVENT = "message_sent";
private String mUsername;
private String mPhotoUrl;
private SharedPreferences mSharedPreferences;
private GoogleApiClient mGoogleApiClient;
private static final String MESSAGE_URL = "http://friendlychat.firebase.google.com/message/";
private Button mSendButton;
private RecyclerView mMessageRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ProgressBar mProgressBar;
private EditText mMessageEditText;
private ImageView mAddMessageImageView;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mFirebaseDatabaseReference;
private FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder> mFirebaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set default username is anonymous.
mUsername = ANONYMOUS;
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if(mFirebaseUser == null){
// Not signed in, launch the Sign in activity
startActivity(new Intent(this, SignInActivity.class));
finish();
return;
} else {
mUsername = mFirebaseUser.getDisplayName();
if(mFirebaseUser.getPhotoUrl() != null){
mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
}
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mLinearLayoutManager.setStackFromEnd(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
// New child entries
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(
FriendlyMessage.class,
R.layout.item_message,
MessageViewHolder.class,
mFirebaseDatabaseReference.child(MESSAGES_CHILD)) {
#Override
protected FriendlyMessage parseSnapshot(DataSnapshot snapshot){
FriendlyMessage friendlyMessage = super.parseSnapshot(snapshot);
if(friendlyMessage != null){
friendlyMessage.setId(snapshot.getKey());
}
return friendlyMessage;
}
#Override
protected void populateViewHolder(final MessageViewHolder messageViewHolder,
FriendlyMessage friendlyMessage, int position) {
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
if(friendlyMessage.getText() != null){
// write this message to the on-device index
FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));
Log.d(TAG, friendlyMessage.getText());
// log a view action on it
FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));
messageViewHolder.messageTextView.setText(friendlyMessage.getText());
messageViewHolder.messageTextView.setVisibility(TextView.VISIBLE);
messageViewHolder.messageImageView.setVisibility(ImageView.GONE);
} else {
String imageUrl = friendlyMessage.getImageUrl();
if(imageUrl.startsWith("gs://")){
StorageReference storageReference = FirebaseStorage.getInstance()
.getReferenceFromUrl(imageUrl);
storageReference.getDownloadUrl().addOnCompleteListener(
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
String downloadUrl = task.getResult().toString();
Glide.with(messageViewHolder.messageImageView.getContext())
.load(downloadUrl)
.into(messageViewHolder.messageImageView);
} else {
Log.w(TAG, "Getting download url was not successful.",
task.getException());
}
}
}
);
} else {
Glide.with(messageViewHolder.messageImageView.getContext())
.load(friendlyMessage.getImageUrl())
.into(messageViewHolder.messageImageView);
}
messageViewHolder.messageImageView.setVisibility(ImageView.VISIBLE);
messageViewHolder.messageTextView.setVisibility(TextView.GONE);
}
messageViewHolder.messengerTextView.setText(friendlyMessage.getName());
if( friendlyMessage.getPhotoUrl() == null){
messageViewHolder.messengerImageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,
R.drawable.ic_account_circle_black_36dp));
} else {
Glide.with(MainActivity.this)
.load(friendlyMessage.getPhotoUrl())
.into(messageViewHolder.messengerImageView);
}
}
};
mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver(){
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the
// user is at the bottom of the list, scroll to the bottom
// of the list to show the newly added message
if (lastVisiblePosition == -1 ||
(positionStart >= (friendlyMessageCount - 1) &&
lastVisiblePosition == (positionStart -1))){
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
mMessageRecyclerView.setAdapter(mFirebaseAdapter);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mSharedPreferences
.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT))});
mMessageEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
mSendButton = (Button) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Send messages on click.
FriendlyMessage friendlyMessage = new
FriendlyMessage(mMessageEditText.getText().toString(),
mUsername,
mPhotoUrl,
null /* no image */);
mFirebaseDatabaseReference.child(MESSAGES_CHILD)
.push().setValue(friendlyMessage);
mMessageEditText.setText("");
}
});
mAddMessageImageView = (ImageView) findViewById(R.id.addMessageImageView);
mAddMessageImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Select image for image message on click.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in.
// TODO: Add code to check if user is signed in.
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
if(requestCode == REQUEST_IMAGE){
if(resultCode == RESULT_OK) {
if(data != null){
final Uri uri = data.getData();
Log.d(TAG, "Uri: " + uri.toString());
FriendlyMessage tempMessage = new FriendlyMessage(null, mUsername, mPhotoUrl,
LOADING_IMAGE_URL);
mFirebaseDatabaseReference.child(MESSAGES_CHILD).push()
.setValue(tempMessage, new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError databaseError,
DatabaseReference databaseReference){
if(databaseError == null){
String key = databaseReference.getKey();
StorageReference storageReference =
FirebaseStorage.getInstance()
.getReference(mFirebaseUser.getUid())
.child(key)
.child(uri.getLastPathSegment());
putImageInStorage(storageReference, uri, key);
} else {
Log.w(TAG, "Unable to write message to database.",
databaseError.toException());
}
}
});
}
}
}
}
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key){
storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
FriendlyMessage friendlyMessage =
new FriendlyMessage(null, mUsername, mPhotoUrl,
task.getResult().getMetadata().getDownloadUrl()
.toString());
mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
.setValue(friendlyMessage);
} else {
Log.w(TAG, "Image upload task was not successful.",
task.getException());
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_menu:
mFirebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
mUsername = ANONYMOUS;
startActivity(new Intent(this, SignInActivity.class));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
private Indexable getMessageIndexable(FriendlyMessage friendlyMessage) {
PersonBuilder sender = Indexables.personBuilder()
.setIsSelf(mUsername.equals(friendlyMessage.getName()))
.setName(friendlyMessage.getName())
.setUrl(MESSAGE_URL.concat(friendlyMessage.getId() + "/sender"));
PersonBuilder recipient = Indexables.personBuilder()
.setName(mUsername)
.setUrl(MESSAGE_URL.concat(friendlyMessage.getId() + "/recipient"));
Indexable messageToIndex = Indexables.messageBuilder()
.setName(friendlyMessage.getText())
.setUrl(MESSAGE_URL.concat(friendlyMessage.getId()))
.setSender(sender)
.setRecipient(recipient)
.build();
return messageToIndex;
}
private Action getMessageViewAction(FriendlyMessage friendlyMessage){
return new Action.Builder(Action.Builder.VIEW_ACTION)
.setObject(friendlyMessage.getName(), MESSAGE_URL.concat(friendlyMessage.getId()))
.setMetadata(new Action.Metadata.Builder().setUpload(false))
.build();
}
If you take from copy/paste, that is only about wrong place code, try
From Android Studio, on toolbar Click "CODE" then select "REARRANGE
CODE" than try "RUN" again.
Or try see sample from original MainActivity.java in android folder
instead android-start on
https://github.com/firebase/friendlychat-android repository

Image is not retrieved in ImageView of RecyclerView from Firebase

MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
private static final int RC_PHOTO_PICKER = 2;
private String mUsername;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
PhotosAdapter contactsAdapter;
List<Photos> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
floatingActionButton=(FloatingActionButton)findViewById(R.id.floatingactionbutton);
contactList = new ArrayList();
contactsAdapter=new PhotosAdapter(contactList,getApplicationContext());
// Initialize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
onSignedInInitialize(user.getDisplayName());
} else {
// User is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(
AuthUI.EMAIL_PROVIDER,
AuthUI.GOOGLE_PROVIDER)
.build(),
RC_SIGN_IN);
}
}
};
recyclerView.setAdapter(contactsAdapter);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),5));
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
}else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Photos friendlyMessage = new Photos(downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(friendlyMessage);
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
attachDatabaseReadListener();
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
}
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Photos friendlyMessage = dataSnapshot.getValue(Photos.class);
contactsAdapter.add(friendlyMessage);
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot) {}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
}
}
}
PhotosAdapter
public class PhotosAdapter extends RecyclerView.Adapter<PhotosAdapter.MyViewHolder> {
private List<Photos> photosList;
private Context context;
public static final String Position="AdapterPosition";
public PhotosAdapter(List<Photos> contactsList, Context context) {
this.photosList = contactsList;
this.context = context;
}
#Override
public PhotosAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, null);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(PhotosAdapter.MyViewHolder holder, int position) {
Photos contacts = photosList.get(position);
Glide.with(context).load(contacts.getPhotoUrl()).into(holder.contactimageView);
}
#Override
public int getItemCount() {
return photosList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView contactimageView;
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
contactimageView = (ImageView) itemView.findViewById(R.id.imageview);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
/* Intent intent = new Intent(context, ChatActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Position,getAdapterPosition());
context.startActivity(intent);*/
}
public void add(Photos photos){
photosList.add(photos);
}
}
Photos
public class Photos {
private String photoUrl;
public Photos() {
}
public Photos(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
This is my code. I am uploading an image on click of FloatingAction button to Firebase Storage.The image gets uploaded successfully, but I am not able to retrieve the image to the ImageView of my RecyclerView. What am I doing wrong? I am also able to see url of image in Storage.Still not able to retrieve message in imageview of recyclerview. Please help.......
you can try this also:-
yourFragment.isResumed()

Categories

Resources