Call adapter.notifyItemChanged(position); working so weird - java

I have a list that I get from firebase, this list is about posts and what I need is when user like it or unlike it, the list updated through adapter. as I used recyclerview and adapter to show my data after receiving it from firebase. Actually, everything works so fine with me but just this issue when user like or unlike the post it goes crazy. I tried to make a toast to make sure that I'm working with the same position as I expected and it proved me right.
the photo of the post appears and disappears by clicking like button like the vides shows and it does not updating the data in a proper way like it mess with the number of likes
You can find my code below with a video to illustrate the problem I am facing.
I hope somebody can help me out.
private void read_posts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//post_models.clear();
Post_Model post_model = dataSnapshot.getValue(Post_Model.class);
post_models.add(post_model);
post_adapter = new Post_Adapter(post_models, getContext());
recyclerviewNewsfeed.setAdapter(post_adapter);
progressBar.setVisibility(View.GONE);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Post_Model post_model = dataSnapshot.getValue(Post_Model.class);
for (int i=0;i<post_models.size();i++){
if(post_models.get(i).getId().equals(post_model.getId())){
post_models.set(i,post_model);
post_adapter.notifyItemChanged(i);
break;
}
}
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
It's my post adapter
public class Post_Adapter extends RecyclerView.Adapter<Post_Adapter.Viewholder> {
private Context context;
private List<Post_Model> post_models;
FirebaseUser firebaseUser;
List<Like_Model> like_modelList, likeblue_modelList;
View_Photos_Adapter view_Photos_adapter;
boolean userlikeit;
public static int positionn=-1;
public Post_Adapter(List<Post_Model> post_models, Context context) {
this.context = context;
this.post_models = post_models;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.post_item, parent, false);
return new Viewholder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final Viewholder holder, final int position) {
final Post_Model post_model = post_models.get(position);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference referencee = FirebaseDatabase.getInstance().getReference("Posts").child(post_model.getId());
referencee.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Toast.makeText(CommentActivity.this, post_id+"", Toast.LENGTH_SHORT).show();
Post_Model post_modell = dataSnapshot.getValue(Post_Model.class);
// Toast.makeText(CommentActivity.this, post_id+"", Toast.LENGTH_SHORT).show();
if (post_modell.getLikeModels() != null) {
for (int i = 0; i < post_modell.getLikeModels().size(); i++) {
if (post_modell.getLikeModels().get(i).getUserid().equals(firebaseUser.getUid())) {
userlikeit = true;
break;
} else {
userlikeit = false;
}
}
} else {
userlikeit = false;
}
//snapshot.getRef().removeValue();
// Toast.makeText(context, userlikeit+"58", Toast.LENGTH_SHORT).show();
//Toast.makeText(CommentActivity.this, comment_models.size()+"", Toast.LENGTH_SHORT).show();
if (userlikeit) {
holder.likebluebtn.setVisibility(View.VISIBLE);
holder.likebtn.setVisibility(View.GONE);
} else {
holder.likebtn.setVisibility(View.VISIBLE);
holder.likebluebtn.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (post_model.getUserid().equals(firebaseUser.getUid())) {
holder.editbtn.setVisibility(View.VISIBLE);
holder.deletebtn.setVisibility(View.VISIBLE);
} else {
holder.editbtn.setVisibility(View.GONE);
holder.deletebtn.setVisibility(View.GONE);
}
holder.editbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.postTextView.setVisibility(View.GONE);
holder.postEditText.setVisibility(View.VISIBLE);
holder.postEditText.setText(post_model.getPost());
holder.editbtn.setVisibility(View.GONE);
holder.savebtn.setVisibility(View.VISIBLE);
}
});
holder.savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Post_Model post_modell = new Post_Model(post_model.getId(), post_model.getUserid()
, holder.postEditText.getText().toString(), post_model.getTime()
, post_model.getCommentModels(), post_model.getPostphotos(), post_model.getLikeModels());
FirebaseDatabase.getInstance().getReference("Posts")
.child(post_model.getId())
.setValue(post_modell);
holder.postTextView.setVisibility(View.VISIBLE);
holder.postEditText.setVisibility(View.GONE);
holder.editbtn.setVisibility(View.VISIBLE);
holder.savebtn.setVisibility(View.GONE);
Toast.makeText(context, "Post has been edited successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, NewsfeedActivity.class);
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
((Activity) context).finish();
}
});
holder.deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(context)
.setTitle("Delete Post")
.setMessage("Are you sure you want to delete this post?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final DatabaseReference referencee = FirebaseDatabase.getInstance().getReference("Posts")
.child(post_model.getId());
referencee.removeValue();
Toast.makeText(context, "Post deleted successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, NewsfeedActivity.class);
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
((Activity) context).finish();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
like_modelList = new ArrayList<>();
likeblue_modelList = new ArrayList<>();
//Toast.makeText(context, read_likes(post_model.getId())+"", Toast.LENGTH_SHORT).show();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
// Toast.makeText(Create_Coworking_SpaceActivity.this, "111111111", Toast.LENGTH_LONG).show();
if (user.getId().equals(post_model.getUserid())) {
if (user.getImageURL().equals("default")) {
holder.userImage.setImageResource(R.drawable.ic_imgprofile);
} else {
Glide.with(holder.itemView).load(user.getImageURL()).into( holder.userImage);
}
holder.username.setText(user.getUsername());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (post_model.getPostphotos() == null) {
holder.postPhotosRC.setVisibility(View.GONE);
} else {
holder.postPhotosRC.setHasFixedSize(true);
holder.postPhotosRC.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
view_Photos_adapter = new View_Photos_Adapter(post_model.getPostphotos(), context);
holder.postPhotosRC.setAdapter(view_Photos_adapter);
}
holder.postTextView.setText(post_model.getPost());
holder.posttimeTextView.setText(post_model.getTime());
holder.commentbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
}
});
if (post_model.getCommentModels() != null) {
holder.numofcommentsEditText.setText(post_model.getCommentModels().size() + "");
holder.numofcommentsTextView.setText(post_model.getCommentModels().size() + "");
}
final int[] li = {0};
holder.likebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
like(post_model.getId());
// Post_Adapter.this.notifyItemChanged(position);
positionn=position;
}
});
holder.likebluebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, userlikeit+"5", Toast.LENGTH_SHORT).show();
unlike(post_model.getId());
// Post_Adapter.this.notifyItemChanged(position);
positionn=position;
}
});
if (post_model.getLikeModels() != null) {
holder.numoflikesEditText.setText(post_model.getLikeModels().size() + "");
holder.numoflikesTextView.setText(post_model.getLikeModels().size() + "");
}
holder.likesTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, LikeActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
}
});
holder.commentsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity)
context).overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_in_left);
}
});
}
#Override
public int getItemCount() {
return post_models == null ? 0 : post_models.size();
}

Related

Link a TextView value to firebase database ID

I want to link a TextView value to my database item ID. And then get the children that are under my database item in a TextView.
When I scan a Barcode with the value 7, I also want the to populate a TextView with for example toolName from the database Item with ID 7.
I've tried and tried, but I don't know how to complete this.
MainActivity:
public class UserMainActivity extends AppCompatActivity {
TextView textusername, textworkid, textuserloggedin;
Button btnalltools, qrscan;
DatabaseReference databaseUsers, databaseTools;
FirebaseAuth firebaseAuth;
FirebaseUser user;
String userID;
String toolid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_main);
firebaseAuth = FirebaseAuth.getInstance();
databaseTools = FirebaseDatabase.getInstance("").getReference("Tools");
textusername = (TextView)findViewById(R.id.tv_textusername);
textworkid = (TextView)findViewById(R.id.tv_textuserworkid);
qrscan = (Button)findViewById(R.id.btn_qrscantoolactivity);
qrscan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(UserMainActivity.this);
intentIntegrator.setPrompt("For flash use volume up key");
intentIntegrator.setBeepEnabled(true);
intentIntegrator.setOrientationLocked(true);
intentIntegrator.setCaptureActivity(Capture.class);
intentIntegrator.initiateScan();
}
});
btnalltools = (Button)findViewById(R.id.btn_alltoollist);
btnalltools.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(UserMainActivity.this, ToollistAllActivity.class);
startActivity(intent1);
}
});
user = FirebaseAuth.getInstance().getCurrentUser();
databaseUsers = FirebaseDatabase.getInstance("").getReference("Users");
userID = user.getUid();
toolid = databaseTools.getKey();
databaseUsers.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
User userprofile = snapshot.getValue(User.class);
if (userprofile != null) {
String user = userprofile.getUserName();
String userid = userprofile.getUserWorkId();
textusername.setText(user);
textworkid.setText(userid);
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable #org.jetbrains.annotations.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult.getContents() != null){
AlertDialog.Builder builder = new AlertDialog.Builder(UserMainActivity.this);
builder.setMessage(intentResult.getContents());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
});
builder.show();
}else{
Toast.makeText(getApplicationContext(), "Opps", Toast.LENGTH_SHORT).show();
}
}
I've tried something like this:
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult.getContents() != null){
TextView tv1 = dialog.findViewById(R.id.tv1);
TextView tv2 = dialog.findViewById(R.id.tv2);
tv1.setText(intentResult.getContents());
databaseTools.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (snapshot.hasChildren()){
if (tv1.getText().toString().equals(databaseTools)){
Tool tools = snapshot.getValue(Tool.class);
String tt = tools.getToolID();
tv2.setText(tt);
}
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
}
});
I've got it to work with this:
Query gettool = databaseTools.orderByChild("toolID").equalTo(tv1.getText().toString());
gettool.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot snapshot1 : snapshot.getChildren()){
Tool tools = snapshot1.getValue(Tool.class);
String tt = tools.getToolName();
tv2.setText(tt);
}

deletes everything from the database,the getRef() method does not work because i cant put my dialog inside the FirebaseRecyclerAdapter

RETRIEVADATA CLASS
package com.dikolobe.salesagent;
public class RetrieveData extends AppCompatActivity implements View.OnClickListener,OnNoteClickListener{
private static final String TAG = "";
private FirebaseRecyclerAdapter<Product, ViewHolder> firebaseRecyclerAdapter;
//FirebaseRecyclerAdapter adapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
ItemsAdapter itemsAdapter;
List<Product> productList=new ArrayList<>();
RecyclerView recyclerView;
TextView phone_num;
ViewHolder viewHolder;
private static final int PERMISSION_REQUEST_CODE = 1;
ImageView img;
OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems= new ArrayList<>();
private List<Product> listItemsFull;
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
String imageUrl = null;
SearchView searchView;
//ImageView delete;
String productId;
String image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve_data);
// delete =findViewById(R.id.delete);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to SEND_SMS - requesting it");
String[] permissions = {Manifest.permission.SEND_SMS};
requestPermissions(permissions, PERMISSION_REQUEST_CODE);
}
}
searchView=findViewById(R.id.search);
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance().getReference()
.child("Items"),Product.class)
.build();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
recyclerView = findViewById(R.id.recyclerview_id);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<Product>();
itemsAdapter = new ItemsAdapter(RetrieveData.this, productList,this,options);
recyclerView.setAdapter(itemsAdapter);
mRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Product product = dataSnapshot.getValue(Product.class);
productList.add(product);
itemsAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onStart(){
super.onStart();
FirebaseRecyclerOptions<Product> options = new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(FirebaseDatabase.getInstance()
.getReference().child("Items"), Product.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull com.dikolobe.salesagent.ViewHolder holder, final int
position, #NonNull Product product) {
}
#NonNull
#Override
public com.dikolobe.salesagent.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.design_row_for_recyclerview, parent, false);
return new com.dikolobe.salesagent.ViewHolder(view,onNoteClickListener);
}
public void deleteProduct(int position) {
try{
FirebaseDatabase.getInstance().getReference().child("Items")
.child(getRef(position).getKey())
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(context,"Deleted succesfully",Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e){
Log.e("error", e.getMessage());
}
}
};
firebaseRecyclerAdapter.startListening();
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStop() {
super.onStop();
firebaseRecyclerAdapter.stopListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
MenuItem menuItem=menu.findItem(R.id.search);
SearchView searchView=(SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
search_product(query);
// itemsAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search_product(newText);
//itemsAdapter.getFilter().filter(newText.toString());
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.add_product) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "post a product", Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.tutorial) {
// startActivity(new Intent(this, AddRider.class));
// Toast.makeText(this,"Add a rider to an Event",Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.logOut) {
startActivity(new Intent(this, MainActivity.class));
Toast.makeText(this, "bye", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
ItemTouchHelper.SimpleCallback simpleCallback=new
ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, Re
cyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
removeItem((long) viewHolder.itemView.getTag());
productList.remove(viewHolder.getAdapterPosition());
itemsAdapter.notifyDataSetChanged();
}
private void removeItem(long id) {
}
};
private boolean updateItem(String seller, String description, String price,String location,String
phone,String productId,String image,String posted_date) {
//getting the specified product reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Items").child(productId);
//updating product
Product product = new Product(productId, seller,
description,price,phone,location,image,posted_date);
dR.setValue(product);
Toast.makeText(getApplicationContext(), "Product Updated", Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onNoteClick(final int position) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(RetrieveData.this);
dialog.setTitle("Choose Action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Intent update_activty = new Intent(getApplicationContext(),Update_Product.class);
startActivity(update_activty);
}
if (i==1){
Product product=productList.get(position);
productId =product.getProductId();
image =product.getImage();
final AlertDialog.Builder dialogdelete = new
AlertDialog.Builder(RetrieveData.this);
dialogdelete.setTitle("Warning");
dialogdelete.setMessage("Are You Sure You Want to Delete?");
dialogdelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Query mQuery = mRef.orderByChild("productId").equalTo(productId);
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
Toast.makeText(RetrieveData.this,"deleted..!",Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(RetrieveData.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Query mPictureReference =
FirebaseDatabase.getInstance().getReference("Items").orderByChild("image").equalTo(image);
mPictureReference.getRef().removeValue().addOnSuccessListener(new
OnSuccessListener() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RetrieveData.this,"Image
deleted",Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RetrieveData.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
dialogdelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialogdelete.show();
}
}
});
dialog.show();
// Toast.makeText(getApplicationContext(),"cliked",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
}
public static String getTimeDate(long timestamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timestamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
}
ADAPTER CLASS
package com.dikolobe.salesagent;
public class ItemsAdapter extends RecyclerView.Adapter implements Filterable {
public ArrayList<Product> filterList = new ArrayList<>();
private int progressStatus = 0;
private Handler handler = new Handler();
private OnNoteClickListener onNoteClickListener;
Context context;
private List<Product> listItems;
private List<Product> listItemsFull;
private Product product;
FirebaseRecyclerOptions<Product> options;
String imageUrl = null;
public ItemsAdapter(Context context, List<Product> listItems,OnNoteClickListener
onNoteClickListener,FirebaseRecyclerOptions options) {
this.context = context;
this.listItems = listItems;
listItemsFull = new ArrayList<>(listItems);
this.onNoteClickListener = onNoteClickListener;
this.options=options;
}
public ItemsAdapter(FirebaseRecyclerOptions<Product> options) {
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.design_row_for_recyclerview,parent,false);
return new ViewHolder(v,onNoteClickListener);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
product = listItems.get(position);
holder.seller.setText(listItems.get(position).getSeller());
holder.desc.setText(listItems.get(position).getDescription());
holder.price.setText(listItems.get(position).getPrice());
holder.location.setText(listItems.get(position).getLocation());
holder.phone.setText(listItems.get(position).getPhone());
holder.time.setText((CharSequence) listItems.get(position).getPosted_date());
holder.progress_Bar = new ProgressBar(context);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
handler.post(new Runnable() {
public void run() {
holder.progressBar.setProgress(progressStatus);
holder.textView.setText(progressStatus+"/"+holder.progressBar.getMax());
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
imageUrl = product.getImage();
Picasso.get().load(imageUrl).into(holder.imageView, new Callback() {
#Override
public void onSuccess() {
holder.image_layout.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
holder.phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
if (id==R.id.phoneTv){
String phoneNumber = product.getPhone();
String message = "I am interested";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(context,"Interest message sent successfully",
Toast.LENGTH_LONG).show();
}
}
});
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
if(id==R.id.call){
String phoneNumber = product.getPhone();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phoneNumber));
context.startActivity(intent);
}
}
}); }
#Override
public int getItemCount() {
return listItems.size();
}
#Override
public Filter getFilter() {
return filterProducts;
}
private Filter filterProducts = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
///*to delete*/String search_text = constraint.toString().toLowerCase();
List<Product> productFiltrate = new ArrayList<>();
if (constraint.length()==0 ){
productFiltrate.addAll(listItemsFull);
}else
{
String pattern = constraint.toString().toLowerCase().trim();
for (Product product:listItemsFull){
if(product.getSeller().toLowerCase().contains(pattern)){
productFiltrate.add(product);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = productFiltrate;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList.clear();
filterList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
INSERT DATA/MAIN_ACTIVITY
package com.dikolobe.salesagent;
public class MainActivity extends AppCompatActivity {
FirebaseRecyclerAdapter firebaseRecyclerAdapter;
ItemsAdapter itemsAdapter;
FirebaseDatabase mDatabase;
DatabaseReference mRef;
FirebaseStorage mStorage;
EditText seller_name,desc,price,location,phone;
Button btnInsert,list;
ImageButton imageButton,take_Photo;
ProgressBar progressBar;
private ProgressDialog mProgress;
Uri imageUri = null;
final int REQUEST_CODE_IMAGE=999;
static final int REQUEST_IMAGE_CAPTURE = 1;
private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();
ViewHolder holder;
FrameLayout image_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seller_name = findViewById(R.id.seller_nameEt);
desc = findViewById(R.id.descEt);
price = findViewById(R.id.priceEt);
location = findViewById(R.id.locationEt);
phone = findViewById(R.id.phoneEt);
btnInsert = findViewById(R.id.save);
//list = findViewById(R.id.list);
imageButton = findViewById(R.id.imageButton);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.textView);
image_layout = (FrameLayout) findViewById(R.id.layout_image);
take_Photo = (ImageButton) findViewById(R.id.take_pic);
take_Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (id==R.id.take_pic){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
});
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference().child("Items");
mStorage = FirebaseStorage.getInstance();
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_IMAGE);
}
});
progressBar = new ProgressBar(MainActivity.this);
image_layout.setVisibility(View.INVISIBLE);
btnInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_layout.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
//current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
try {
// Sleep for 200 milliseconds.
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
final String seller = seller_name.getText().toString().trim();
final String fn = desc.getText().toString().trim();
final String ln = price.getText().toString().trim();
final String place = location.getText().toString().trim();
final String phon = phone.getText().toString().trim();
final String id = mRef.push().getKey();
if (!(seller.isEmpty() && fn.isEmpty() && ln.isEmpty() && place.isEmpty() &&
phon.isEmpty() && imageUri!=null)){
StorageReference filepath =
mStorage.getReference().child("images").child(imageUri.getLastPathSegment());
filepath.putFile(imageUri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
image_layout.setVisibility(View.INVISIBLE);
Task<Uri> downloadUrl =
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String t=task.getResult().toString();
final DatabaseReference newPost=mRef.push();
newPost.child("seller").setValue(seller);
newPost.child("description").setValue(fn);
newPost.child("price").setValue(ln);
newPost.child("location").setValue(place);
newPost.child("phone").setValue(phon);
newPost.child("productId").setValue(id);
newPost.child("image").setValue(task.getResult().toString());
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String strDate = dateFormat.format(date).toString();
newPost.child("posted_date").setValue(strDate);
Toast.makeText(MainActivity.this,"successfully uploaded",
Toast.LENGTH_SHORT).show();
seller_name.setText("");
desc.setText("");
price.setText("");
location.setText("");
phone.setText("");
imageButton.setImageURI(null);
goToRetrieveDataClass();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Failed to
upload..!",Toast.LENGTH_LONG).show();
}
});
}
});
}else Toast.makeText(MainActivity.this,"Please write all your
details..!",Toast.LENGTH_LONG).show();
}
});
if (!hasCamera())
take_Photo.setEnabled(false);
}
#Override
protected void onStart() {
super.onStart();
// firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
// firebaseRecyclerAdapter.stopListening();
}
private Boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
if (requestCode == REQUEST_CODE_IMAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
gallery.setType("image/*");
startActivityForResult(gallery, REQUEST_CODE_IMAGE);
} else {
Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
imageUri = data.getData();
CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1).start(this);
imageButton.setImageURI(imageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Exception error = result.getError();
}
}
super.onActivityResult(requestCode, resultCode,data);
}
}

Recyclerview's Onscroll is not working while fetching data from firebase

I want to add onScroll Listener, but recyclerview's addonScrollListner() method is not doing anything, I want to fetch next ten items on every recyclerview's scroll.
At first time the data is fetching fine, but when i am scrolling recyclerview then nothing is happening, i am not able to find out why is this happening.
It is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView_con);
progressBar = findViewById(R.id.contentprogressbar);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
recyclerView = findViewById(R.id.listview);
mSwipeRefreshLayout = findViewById(R.id.swipeContainer);
textView = findViewById(R.id.emptylist);
backbtncontent = findViewById(R.id.backbtncntent);
backbtncontent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ContentActivity.this, HomeActivity.class);
startActivity(i);
}
});
classname = getIntent().getStringExtra("classname");
if (classname.equals("A")) {
content = getIntent().getStringExtra("jokecontent");
} else if (classname.equals("B")) {
content = getIntent().getStringExtra("shayaricontent");
}
getLastKeyFromFirebase();
final LinearLayoutManager layoutManager= new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
arrayAdapter = new NewAdapterContent(contentname,this);
recyclerView.setAdapter(arrayAdapter);
getUsers();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
total_item = layoutManager.getItemCount();
last_visible_item = layoutManager.findLastCompletelyVisibleItemPosition();
if(!isLoading && total_item<=((last_visible_item+ITEM_LOAD_COUNT))){
getUsers();
isLoading = true;
}
}
});
}
private void getUsers()
{
if (!isMaxData) {
Query query;
if (classname.equals("A")) {
if (TextUtils.isEmpty(last_nodes)) //wait content to aa n raehre
query = FirebaseDatabase.getInstance().getReference("ContentJokes")
.orderByChild("subcategory")
.equalTo(content)
.limitToFirst(ITEM_LOAD_COUNT);
else
query = FirebaseDatabase.getInstance().getReference("ContentJokes")
.orderByChild("subcategory")
//.equalTo(content)
.startAt(last_nodes)
.limitToFirst(ITEM_LOAD_COUNT);
//1 sec wait cll ari kisi ki
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (!dataSnapshot.exists()) {
//hello ?
isLoading = false;
isMaxData = true;
// progressBar.setVisibility(View.GONE);
Toast.makeText(ContentActivity.this, "There is no jokes present under this category", Toast.LENGTH_SHORT).show();
} else {
String contentdisplay = dataSnapshot.child("content").getValue(String.class);
String key = dataSnapshot.child("content").getKey();
ContentModel contentModel = new ContentModel(contentdisplay, key);
contentname.add(0, contentModel);
arrayAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
arrayAdapter.notifyItemInserted(0);
last_nodes = contentname.get(contentname.size() - 1).getId();
if (!last_nodes.equals(last_key)) {
} else
last_nodes = last_key;
isLoading = false;
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else if(classname.equals("B")){
if (TextUtils.isEmpty(last_nodes)) //wait content to aa n raehre
query = FirebaseDatabase.getInstance().getReference("ContentShayari")
.orderByChild("subcategory")
.equalTo(content)
.limitToFirst(ITEM_LOAD_COUNT);
else
query = FirebaseDatabase.getInstance().getReference("ContentShayari")
.orderByChild("subcategory")
.equalTo(content)
.startAt(last_nodes)
.limitToFirst(ITEM_LOAD_COUNT);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (!dataSnapshot.exists()) {
isLoading = false;
isMaxData = true;
// progressBar.setVisibility(View.GONE);
Toast.makeText(ContentActivity.this, "There is no jokes present under this category", Toast.LENGTH_SHORT).show();
} else {
String contentdisplay = dataSnapshot.child("content").getValue(String.class);
String key = dataSnapshot.child("content").getKey();
ContentModel contentModel = new ContentModel(contentdisplay, key);
contentname.add(0, contentModel);
arrayAdapter.notifyDataSetChanged();
// progressBar.setVisibility(View.GONE);
arrayAdapter.notifyItemInserted(0);
last_nodes = contentname.get(contentname.size() - 1).getId();
if (!last_nodes.equals(last_key)) {
} else
last_nodes = last_key;
isLoading = false;
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
private void getLastKeyFromFirebase() {
Query getLastKey;
if (classname.equals("A")) {
getLastKey = FirebaseDatabase.getInstance().getReference()
.child("ContentJokes")
.orderByChild("subcategory").equalTo(content)
.limitToLast(1);
getLastKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot lastKey : dataSnapshot.getChildren()) {
last_key = lastKey.getKey();
Toast.makeText(ContentActivity.this, String.valueOf(last_key), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ContentActivity.this, "cannot get last key", Toast.LENGTH_SHORT).show();
}
});
} else if (classname.equals("B")) {
getLastKey = FirebaseDatabase.getInstance().getReference()
.child("ContentShayari")
.orderByChild("subcategory").equalTo(content)
.limitToLast(1);
getLastKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot lastKey : dataSnapshot.getChildren()) {
last_key = lastKey.getKey();
Toast.makeText(ContentActivity.this, String.valueOf(last_key), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ContentActivity.this, "cannot get last key", Toast.LENGTH_SHORT).show();
}
});
}
}
RecyclerAdapter Code:
public class NewAdapterContent extends RecyclerView.Adapter<NewAdapterContent.ViewHolder> {
ArrayList<ContentModel>contentModels;
Context context;
public NewAdapterContent(ArrayList<ContentModel>contentModels, Context context) {
this.contentModels = contentModels;
this.context = context;
}
public void addAll(ArrayList<ContentModel>contentModels){
int initSize = contentModels.size();
contentModels.addAll(contentModels);
notifyItemRangeChanged(initSize, contentModels.size());
}
public String getLastItemId(){
return contentModels.get(contentModels.size()-1).getId();
}
#NonNull
#Override
public NewAdapterContent.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NewAdapterContent.ViewHolder holder, int position) {
holder.textView.setText(contentModels.get(position).getContent());
}
#Override
public int getItemCount() {
return contentModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.contentText);
}
}
}
Anytime of help would be appreciated. Please help.
Try it which is very easy to use that was worked for me by using the custom RecyclerView.OnScrollListener named EndlessRecyclerViewScrollListener -
EndlessRecyclerViewScrollListener scrollListener = new
EndlessRecyclerViewScrollListener(layoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
if(!isLoading){
getUsers();
isLoading = true;
}
}
};
recyclerView.addOnScrollListener(scrollListener);

My activity goes to previous activity when firebase database change is detected

Thats the Fragment containing the recyclerView which leads to activity with Chat
public class FragmentBusinessHome extends Fragment {
/* For to do adapter */
private List<String> namesToDo;
private List<String> uids;
private List<String> servicesNames;
private AdapterToDo adapterToDo;
private RecyclerView toDoRecyclerView;
/* For checking requests adapter */
private List<String> userUids;
private List<String> serviceNames;
private List<String> userNames;
private AdapterPendingRequests adapterPendingRequests;
private RecyclerView pendingRequestsRecyclerView;
private FirebaseAuth mAuth;
public FragmentBusinessHome(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_business_home, container, false);
mAuth = FirebaseAuth.getInstance();
namesToDo = new ArrayList<>();
uids = new ArrayList<>();
servicesNames = new ArrayList<>();
userUids = new ArrayList<>();
serviceNames = new ArrayList<>();
userNames = new ArrayList<>();
toDoRecyclerView = view.findViewById(R.id.toDoRecyclerView);
pendingRequestsRecyclerView = view.findViewById(R.id.requestsToApproveRecyclerView);
LinearLayoutManager layoutManagerActive = new LinearLayoutManager(getActivity());
layoutManagerActive.setStackFromEnd(true);
layoutManagerActive.setReverseLayout(true);
toDoRecyclerView.setLayoutManager(layoutManagerActive);
LinearLayoutManager layoutManagerPendingRequests = new LinearLayoutManager(getActivity());
layoutManagerPendingRequests.setStackFromEnd(true);
layoutManagerPendingRequests.setReverseLayout(true);
pendingRequestsRecyclerView.setLayoutManager(layoutManagerPendingRequests);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference checkRequests = FirebaseDatabase.getInstance().getReference("Providers").child(uid).child("Gigs");
checkRequests.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (ds.getValue(String.class).equals("active")) {
DatabaseReference getRequests = FirebaseDatabase.getInstance().getReference("Services").child(ds.getKey()).child(uid).child("Gigs").child("pending");
getRequests.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
serviceNames.clear(); userNames.clear(); userUids.clear();
for (DataSnapshot data : dataSnapshot.getChildren()) {
String userName = data.child("names").getValue(String.class);
String serviceName = ds.getKey();
String userUid = data.getKey();
userNames.add(userName);
serviceNames.add(serviceName);
userUids.add(userUid);
adapterPendingRequests = new AdapterPendingRequests(getActivity(), userUids, userNames, serviceNames, mAuth.getCurrentUser().getUid());
adapterPendingRequests.notifyDataSetChanged();
pendingRequestsRecyclerView.setAdapter(adapterPendingRequests);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DatabaseReference getActive = FirebaseDatabase.getInstance().getReference("Services").child(ds.getKey()).child(uid).child("Gigs").child("active");
getActive.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userUids.clear(); namesToDo.clear(); servicesNames.clear();
for(DataSnapshot datas : dataSnapshot.getChildren()){
String userUid = datas.getKey();
String userName = datas.child("names").getValue(String.class);
String serviceName = ds.getKey();
userUids.add(userUid);
namesToDo.add(userName);
servicesNames.add(serviceName);
Log.d("TAG", userUids.toString());
adapterToDo = new AdapterToDo(getActivity(), namesToDo, userUids, servicesNames);
adapterToDo.notifyDataSetChanged();
toDoRecyclerView.setAdapter(adapterToDo);
if(!userUids.isEmpty()){
LinearLayout toDoLayout = view.findViewById(R.id.toDoLayout);
toDoLayout.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
Thats fragment's activity
private ImageButton moreBtn, chatsBtn;
private BottomNavigationView bottomNavigationView;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_home);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentBusinessHome()).commit();
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationListener);
moreBtn = findViewById(R.id.moreBtn);
chatsBtn = findViewById(R.id.chatsBtn);
moreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final PopupMenu popup = new PopupMenu(BusinessHomeActivity.this, moreBtn);
popup.getMenuInflater().inflate(R.menu.popup_toolbar_more_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_btn:
mAuth.signOut();
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Intent to_login_activity = new Intent(BusinessHomeActivity.this, WelcomeActivity.class);
startActivity(to_login_activity);
finish();
}
}, 1000);
}
return true;
}
});
}
});
chatsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(BusinessHomeActivity.this, "Will be available soon!", Toast.LENGTH_LONG).show();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.home:
selectedFragment = new FragmentBusinessHome();
break;
case R.id.inbox:
selectedFragment = new FragmentInbox();
break;
case R.id.profile:
selectedFragment = new FragmentProfile();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, selectedFragment).commit();
return true;
}
};
That's the adapter for the fragment
public class AdapterToDo extends RecyclerView.Adapter<AdapterToDo.MyHolder> {
Context context;
List<String> namesToDo;
List<String> uids;
List<String> servicesNames;
public AdapterToDo(Context context, List<String> namesToDo, List<String> uids, List<String> servicesNames) {
this.context = context;
this.namesToDo = namesToDo;
this.uids = uids;
this.servicesNames = servicesNames;
}
#NonNull
#Override
public AdapterToDo.MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.to_do_item, parent, false);
return new AdapterToDo.MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final AdapterToDo.MyHolder holder, final int position) {
holder.userNames.setText(namesToDo.get(position));
String currentUid = uids.get(position);
String currentOppositeName = namesToDo.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent to_chat_activity = new Intent(context, ChatActivity.class);
to_chat_activity.putExtra("oppositeUid", currentUid);
to_chat_activity.putExtra("oppositeNames", currentOppositeName);
to_chat_activity.putExtra("class", getClass().getName());
context.startActivity(to_chat_activity);
}
});
}
#Override
public int getItemCount() {
return uids.size();
}
class MyHolder extends RecyclerView.ViewHolder {
private TextView userNames;
private MyHolder(#NonNull View itemView) {
super(itemView);
userNames = itemView.findViewById(R.id.userNames);
}
}
}
That is the Activity where the fragment's adapter leads to
private String oppositeUid, oppositeNames, className;
private TextView oppositeNamesTextView;
private Button sendBtn;
private EditText message;
private FirebaseAuth mAuth;
private RecyclerView recyclerView;
private List<ModelChat> modelChatList;
private AdapterChat chatAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
Intent intent = getIntent();
oppositeUid = intent.getStringExtra("oppositeUid");
oppositeNames = intent.getStringExtra("oppositeNames");
className = intent.getStringExtra("class");
Log.d("CLASSNAME", className);
modelChatList = new ArrayList<>();
oppositeNamesTextView = findViewById(R.id.oppositeNames);
sendBtn = findViewById(R.id.sendBtn);
message = findViewById(R.id.message);
recyclerView = findViewById(R.id.chatRecyclerView);
LinearLayoutManager linearLayout = new LinearLayoutManager(this);
linearLayout.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayout);
oppositeNamesTextView.setText(oppositeNames);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String mMessage = message.getText().toString().trim();
if(!TextUtils.isEmpty(mMessage)){
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("sender", mAuth.getCurrentUser().getUid());
hashMap.put("receiver", oppositeUid);
hashMap.put("message", mMessage);
hashMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
if(className.equals("com.example.uploy.AdapterToDo$1")){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Users").child(oppositeUid).child("Chats").child(mAuth.getCurrentUser().getUid());
databaseReference1.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}else{
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(oppositeUid).child("Chats").child(mAuth.getCurrentUser().getUid());
databaseReference.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference1.push().setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
message.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ChatActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
if(className.equals("com.example.uploy.AdapterToDo$1")){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Providers").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
modelChatList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("details")){
continue;
}
ModelChat modelChat = snapshot.getValue(ModelChat.class);
modelChatList.add(modelChat);
chatAdapter = new AdapterChat(ChatActivity.this, modelChatList);
chatAdapter.notifyDataSetChanged();
recyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else{
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Chats").child(oppositeUid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
modelChatList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("details")){
continue;
}
ModelChat modelChat = snapshot.getValue(ModelChat.class);
modelChatList.add(modelChat);
chatAdapter = new AdapterChat(ChatActivity.this, modelChatList);
chatAdapter.notifyDataSetChanged();
recyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Log.d("TAG", "PRESSED");
}
The PROBLEM is that when the fragment opens the activity (it contains messages in chat between to users, which are loaded perfectly fine) and the activity detects any change in the chats database reference it stops and loads the previous activity (where the fragment is placed). I wonder what the solution is and I would be glad if you help me.

error: cannot find symbol method getDownloadUrl()

I'm still a beginner in programming. I'm developing an application for a college job. However, I came across this mistake. I do not know how I can fix it. This problem:
error: cannot find symbol method getDownloadUrl()
How can I solve this error?
Here is my code:
package com.valcirjr98.logindj;
$public class ProfileActivity extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
TextView textView;
ImageView imageView;
EditText editText;
Uri uriProfileImage;
ProgressBar progressBar;
String profileImageUrl;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editText = (EditText) findViewById(R.id.editTextDisplayName);
imageView = (ImageView) findViewById(R.id.imageView);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
textView = (TextView) findViewById(R.id.textViewVerified);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
loadUserInformation();
findViewById(R.id.buttonSave).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveUserInformation();
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
finish();
startActivity(new Intent(this, MainActivity.class));
}
}
private void loadUserInformation() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getPhotoUrl() != null) {
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
if (user.isEmailVerified()) {
textView.setText("Email Verified");
} else {
textView.setText("Email Not Verified (Click to Verify)");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(ProfileActivity.this, "Verification Email Sent", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
}
private void saveUserInformation() {
String displayName = editText.getText().toString();
if (displayName.isEmpty()) {
editText.setError("Name required");
editText.requestFocus();
return;
}
FirebaseUser user = mAuth.getCurrentUser();
if (user != null && profileImageUrl != null) {
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
.setDisplayName(displayName)
.setPhotoUri(Uri.parse(profileImageUrl))
.build();
user.updateProfile(profile)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ProfileActivity.this, "Profile Updated", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uriProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
imageView.setImageBitmap(bitmap);
uploadImageToFirebaseStorage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImageToFirebaseStorage() {
StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, MainActivity.class));
break;
}
return true;
}
private void showImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Profile Image"), CHOOSE_IMAGE);
}
}
profileImageRef.putFile(uriProfileImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileImageUrl= taskSnapshot.getDownloadUrl().toString();
}
});
*
This method worked for me.
profileImageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful() && task != null) {
profileImageUrl = task.getResult().getDownloadUrl().toString();
}
}
});
Try this!

Categories