Load Images from Firestore into RecyclerView : Images not showing - android

I am new to this, I am trying to load images from Firestore into a Grid layout recyclerview, the Toast in Firestore onSuccess method shows "Success" message, but the images aren't showing, I am not sure where I did wrong. I used the Image Url saved in Firestore from Firebase Storage.
Could someone please help? Thank you in advance.
Firestore structure:
The PhotoActivity:
public class PhotoActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private LinearLayout confirmLayout;
private ImageView pickedImageView;
private EditText titleEditText, photoDescriptionEditText;
private ProgressBar progressBar;
private String title, photoDescription;
private Date datePhoto;
private Uri pickedImageUrl;
private FirebaseFirestore db;
private FirebaseAuth mAuth;
private String userId;
private CollectionReference collectionReference;
private StorageReference storageReference;
private FloatingActionButton fab;
private RecyclerView recyclerView;
private List<Photo> photoList;
private PhotoAdapter photoAdapter;
private ProgressBar circularProgressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
confirmLayout = (LinearLayout) findViewById(R.id.confirmPhotoUploadLayout);
pickedImageView = (ImageView) findViewById(R.id.pickedImage);
titleEditText = (EditText) findViewById(R.id.photoTitle);
photoDescriptionEditText = (EditText) findViewById(R.id.photoDescription);
progressBar = (ProgressBar) findViewById(R.id.progressbarPhoto);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewPhoto);
circularProgressbar = (ProgressBar) findViewById(R.id.progress_circularPhoto);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
userId = mAuth.getCurrentUser().getUid();
storageReference = FirebaseStorage.getInstance().getReference(userId);
collectionReference = FirebaseFirestore.getInstance().collection("main").document(userId).collection("photo");
fab = (FloatingActionButton) findViewById(R.id.fabPhoto);
circularProgressbar.setVisibility(View.VISIBLE);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
photoList = new ArrayList<>();
photoAdapter = new PhotoAdapter(this, photoList);
recyclerView.setAdapter(photoAdapter);
showPhotoGrid();
}
private void showPhotoGrid() {
collectionReference
.orderBy("datePhoto", Query.Direction.DESCENDING)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
assert queryDocumentSnapshots != null;
if (!queryDocumentSnapshots.isEmpty()){
//if contains photos
circularProgressbar.setVisibility(View.GONE);
Toast.makeText(PhotoActivity.this, "Success", Toast.LENGTH_SHORT).show();
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot documentSnapshot : list){
Photo photo = documentSnapshot.toObject(Photo.class);
assert photo != null;
photo.setID(documentSnapshot.getId());
photoList.add(photo);
}
photoAdapter.notifyDataSetChanged();
} else {
//show no photos
circularProgressbar.setVisibility(View.GONE);
Toast.makeText(PhotoActivity.this, "No photos added yet", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
circularProgressbar.setVisibility(View.GONE);
Toast.makeText(PhotoActivity.this, "Error in showing images: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
public void addPhoto(View view) {
showImageChooser();
}
private void showImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
pickedImageUrl = data.getData();
Picasso.with(this).load(pickedImageUrl).into(pickedImageView);
confirmLayout.setVisibility(View.VISIBLE);
fab.setVisibility(View.GONE);
photoAdapter.notifyDataSetChanged();
}
}
public void hideConfirmLayout(View view) {
pickedImageView.setImageDrawable(null);
confirmLayout.setVisibility(View.GONE);
fab.setVisibility(View.VISIBLE);
}
public void uploadPhoto(View view) {
title = titleEditText.getText().toString().trim();
photoDescription = photoDescriptionEditText.getText().toString().trim();
if (title.isEmpty()) {
titleEditText.setError("Please give a title");
} else if (photoDescription.isEmpty()) {
photoDescription = "No description for this photo";
}
if (pickedImageUrl != null) {
if (title.isEmpty()) {
titleEditText.setError("Required");
} else {
StorageReference imageReference = storageReference.child(title + "." + getFileExtension(pickedImageUrl));
imageReference.putFile(pickedImageUrl).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
}, 1000);
String thatImageUrl = taskSnapshot.getStorage().getDownloadUrl().toString();
Photo photo = new Photo(userId, title, photoDescription, thatImageUrl, datePhoto);
collectionReference.add(photo).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(PhotoActivity.this, "Saved to gallery", Toast.LENGTH_SHORT).show();
confirmLayout.setVisibility(View.GONE);
pickedImageView.setImageDrawable(null);
titleEditText.setText(null);
photoDescriptionEditText.setText(null);
fab.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PhotoActivity.this, "Firestore error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PhotoActivity.this, "Storage error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.VISIBLE);
double progress = 100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount();
progressBar.setProgress((int) progress);
}
});
}
} else {
Toast.makeText(this, "No photo is selected", Toast.LENGTH_LONG).show();
}
}
private String getFileExtension(Uri uri) {
//get photo type: jpeg, png
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
}
The Photo object class
public class Photo implements Serializable {
private String ID;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
private String photoTitle;
private String photoDescription;
private String photoUrl;
#ServerTimestamp
private Date datePhoto;
public Date getDatePhoto() {
return datePhoto;
}
public void setDatePhoto(Date datePhoto) {
this.datePhoto = datePhoto;
}
public Photo() {
}
public Photo(String ID, String photoTitle, String photoDescription, String photoUrl, Date datePhoto) {
this.ID = ID;
this.photoTitle = photoTitle;
this.photoDescription = photoDescription;
this.photoUrl = photoUrl;
this.datePhoto = datePhoto;
}
public String getPhotoTitle() {
return photoTitle;
}
public void setPhotoTitle(String photoTitle) {
this.photoTitle = photoTitle;
}
public String getPhotoDescription() {
return photoDescription;
}
public void setPhotoDescription(String photoDescription) {
this.photoDescription = photoDescription;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
the PhotoAdapter:
public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {
private Context context;
private List<Photo> photoList;
public PhotoAdapter(Context context, List<Photo> photoList) {
this.context = context;
this.photoList = photoList;
}
#NonNull
#Override
public PhotoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new PhotoViewHolder(LayoutInflater.from(context).inflate(R.layout.single_photo_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull PhotoViewHolder holder, int position) {
Photo photo = photoList.get(position);
if (photo.getPhotoUrl() != null && !photo.getPhotoUrl().isEmpty()){
Picasso.with(context).load(photo.getPhotoUrl()).into(holder.showImage);
}
}
#Override
public int getItemCount() {
return photoList.size();
}
public class PhotoViewHolder extends RecyclerView.ViewHolder {
ImageView showImage;
public PhotoViewHolder(View inflate) {
super(inflate);
showImage = inflate.findViewById(R.id.singlePhotoImageView);
}
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient0"
tools:context=".PhotoActivity">
<TextView
android:id="#+id/titlePhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/quicksand_bold"
android:gravity="center"
android:padding="#dimen/_20sdp"
android:text="PHOTO GALLERY"
android:textColor="#color/white"
android:textSize="#dimen/_14sdp"
android:layout_alignParentTop="true"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewPhoto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/titlePhoto"/>
<LinearLayout
android:id="#+id/confirmPhotoUploadLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/white_rounded"
android:gravity="center"
android:orientation="vertical"
android:paddingTop="#dimen/_20sdp"
android:paddingBottom="#dimen/_10sdp"
android:visibility="gone">
<EditText
android:id="#+id/photoTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_16sdp"
android:layout_marginTop="#dimen/_16sdp"
android:background="#null"
android:hint="Photo title" />
<EditText
android:id="#+id/photoDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_16sdp"
android:layout_marginEnd="#dimen/_16sdp"
android:layout_marginBottom="#dimen/_16sdp"
android:background="#null"
android:hint="Write something about this photo..." />
<ProgressBar
android:id="#+id/progressbarPhoto"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
tools:visibility="visible" />
<ImageView
android:id="#+id/pickedImage"
android:layout_width="match_parent"
android:layout_height="#dimen/_300sdp"
android:layout_marginBottom="#dimen/_14sdp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/_10sdp"
android:gravity="center">
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="#drawable/red_rounded_bg"
android:onClick="hideConfirmLayout"
android:text="cancel"
android:textColor="#color/white" />
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_10sdp"
android:background="#drawable/rounded_button"
android:onClick="uploadPhoto"
android:text="save to gallery"
android:textColor="#color/white" />
</LinearLayout>
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_margin="#dimen/_20sdp"
android:clickable="true"
android:focusable="true"
android:onClick="addPhoto"
android:src="#drawable/ic_add" />
<ProgressBar
android:id="#+id/progress_circularPhoto"
android:layout_width="#dimen/_100sdp"
android:layout_height="#dimen/_100sdp"
android:layout_centerInParent="true"
android:visibility="gone"
tools:visibility="visible"/>
</RelativeLayout>
single photo Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/singlePhotoImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

I found a solution based on this post--> How to use getdownloadurl in recent versions?
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//get the uri and carry out action here
//uri = correct filepath
}
now the images are showing in the recyclerview, yay ! Thanks for the help!

It seems like your urls are wrong.
taskSnapshot.getDownloadUrl returns Task, not the Uri or Url string. You need to add OnSuccessListener callback to get download Uri
Try to save urls by this way:
taskSnapshot.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
String url = downloadUrl.toString()
// save this url to Firestore
}
Check this in Official documentation

Related

Gallery video thumbnails load extremely slow in android recyclerview

I am trying to display all user video thumbnails from local gallery in recyclerview but it loads thumbnails very slow (it takes almost 10 seconds to load all video thumbnails). Code provided below:
VideoGalleryAdapter.java:
public class VideoGalleryAdapter extends RecyclerView.Adapter<VideoGalleryAdapter.viewHolder> {
public OnItemClickListener onItemClickListener;
Context context;
ArrayList<VideoGalleryModel> videoArrayList;
public VideoGalleryAdapter(Context context, ArrayList<VideoGalleryModel> videoArrayList) {
this.context = context;
this.videoArrayList = videoArrayList;
}
#Override
public VideoGalleryAdapter.viewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.video_list, viewGroup, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(final VideoGalleryAdapter.viewHolder holder, final int i) {
holder.videoDuration.setText(videoArrayList.get(i).getVideoDuration());
Glide.with(context).asBitmap().load(videoArrayList.get(i).getVideoThumb()).into(holder.videoThumb);
}
#Override
public int getItemCount() {
return videoArrayList.size();
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(int pos, View v);
}
public class viewHolder extends RecyclerView.ViewHolder {
TextView videoDuration;
ImageView videoThumb;
public viewHolder(#NonNull View itemView) {
super(itemView);
videoDuration = itemView.findViewById(R.id.videoDuration);
videoThumb = itemView.findViewById(R.id.videoThumb);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(getAdapterPosition(), v);
}
});
}
}
}
AddVideoActivity.java:
public class AddVideoActivity extends AppCompatActivity {
public static final int PERMISSION_READ = 0;
public static ArrayList<VideoGalleryModel> videoArrayList;
RecyclerView videoGalleryRV;
ImageButton backBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_video);
backBtn = findViewById(R.id.backBtn);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
if (checkPermission()) {
videoList();
}
}
public void videoList() {
videoGalleryRV = findViewById(R.id.videoGalleryRV);
videoGalleryRV.setLayoutManager(new GridLayoutManager(this, 3));
videoGalleryRV.setItemAnimator(new DefaultItemAnimator());
videoArrayList = new ArrayList<>();
getVideos();
}
//get video files from storage
public void getVideos() {
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
//looping through all rows and adding to list
if (cursor != null && cursor.moveToFirst()) {
do {
String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DURATION));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
Bitmap bmp = ThumbnailUtils.createVideoThumbnail(data, MediaStore.Video.Thumbnails.MINI_KIND);
VideoGalleryModel videoModel = new VideoGalleryModel();
videoModel.setVideoThumb(bmp);
videoModel.setVideoUri(Uri.parse(data));
videoModel.setVideoDuration(timeConversion(Long.parseLong(duration)));
videoArrayList.add(videoModel);
} while (cursor.moveToNext());
}
VideoGalleryAdapter videoGalleryAdapter = new VideoGalleryAdapter(this, videoArrayList);
videoGalleryRV.setAdapter(videoGalleryAdapter);
videoGalleryAdapter.setOnItemClickListener(new VideoGalleryAdapter.OnItemClickListener() {
#Override
public void onItemClick(int pos, View v) {
Toast.makeText(AddVideoActivity.this, "Video Clicked", Toast.LENGTH_SHORT).show();
}
});
}
//time conversion
public String timeConversion(long value) {
String videoTime;
int dur = (int) value;
int hrs = (dur / 3600000);
int mns = (dur / 60000) % 60000;
int scs = dur % 60000 / 1000;
if (hrs > 0) {
videoTime = String.format("%02d:%02d:%02d", hrs, mns, scs);
} else {
videoTime = String.format("%02d:%02d", mns, scs);
}
return videoTime;
}
//runtime storage permission
public boolean checkPermission() {
int READ_EXTERNAL_PERMISSION = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if ((READ_EXTERNAL_PERMISSION != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_READ);
return false;
}
return true;
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_READ) {
if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
Toast.makeText(getApplicationContext(), "Please allow storage permission", Toast.LENGTH_LONG).show();
} else {
videoList();
}
}
}
}
}
activity_add_video.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddVideoActivity">
<RelativeLayout
android:id="#+id/headerContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp">
<ImageButton
android:id="#+id/backBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:padding="10dp"
android:src="#drawable/ic_arrow_back"
android:tint="#android:color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="25dp"
android:layout_toEndOf="#id/backBtn"
android:fontFamily="#font/gilroymedium"
android:text="Choose video"
android:textColor="#android:color/black"
android:textSize="22sp" />
</RelativeLayout>
<View
android:id="#+id/headerDivider"
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_below="#id/headerContainer"
android:background="#android:color/darker_gray" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/videoGalleryRV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/headerDivider"
android:overScrollMode="never" />
</RelativeLayout>
VideoGalleryModel.java:
public class VideoGalleryModel {
Bitmap videoThumb;
String videoDuration;
Uri videoUri;
public Bitmap getVideoThumb() {
return videoThumb;
}
public void setVideoThumb(Bitmap videoThumb) {
this.videoThumb = videoThumb;
}
public String getVideoDuration() {
return videoDuration;
}
public void setVideoDuration(String videoDuration) {
this.videoDuration = videoDuration;
}
public Uri getVideoUri() {
return videoUri;
}
public void setVideoUri(Uri videoUri) {
this.videoUri = videoUri;
}
}
video_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/mainVideoContainer"
android:layout_width="125dp"
android:layout_height="125dp"
android:layout_marginBottom="5dp"
android:background="#color/colorBlackTransparent">
<ImageView
android:id="#+id/videoThumb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_launcher_background"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/videoDuration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:06"
android:padding="5dp"
android:layout_marginEnd="10dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:fontFamily="#font/gilroysemibold"
android:textColor="#android:color/white"/>
</RelativeLayout>
</RelativeLayout>
I just want to know the proper way to show video thumbnail in recyclerview and how to load it faster. If you have additional questions ask me and I will be happy to answer it. Any help would be appreciated
Since creating a video thumbnail is a heavy operation. So this is taking time.
Try commenting these lines
//Bitmap bmp = ThumbnailUtils.createVideoThumbnail(data, MediaStore.Video.Thumbnails.MINI_KIND);
//videoModel.setVideoThumb(bmp);
and load image thumbnail directly using Glide
Glide.with(context).load(new File(videoArrayList.get(i).videoUri.toString())).into(holder.videoThumb);

Fetched Firebase Data is not showing into Listview

I have created a listview where I want to put all the fetched data according to the result of the previous activity values. Like, I have a Spinner and an Edittext then a search button.
The result will be according to the spinner value and edit text value both. But it is not coming. Please help.
Below my Test class with its layout file (here the spinner and edit text present)
and The SearchResults activity, and Useradapter (model class)
Test.java
public class Test extends AppCompatActivity {
Spinner sp;
EditText e1;
Button logout, searchuser;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
logout = (Button)findViewById(R.id.logout);
searchuser = (Button)findViewById(R.id.searchbutt1);
sp = (Spinner)findViewById(R.id.selectblood) ;
e1 = (EditText)findViewById(R.id.searchpin);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
final String[] bloodgroups = new String[]{"A+","A-", "B+", "B-","O+", "O-", "AB+", "AB-"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, bloodgroups);
sp.setAdapter(adapter);
searchuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String bloods = sp.getSelectedItem().toString();
String pin1 = e1.getText().toString();
Intent intent = new Intent(Test.this, Searchresults.class);
intent.putExtra("bloods", bloods);
intent.putExtra("pin1", pin1);
startActivity(intent);
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(Test.this);
alert.setMessage("Are you Sure?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseAuth.getInstance().signOut();
Intent i = new Intent(getApplicationContext(), SignupPage.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialogg = alert.create();
dialogg.show();
}
});
}
}
Layout file (Fragmenthome.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/button">
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="400dp"
android:src="#drawable/bloodimage"
app:layout_constraintBottom_toTopOf="#+id/cardView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.32999998" />
<androidx.cardview.widget.CardView
android:id="#+id/cardView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
app:cardCornerRadius="15dp"
app:cardElevation="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.7">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<Spinner
android:id="#+id/selectblood"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/searchpin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Pincode"
android:inputType="number"/>
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
<Button
android:id="#+id/searchbutt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:background="#drawable/buttonpressed"
android:text="Search"
android:textColor="#ffffff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/cardView2"
app:layout_constraintVertical_bias="0.32" />
<Button
android:id="#+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:background="#drawable/buttonpressed"
android:text="Logout"
android:textColor="#ffffff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/searchbutt1" />
Searchresults Activity
public class Searchresults extends AppCompatActivity {
String pinfin;
String bloodfin;
ArrayList<String> donorList;
ListView listView;
ArrayAdapter<String> arrayAdapter;
public static ArrayList<UserAdapter> donorInfo;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchresults);
Bundle extras = getIntent().getExtras();
bloodfin = extras.getString("bloods");
pinfin = extras.getString("pin1");
donorList = new ArrayList<>();
donorInfo = new ArrayList<>();
listView = (ListView) findViewById(R.id.list_donor);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
donorList);
listView.setAdapter(arrayAdapter);
myRef = FirebaseDatabase.getInstance().getReference("Users");
myRef.child(bloodfin).child(pinfin).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserAdapter donor = dataSnapshot.getValue(UserAdapter.class);
donorInfo.add(donor);
assert donor != null;
String donorInfo = donor.namefin + " \n" + donor.gender + " \n" + donor.phonefin + " \n" + donor.addfin + " \n" + donor.bloodfin ;
donorList.add(donorInfo);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Searchresults.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
UserAdapter Class
public class UserAdapter {
public String email, namefin, addfin, statefin, phonefin, pinfin, bloodfin, gender;
public UserAdapter(String email, String namefin, String addfin, String statefin, String pinfin, String phonefin, String bloodfin, String gender) {
this.email = email;
this.namefin = namefin;
this.addfin = addfin;
this.statefin = statefin;
this.phonefin = phonefin;
this.pinfin = pinfin;
this.bloodfin = bloodfin;
this.gender = gender;
}
public String getEmail() {
return email;
}
public String getNamefin() {
return namefin;
}
public String getAddfin() {
return addfin;
}
public String getStatefin() {
return statefin;
}
public String getPhonefin() {
return phonefin;
}
public String getPinfin() {
return pinfin;
}
public String getBloodfin() {
return bloodfin;
}
public String getGender() {
return gender;
}
public void setEmail(String email) {
this.email = email;
}
public void setNamefin(String namefin) {
this.namefin = namefin;
}
public void setAddfin(String addfin) {
this.addfin = addfin;
}
public void setStatefin(String statefin) {
this.statefin = statefin;
}
public void setPhonefin(String phonefin) {
this.phonefin = phonefin;
}
public void setPinfin(String pinfin) {
this.pinfin = pinfin;
}
public void setBloodfin(String bloodfin) {
this.bloodfin = bloodfin;
}
public void setGender(String gender) {
this.gender = gender;
}
}
myRef = FirebaseDatabase.getInstance().getReference("Users");
myRef.child(bloodfin).child(pinfin).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserAdapter donor = dataSnapshot.getValue(UserAdapter.class);
donorInfo.add(donor);
assert donor != null;
String donorInfo = donor.namefin + " \n" + donor.gender + " \n" + donor.phonefin + " \n" + donor.addfin + " \n" + donor.bloodfin ;
donorList.add(donorInfo);
arrayAdapter = new ArrayAdapter(donorList, getContext());
recyclerview.setAdapter(arrayAdapter);
}

How to pass Recycler View Items into one TextView

I am trying to get a TextView value item within the RecyclerView. My RecyclerView layout file has two TextViews, one is Product Name and the other for the Quantity as you can see here
=== This is my cart_items_layout_item ===
<TextView
android:id="#+id/cart_list_product_name"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:text="Product Name"
android:textColor="#color/colorPrimary"
android:textSize="16sp"
android:layout_marginLeft="5dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/cart_list_product_quantity"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:text="Product Quantity"
android:textColor="#color/colorPrimary"
android:textSize="16sp"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:gravity="end"
android:textStyle="bold"/>
This is my activity_cart xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/cart_list"
android:layout_width="match_parent"
android:layout_height="542dp"
android:layout_above="#+id/next"
android:layout_below="#id/header_color"
android:layout_marginBottom="113dp">
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="#+id/next"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/button"
android:text="CONFIRM ORDER/S"
android:textColor="#color/colorPrimaryDark"
android:layout_margin="10dp" />
<Button
android:id="#+id/sendSMSButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="0dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="69dp"
android:background="#drawable/button"
android:text="Send"
android:textColor="#color/colorPrimaryDark" />
<TextView
android:id="#+id/smsphoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/cart_list"
android:text="0918"/>
This is my RecyclerView Adapter Class
#Override
protected void onStart() {
super.onStart();
final DatabaseReference cartListRef =
FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions<Cart> options =
new FirebaseRecyclerOptions.Builder<Cart>()
.setQuery(cartListRef.child("User View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products"), Cart.class)
.build();
FirebaseRecyclerAdapter<Cart, CartViewHolder> adapter =
new FirebaseRecyclerAdapter<Cart, CartViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull CartViewHolder
holder, int i, #NonNull final Cart model) {
holder.txtProductName.setText(model.getProductName());
holder.txtProductQuantity.setText("Quantity = " +
model.getQuantity());
holder.itemView.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View view)
{
CharSequence options[] = new CharSequence[]
{
"Edit",
"Removed"
};
AlertDialog.Builder builder = new
AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface
dialogInterface, int i)
{
if (i == 0)
{
Intent intent = new
Intent(CartActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid",model.getPid());
startActivity(intent);
}
if(i == 1)
{
cartListRef.child("User View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new
OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull
Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(CartActivity.this, "Item removed successfully",
Toast.LENGTH_SHORT).show();
// Intent intent = new
Intent(CartActivity.this, Home.class);
//
startActivity(intent);
}
}
});
}
if(i == 1)
{
cartListRef.child("Admin View")
.child(Prevalent.CurrentOnlineUsers.getPhone())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new
OnCompleteListener<Void>() {
#Override
public void
onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(CartActivity.this, "Item removed successfully",
Toast.LENGTH_SHORT).show();
// Intent intent =
new Intent(CartActivity.this, Home.class);
//
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_items_layout,
parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
=== this is my Cart class/Model ===
public class Cart
{
private String
date,discount,pid,productDesc,productName,productSupplier,quantity,time;
public Cart()
{
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductSupplier() {
return productSupplier;
}
public void setProductSupplier(String productSupplier) {
this.productSupplier = productSupplier;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Cart(String date, String discount, String pid, String productDesc,
String productName, String productSupplier, String quantity, String time)
{
this.date = date;
this.discount = discount;
this.pid = pid;
this.productDesc = productDesc;
this.productName = productName;
this.productSupplier = productSupplier;
this.quantity = quantity;
this.time = time;
}
=== CartViewHolder ===
public class CartViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
public TextView txtProductName, txtProductQuantity;
private ItemClickListener itemClickListener;
public CartViewHolder(#NonNull View itemView) {
super(itemView);
txtProductName = itemView.findViewById(R.id.cart_list_product_name);
txtProductQuantity =
itemView.findViewById(R.id.cart_list_product_quantity);
}
#Override
public void onClick(View view)
{
itemClickListener.onClick(view, getAdapterPosition(), false);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
}
As you can see in this Image, i use the cart class/model to pass the data to them, then i created another class called CartViewHolder i use this class to set the data into Recycler View. i want to get this values and put it in the message particularly in the SMS. i dont know how to pass it i tried several codes for it.
private void sendSmsBySIntent ()
{
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
//Want to Intent the Items in Here the Product Name and the Quantity
smsSIntent.putExtra("PUT THE ITEMS HERE");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
you can use your List<Cart> cart model list item to send product and quantity to
sms.
private void sendSmsBySIntent (Cart model)
{
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
smsSIntent.putExtra("pName",model.getProductName());
smsSIntent.putExtra("pQty",model.getQuantity());
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
You need the list you sent to the adapter. Send it as a parameter to the sendSmsBySIntent() function and make a for loop where you build a String.
ie.:
private void sendSmsBySIntent (List<Cart> yourList){
StringBuilder extra = new StringBuilder();
for (int i = 0; i < yourList.size(); i++) {
//Build the string the way you want
extra.append(yourList.get(i).getName()).append(" ").append(yourList.get(i).getQuantity);
}
//Want to set specific Phone Number here
Uri uri = Uri.parse("SET DEFAULT VALUE FOR THIS");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
//Want to Intent the Items in Here the Product Name and the Quantity
smsSIntent.putExtra(extra.toString());
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
Edit:
I changed the function inside () , check it.
Now, when you call the function you have to pass the list you are working with. Like so: sendSmsBySIntent(placeHereYourCartList)

How to choose picture from gallery and display it in CardView when Button inside the same CardView of ReclerView is pressed

I'm creating an app where there's cardviews and in every cardview there is a button "choose picture" and a imageView and some data, I want to make the user get a photo from gallery when button "choose file" is pressed and display it and display it in the same cardview of RecyclerView.
I tried this in my MainActivity :
mButtonChooseImage = findViewById(R.id.button_choose_image);
// I got an error in this line
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK &&
data != null
&& data.getData() != null){
mImageUri = data.getData();
Picasso.with(this).load(mImageUri).into(mImageView);
}
}
I tried also in the RecyclerViewAdapter to do a function openFileChooser() but it doesn't work because i can not call onActivityResult in my recyclerViewAdapter.
how we can recover the result of onActivityResult inside an Adapter? I've read some about interfaces, but i couldn't be able trying implementing this.
this is my my activity_main layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"/>
</RelativeLayout>
this my example_item layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardCornerRadius="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="#drawable/ic_launcher_background" />
//this is my button"choose image"
<Button
android:id="#+id/button_choose_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choose file" />
<TextView
android:id="#+id/text_view_creator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="creator name"
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/text_view_ingredients"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ingredients:"
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/text_view_likes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="like: "
android:textColor="#android:color/black"
android:textSize="20sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
th is my MainActivity :
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExamplelist;
private RequestQueue mRequestQueue;
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private ImageView mImageView;
private Uri mImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExamplelist= new ArrayList<>();
mRequestQueue= Volley.newRequestQueue(this);
parseJSON();
mButtonChooseImage = findViewById(R.id.button_choose_image);
//I have an error in this line
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
//this is my openFilechooser function
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
//this is my overrided onActivityresult function
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null
&& data.getData() != null){
mImageUri = data.getData();
Picasso.with(this).load(mImageUri).into(mImageView);
}
}
private void parseJSON(){
String url = "https://srehwald.github.io/eat-api/mensa-garching/2019/24.json";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
mExamplelist = new ArrayList<ExampleItem>();
//loop in days
JSONArray jsonArray = response.getJSONArray("days");
for (int i=0;i<jsonArray.length();i++){
JSONObject day = jsonArray.getJSONObject(i);
String dishesarray = day.getString("dishes");
String date = day.getString("date");
//loop in dishes
JSONArray JsonDishes = new JSONArray(dishesarray);
for (int j=0;j<(JsonDishes.length());j++){
JSONObject json_obj=JsonDishes.getJSONObject(j);
String namedishes=json_obj.getString("name");
Double dishes_price=json_obj.getDouble("price");
String ingredients=json_obj.getString("ingredients");
mExamplelist.add(new ExampleItem("test",namedishes,dishes_price,ingredients));
}
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExamplelist);
mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
}
and this is my ReyclerViewadapter :
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
public ExampleAdapter(Context context, ArrayList<ExampleItem> exampleList){
mContext = context;
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String imageUrl = currentItem.getmImageUrl();
String creatorName = currentItem.getMcreator();
String ingredients = currentItem.getMingredients();
Double likeCount= currentItem.getmLikes();
holder.mTextViewCreator.setText(creatorName);
holder.mTextViewLikes.setText("like: "+likeCount);
holder.mingredients.setText("Ingredients :"+ingredients);
Picasso.with(mContext).load(imageUrl).fit().centerInside().into(holder.mImageView);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder{
public ImageView mImageView;
public TextView mTextViewCreator;
public TextView mTextViewLikes;
public TextView mingredients;
public Button mTakephoto;
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
mImageView=itemView.findViewById(R.id.image_view);
mTextViewCreator=itemView.findViewById(R.id.text_view_creator);
mTextViewLikes=itemView.findViewById(R.id.text_view_likes);
mingredients=itemView.findViewById(R.id.text_view_ingredients);
mTakephoto=itemView.findViewById(R.id.button_choose_image);
}
}
}
I expect that user can choose a picture from gallery when the button "choose picture" and would be dislpay it in the same Cardview where the button is presssed.
Thank you for your time in advance.

Images don't appear in RecyclerView using Firebase-UI, Firestore as database and Picasso

I am using Firebase-UI to load images from Firebase Storage url string from Firestore and shown into RecyclerView using Picasso.
I have 2 variables in the database : name and image url the name appears in the recyclerview but the image not what is the problem that makes image does not appear.
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="20sp" />
<ImageView
android:id="#+id/image_view_upload"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
public class Upload {
private String mName;
private String mImageUrl;
public Upload() {
//empty constructor needed
}
public Upload(String name, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
mName = name;
mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl = imageUrl;
}
}
package com.example.amr.firebasestorage;
public class ImageActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private FirebaseFirestore firebaseFirestor;
private FirestoreRecyclerAdapter<Upload, ImageActivity.ImageViewHolder>
Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
//=========firebase==============
firebaseFirestor = FirebaseFirestore.getInstance();
//===============================
//==========Recycler Items========
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Query query = firebaseFirestor.collection("uploads")
;
FirestoreRecyclerOptions<Upload> options = new FirestoreRecyclerOptions.Builder<Upload>()
.setQuery(query, Upload.class)
.build();
Adapter = new FirestoreRecyclerAdapter<Upload, ImageViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ImageViewHolder holder, int
position, #NonNull Upload model) {
holder.setName(model.getName());
holder.setImageUrl(model.getImageUrl());
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(view);
}
};
recyclerView.setAdapter(Adapter);
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
View mView;
public ImageViewHolder(View itemView) {
super(itemView);
mView=itemView;
imageView = mView.findViewById(R.id.image_view_upload);
}
public void setName(String name) {
textViewName = mView.findViewById(R.id.text_view_name);
textViewName.setText(name);
}
public void setImageUrl(String imageUrl) {
imageView = mView.findViewById(R.id.image_view_upload);
Picasso.get()
.load(imageUrl)
.fit()
.into(imageView);
}
}
#Override
public void onStart() {
super.onStart();
Adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if ( Adapter != null ) {
Adapter.stopListening();
}
}
}
//main activity
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
//_________
private StorageTask storageTask;
private StorageReference storageReference;
private DocumentReference firebaseFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
//________
storageReference = FirebaseStorage.getInstance().getReference("uploads");
firebaseFirestore = FirebaseFirestore.getInstance().collection("uploads").document();
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ( storageTask != null && storageTask.isInProgress() ) {
Toast.makeText(MainActivity.this, "wait", Toast.LENGTH_SHORT).show();
} else {
uploadFiles();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImagesActivity();
}
});
}
private void openImagesActivity() {
Intent inten = new Intent(this, ImageActivity.class);
startActivity(inten);
}
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void uploadFiles() {
if ( mImageUri != null ) {
StorageReference fileRef = storageReference
//
.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));
//.child("Photos").child(mImageUri.getLastPathSegment());
storageTask = fileRef.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(MainActivity.this, "Upload succesful", Toast.LENGTH_SHORT).show();
Uri downloadUri = taskSnapshot.getUploadSessionUri();
assert downloadUri != null;
Upload upload = new Upload(mEditTextFileName
.getText().toString().trim()
, downloadUri.toString());
firebaseFirestore.set(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
public void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null ) {
mImageUri = data.getData();//something back
Picasso.get().load(mImageUri).into(mImageView);
}
}
}
my database
my mobile pic
The problem lies in the fact that you have an incorrect getter for mName field in your model class. When you are using getName() as a getter, Firebase is looking after a field named name and not mName, as it is in your code now. See the difference? The correct model class should look like this:
public class Upload {
private String name;
private String imageUrl;
public Upload() {}
public Upload(String name, String imageUrl) {
this.name = name;
this.imageUrl = imageUrl;
}
public String getName() { return name; }
public String getImageUrl() { return imageUrl; }
}
The setters are not required, are always optional because if there is no setter for a JSON property, the Firebase client will set the value directly onto the field. But if you wish to use setters, the correct setters for your fields are:
public void setName(String name) { this.name = name; }
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
I fixed it
the problem was not in setter and getter but it was here
Uri downloadUri = taskSnapshot.getUploadSessionUri();
it is not the right link to show i replaced it by this
Uri downloadUri = taskSnapshot.getDownloadUrl();
works perfectly

Categories

Resources