I stored texts and images in firebase Storage, here's how my images path looks like in storage (1655329886202.jpg),
and here's ow they look in realtime database (https://firebasestorage.googleapis.com/v0/b/link-plus-8e35e.appspot.com/etc...)
I retrieved the texts but can't retrieve the images to the recycler view, I'm new to programming.
here is the code.
adapter :
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.name);
imageView = itemView.findViewById(R.id.image_View_car);
}
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.dynamic_rv_item_layout, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Glide.with(mContext)
.load(uploadCurrent.getImageUrl())
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
}
Main activity code
ActivityResultLauncher<String> mGetContent = registerForActivityResult(
new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
if (result != null) {
mImageView.setImageURI(result);
mImageUri = result;
}
}
}
);
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(FireBaseImage.this, "Upload in progress", Toast.LENGTH_LONG).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(FireBaseImage.this, "Upload Successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getUploadSessionUri().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(FireBaseImage.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot Snapshot) {
double progress = (100.0 * Snapshot.getBytesTransferred() / Snapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
}
Related
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);
}
}
I've recently learned of ListAdapter and applied to my RecyclerView. I followed a tutorial and the list of items (retrieved from a database via Retrofit) is displayed as expected. However, when I add a new item the list does not update unless I leave the activity and return. What am I missing here?
ViewModel
public class NoteViewModel extends ViewModel {
private static final String TAG = "NoteViewModel";
MutableLiveData<List<Note>> mutableLiveData;
public LiveData<List<Note>> getNoteList(String userID) {
if (mutableLiveData == null) {
mutableLiveData = new MutableLiveData<>();
}
initNoteList(userID);
return mutableLiveData;
}
private void initNoteList(String userID) {
List<Note> noteList = new ArrayList<>();
Call<List<Note>> noteCall = APIClient.getUserService().retrieveUserNotes(userID);
noteCall.enqueue(new Callback<List<Note>>() {
#Override
public void onResponse(Call<List<Note>> call, Response<List<Note>> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
noteList.addAll(response.body());
mutableLiveData.setValue(noteList);
Log.d(TAG, "onResponse: " + noteList.size());
} else {
Log.d(TAG, "onResponse: Retrieve Note List Body Error");
}
} else {
Log.d(TAG, "onResponse: Response Fail");
}
}
#Override
public void onFailure(Call<List<Note>> call, Throwable t) {
Log.d(TAG, "onFailure: Retrieve Note List Failure: " + t.getMessage());
}
});
}
ListAdapter
public class NoteListAdapter extends ListAdapter<Note, NoteListAdapter.NoteViewHolder> {
NoteClickListener noteClickListener;
public NoteListAdapter(#NonNull DiffUtil.ItemCallback<Note> diffCallback, NoteClickListener noteClickListener) {
super(diffCallback);
this.noteClickListener = noteClickListener;
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_item, parent, false);
return new NoteViewHolder(v, noteClickListener);
}
#Override
public void onBindViewHolder(#NonNull NoteViewHolder holder, int position) {
Note note = getItem(position);
assert note != null;
holder.bind(note);
}
public static class NoteViewHolder extends RecyclerView.ViewHolder {
NoteClickListener noteClickListener;
TextView noteTitle;
public NoteViewHolder(View itemView, NoteClickListener noteClickListener) {
super(itemView);
this.noteClickListener = noteClickListener;
noteTitle = itemView.findViewById(R.id.note_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
noteClickListener.onNoteClick(getAbsoluteAdapterPosition());
}
});
public void bind(Note note) {
noteTitle.setText(note.getTitle());
}
}
public interface NoteClickListener {
void onNoteClick(int position);
void onNoteLongClick(int position);
}
Activity
public class NotesList extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
Toolbar toolbar;
FloatingActionButton addNote, deleteNote;
User user;
NoteListAdapter noteListAdapter;
NoteViewModel noteViewModel;
private static final int EDIT_NOTE = 10001;
private static final int SAVE_NOTE = 10002;
private boolean reloadNotes = false;
List<Note> noteList;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes_list);
Intent notes = getIntent();
user = (User) notes.getParcelableExtra("user");
addNote = findViewById(R.id.fab_notes);
deleteNote = findViewById(R.id.delete_notes);
deleteNote.setVisibility(View.GONE);
toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back_24);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotesList.this.onBackPressed();
}
});
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
addNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newNote = new Intent(NotesList.this, CreateUserNote.class);
newNote.putExtra("user", user);
NotesList.this.startActivity(newNote);
}
});
recyclerView = findViewById(R.id.notesRecyclerView);
noteListAdapter = new NoteListAdapter(Note.itemCallback, new NoteListAdapter.NoteClickListener() {
#Override
public void onNoteClick(int position) {
// TODO: Edit Note
Toast.makeText(NotesList.this, noteListAdapter.getCurrentList().get(position).getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNoteLongClick(int position) {
// TODO: Delete Note
}
});
recyclerView.setAdapter(noteListAdapter);
noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
noteViewModel.getNoteList(user.getUser_id()).observe(NotesList.this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
noteListAdapter.submitList(notes);
}
});
}
I found a workaround which is to call submitList() in onActivityResult() after adding a new item. However, I would like to know if this is good programming.
Here is what I added:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SAVE_NOTE) {
if (resultCode == CreateUserNote.RESULT_OK) {
noteListAdapter.submitList(noteViewModel.getNoteList(user.getUser_id()).getValue());
}
}
}
Changed the following:
addNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent newNote = new Intent(NotesList.this, CreateUserNote.class);
newNote.putExtra("user", user);
NotesList.this.startActivityForResult(newNote, SAVE_NOTE);
}
});
Create new item activity retrofit call:
private void saveNote(String user_id, String title, String content) {
Call<String> noteCall = APIClient.getUserService().addUserNote(user_id, title, content);
noteCall.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
if (response.body().equals("true")) {
setResult(CreateUserNote.RESULT_OK);
finish();
} else {
Toast.makeText(CreateUserNote.this, "Save User Note Failure", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(CreateUserNote.this, "Save User Note Failure: " + t.getMessage(), Toast.LENGTH_SHORT).show();
Log.w("Error", "Save User Note Failure: " + t.getMessage());
}
});
}
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();
}
I am displaying image on recyclerView using modal class and adapter class file,
now I want to share images externally and download images on the phone.
but I tried a lot, I am not understanding how to get image URL in adapter file.
Please help me to find a solution.
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
private List<Data> data;
private Context context;
public ImageAdapter(List<Data> data, Context context) {
this.data = data;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_design,parent,false);
return new ImageAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data data1=data.get(position);
ImageView imageView=holder.imageView;
Glide.with(context)
.load(data1.getImgUrl())
.placeholder(R.drawable.logo)
.into(imageView);
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public ImageButton share,download;
public ViewHolder(final View itemView) {
super(itemView);
imageView=(ImageView)itemView.findViewById(R.id.image);
share=(ImageButton)itemView.findViewById(R.id.share);
download=(ImageButton)itemView.findViewById(R.id.download);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "url", Toast.LENGTH_SHORT).show();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,"url here ");
shareIntent.setType("images/*");
context.startActivity(Intent.createChooser(shareIntent,"Send Via"));
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
}
thanks in advance.
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data data1=data.get(position);
ImageView imageView=holder.imageView;
Glide.with(context)
.load(data1.getImgUrl())
.placeholder(R.drawable.logo)
.into(imageView);
}
replace this with
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data data1=data.get(position);
ImageView imageView=holder.imageView;
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "url", Toast.LENGTH_SHORT).show();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,getLocalBitmapUri(getBitmapFromURL(data1.getImgUrl())));
shareIntent.setType("images/*");
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(Intent.createChooser(shareIntent,"Send Via"));
}
});
Glide.with(context)
.load(data1.getImgUrl())
.placeholder(R.drawable.logo)
.into(imageView);
}
also add
public Uri getLocalBitmapUri(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "image" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
and
fun getBitmapFromURL(strURL: String): Bitmap? {
return try {
val url = URL(strURL)
val connection = url.openConnection() as HttpURLConnection
connection.doInput = true
connection.connect()
val input = connection.inputStream
BitmapFactory.decodeStream(input)
} catch (e: IOException) {
e.printStackTrace()
null
}
}
You are getting image url from list, before share you have to Use Picasso to load the url into a Bitmap. after that
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shareItem(data1.getImgUrl())
}
});
public void shareItem(String url) {
Picasso.with(getApplicationContext()).load(url).into(new Target() {
#Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/*");
i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap));
startActivity(Intent.createChooser(i, "Share Your Image"));
}
#Override public void onBitmapFailed(Drawable errorDrawable) { }
#Override public void onPrepareLoad(Drawable placeHolderDrawable) { }
});
}
Convert Bitmap into URi:
public Uri getLocalBitmapUri(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "image" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
Hope it will help you!!
I have An Activity where i retrieve messages that are communicated by the Users. I want to Delete a selected message on Long click.
Here is my code, the Copy to clipboard function is working fine but the delete is giving me a hard time.
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MyMessageViewHolder>{
private ArrayList<Messages> arrayListMessages= new ArrayList<>();
private Context mcontext;
FirebaseAuth mAuth;
private DatabaseReference mUserDatabase;
public ArrayAdapter adapter;
public MessageAdapter(Context context, ArrayList<Messages> arrayListMessages){
this.arrayListMessages = arrayListMessages;
mcontext = context;
}
#Override
public MyMessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_single_layout, parent,false);
return new MyMessageViewHolder(view);
}
#Override
public void onBindViewHolder(final MyMessageViewHolder holder, final int position) {
mAuth = FirebaseAuth.getInstance();
String mCurrentUser = mAuth.getCurrentUser().getUid();
final Messages messages = arrayListMessages.get(position);
String message_type = messages.getType();
String from_user = messages.getFrom();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(from_user);
if(mCurrentUser.equals(messages.getFrom())){
holder.textViewMessage.setBackgroundResource(R.drawable.custom_message_bg_primary);
holder.textViewMessage.setTextIsSelectable(true);
holder.textViewMessage.setGravity(Gravity.RIGHT);
holder.textViewMessage.setTextColor(Color.WHITE);
holder.textViewMessage.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view)
{
CharSequence options[] = new CharSequence[]{"Delete", "Copy Text"};
final AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if (i == 0) {
String selectedItem = messages.getMessage();
arrayListMessages.remove(selectedItem);
Toast.makeText(mcontext, "Message deleted", Toast.LENGTH_SHORT).show();
}
if (i == 1)
{
ClipboardManager cm = (ClipboardManager) mcontext.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(holder.textViewMessage.getText());
Toast.makeText(mcontext, "Copied to clipboard", Toast.LENGTH_SHORT).show();
}
}
});
builder.show();
return true;
}
});
}else{
holder.textViewMessage.setBackgroundResource(R.drawable.custom_message_bd_white);
holder.textViewMessage.setTextIsSelectable(true);
holder.textViewMessage.setGravity(Gravity.LEFT);
holder.textViewMessage.setTextColor(Color.BLACK);
holder.textViewMessage.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
CharSequence options[] = new CharSequence[]{"Delete", "Copy Text"};
final AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if (i == 0) {
String selectedItem = messages.getMessage();
arrayListMessages.remove(selectedItem);
adapter.notifyDataSetChanged();
Toast.makeText(mcontext, "Message deleted", Toast.LENGTH_SHORT).show();
}
if (i == 1)
{
ClipboardManager cm = (ClipboardManager) mcontext.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(holder.textViewMessage.getText());
Toast.makeText(mcontext, "Copied to clipboard", Toast.LENGTH_SHORT).show();
}
}
});
builder.show();
return true;
}
});
}
holder.textViewMessage.setText(messages.getMessage());
if(message_type.equals("text")) {
holder.textViewMessage.setText(messages.getMessage());
holder.messageImage.setVisibility(View.INVISIBLE);
} else {
holder.textViewMessage.setVisibility(View.INVISIBLE);
Picasso.with(holder.UserProfile.getContext()).load(messages.getMessage())
.placeholder(R.drawable.my_profile).into(holder.messageImage);
}
}
private void copyText() {
}
#Override
public int getItemCount() {
return arrayListMessages.size();
}
class MyMessageViewHolder extends RecyclerView.ViewHolder{
TextView textViewMessage;
CircleImageView UserProfile;
ImageView messageImage;
public MyMessageViewHolder(View itemView) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.messageTextView);
UserProfile = itemView.findViewById(R.id.message_profile_layout);
messageImage = (ImageView) itemView.findViewById(R.id.message_image_layout);
}
}
}
Is there any suggestions on how can i enable the delete function on the selected item? Thanks in advance...
Be aware that you shouldn't use setOnLongClickListener in the onBindViewHolder method never. Try moving it to the MyMessageViewHolder constructor.
like this:
public MessageAdapter(Context context, ArrayList<Messages> arrayListMessages){
this.arrayListMessages = arrayListMessages;
mcontext = context;
mAuth = FirebaseAuth.getInstance();
}
class MyMessageViewHolder extends RecyclerView.ViewHolder {
TextView textViewMessage;
CircleImageView UserProfile;
ImageView messageImage;
public MyMessageViewHolder(View itemView) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.messageTextView);
UserProfile = itemView.findViewById(R.id.message_profile_layout);
messageImage = (ImageView) itemView.findViewById(R.id.message_image_layout);
String mCurrentUser = mAuth.getCurrentUser().getUid();
final Messages messages = arrayListMessages.get(getLayoutPosition());
String message_type = messages.getType();
String from_user = messages.getFrom();
mUserDatabase =
FirebaseDatabase.getInstance().getReference().child("Users").child(from_user);
textViewMessage.setOnLongClickListener(new View.OnLongClickListener() {
#Override public boolean onLongClick(View view) {
if (mCurrentUser.equals(messages.getFrom())) {
...
} else {
...
}
}
}
}
}