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);
Related
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
Here is my Orderofday.java where i am getting data from URL and in String proceeding_file i get pdf link. i have shown the data present on every card but could not achieve to open a pdf link on card button clicked.
public class Orderofday extends AppCompatActivity {
private static final String TAG = Orderofday.class.getSimpleName();
private RecyclerView recyclerView;
private OrderList mAdapter;
ProgressDialog progess;
List<OrdersModel> myList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orderofday);
progess = new ProgressDialog(Orderofday.this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new OrderList(myList, Orderofday.this);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
getResult();
}
public void getResult() {
String url = "http://senate.gov.pk/ne/getdata/order_of_day_json.php";
//detect internet and show the data
if (isNetworkStatusAvialable(getApplicationContext())) {
progess.setMessage("Loading data....");
progess.show();
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject mainList = new JSONObject(response);
JSONArray result = mainList.getJSONArray("data");
if (result.length() > 0) {
for (int i = 0; i < result.length(); i++) {
mainList = result.getJSONObject(i);
OrdersModel model = new OrdersModel();
model.title_en = mainList.getString("title_en");
model.YearID = mainList.getString("YearID");
model.session_title_en = mainList.getString("session_title_en");
model.sitting_date = mainList.getString("sitting_date");
model.proceeding_file = mainList.getString("proceeding_file");
myList.add(model);
}
mAdapter.notifyDataSetChanged();
progess.dismiss();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
progess.dismiss();
}
});
Log.d("params", strReq.getUrl() + " and " + strReq.getBodyContentType() + " abd " + strReq.getBodyContentType());
// Adding String request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, TAG);
} else {
Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show();
}
}
//check internet connection
public static boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if (netInfos != null) {
return netInfos.isConnected();
}
}
return false;
}
}
Here is my OrderList.java class where i am setting the text from OderModel.java
public class OrderList extends RecyclerView.Adapter<OrderList.MyViewHolder> {
List<OrdersModel> list;
Context c;
public OrderList(List<OrdersModel> list, Context c) {
this.list = list;
this.c = c;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.orders_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
OrdersModel movie = list.get(position);
holder.name.setText(movie.gettitle_en());
holder.type.setText(movie.getYearID());
holder.session_title.setText((movie.getsession_title_en()));
holder.sitting_date.setText(movie.getsitting_date());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, type , session_title , sitting_date , proceeding_file;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
type = view.findViewById(R.id.type);
session_title = view.findViewById(R.id.session_title);
sitting_date = view.findViewById(R.id.sitting_date);
}
}
}
And here is my OrderModel.java where i made getters and setter
public class OrdersModel {
String title_en;
String YearID;
String session_title_en;
String sitting_date;
String proceeding_file;
public String gettitle_en() {
return title_en;
}
public void settitle_en(String title_en) {
this.title_en = title_en;
}
public String getYearID() {
return YearID;
}
public void setYearID(String YearID) {
this.YearID = YearID;
}
public String getsession_title_en() {
return session_title_en;
}
public void setsession_title_en(String session_title_en) {
this.session_title_en = session_title_en;
}
public String getsitting_date() {
return sitting_date;
}
public void setsitting_date(String session) {
this.sitting_date = sitting_date;
}
public String getproceeding_file() {
return proceeding_file;
}
public void setproceeding_file(String date) {
this.proceeding_file = proceeding_file;
}
String file;
}
Now i need to open a pdf against every card view clicked i got url of pdf in procedding_file (String) but couldn't get it. Kindly help me out to achieve this and here is xml.
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_margin="#dimen/_5sdp"
android:layout_height="wrap_content"
android:padding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
android:textStyle="bold"
android:textSize="20sp"
android:layout_margin="5dp"
android:text="Title_ID"
android:textColor="#android:color/black" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/type"
android:layout_below="#id/name"
android:layout_margin="5dp"
android:textSize="15sp"
android:text="YearID"
android:textColor="#android:color/black" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/session_title"
android:layout_below="#id/type"
android:layout_margin="5dp"
android:textSize="15sp"
android:text="Session Title"
android:textColor="#android:color/black" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sitting_date"
android:layout_below="#id/session_title"
android:layout_margin="5dp"
android:textSize="15sp"
android:text="Date "
android:textColor="#android:color/black" />
<Button
android:id="#+id/view_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sitting_date"
android:layout_alignParentRight="true"
android:text="Click to View Pdf"
android:textColor="#000000"
android:textSize="#dimen/_10sdp">
</Button>
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Above answer is correct. However a better solution and the rightest one is to create an interface for the clicklistenet and implement it in tour activity
Initialize viewButton in ViewHolder.
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, type , session_title , sitting_date , proceeding_file;
public Button viewButton;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
type = view.findViewById(R.id.type);
session_title = view.findViewById(R.id.session_title);
sitting_date = view.findViewById(R.id.sitting_date);
viewButton = view.findViewById(R.id.view_button);
}
}
Then set onClickListener on viewButton and openPdf
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
OrdersModel movie = list.get(position);
holder.name.setText(movie.gettitle_en());
holder.type.setText(movie.getYearID());
holder.session_title.setText((movie.getsession_title_en()));
holder.sitting_date.setText(movie.getsitting_date());
holder.viewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openPdf(movie.getproceeding_file())
}
});
}
Suggestion: You should move your PdfViewer in another activity and redirect user to that activity when click viewButton.
initialise view_pdf button in MyViewHolder class. like others.
parse proceeding file like others ~ movie.getproceeding_file()
under the onBindViewHolder put below snippet of code:
holder.proceeding_file.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pdf_url = movie.getproceeding_file();
// do not forget to concate preceding url of the pdf
Webview webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(pdf_url);
}
});
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.
i am building a simple recycle view with a custom adapter, i already set the position of all of my elements, but somehow the image of my row the main one is not showing up and i don't know why.
Before i changed the xml it was showing up, so basicly i have my main activity:
public class PlantFeed extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,PlantFeedAdapter.OnItemClickListener {
//initialize fields
String token;
ArrayList<PlantPhotoUser> photos = new ArrayList<>();
VolleyService mVolleyService;
IResult mResultCallback = null;
final String GETREQUEST = "GETCALL";
String connectionTxt;
String URL;
String date;
String lat;
String lon;
String alt;
PlantFeedAdapter plantFeedAdapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plant_feed);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
connectionString connection = ((connectionString) getApplicationContext());
connectionTxt = connection.getGlobalVarValue();
URL = connectionTxt + "/fotos";
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(PlantFeed.this,CameraCapture.class);
startActivity(i);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
recyclerView = (RecyclerView)findViewById(R.id.recycleView2);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
plantFeedAdapter = new PlantFeedAdapter(getApplicationContext(), photos,PlantFeed.this);
recyclerView.setAdapter(plantFeedAdapter);
token = checkForToken();
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley(GETREQUEST,URL,token);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d("HELLL","hi1");
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
PlantPhotoUser plantPhotoUser;
Log.d("HELLLL","hi");
for (int i=0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Log.d("objeto",object.toString());
int userId = object.getInt("userId");
Log.d("objeto",String.valueOf(userId));
String username = object.getJSONObject("user").getString("username");
Log.d("objeto",String.valueOf(username));
int plantId = object.getInt("plantId");
Log.d("objeto",String.valueOf(plantId));
String specie = object.getJSONObject("plant").getString("specie");
Log.d("objeto",String.valueOf(specie));
String path = object.getString("image");
Log.d("objeto",String.valueOf(path));
int fotoId = object.getInt("id");
if(object.getString("date") != null){
date = object.getString("date");
}
if(object.getString("lat") != null){
lat = object.getString("lat");
}
if(object.getString("lon") != null){
lon = object.getString("lon");
}
if(object.getString("altitude") != null){
alt = object.getString("altitude");
}
plantPhotoUser = new PlantPhotoUser(fotoId,plantId,userId,path,specie,date,lat,lon,alt,username);
photos.add(plantPhotoUser);
} catch (JSONException e) {
e.printStackTrace();
}
}
plantFeedAdapter.notifyDataSetChanged();
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d("FAIL",error.toString());
}
};
}
public String checkForToken() {
SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
String tokenKey = getResources().getString(R.string.token);
String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
return token;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.plant_feed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.Perfil) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Intent i = new Intent(PlantFeed.this,CameraCapture.class);
startActivity(i);
} else if (id == R.id.nav_gallery) {
Intent i = new Intent(PlantFeed.this,PlantFeed.class);
startActivity(i);
} else if (id == R.id.nav_slideshow) {
Intent i = new Intent(PlantFeed.this,FamilyLibrary.class);
startActivity(i);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onRowClick(int position, String name, int id, View view) {
}
#Override
public void onTitleClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,PhotosForPlant.class);
i.putExtra("plantId",String.valueOf(id));
startActivity(i);
}
#Override
public void onImageClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,PhotosForPlant.class);
i.putExtra("plantId",String.valueOf(id));
startActivity(i);
}
#Override
public void onReportClicked(int position, int id, String name, View clickedview) {
Log.d("HELLLO","HELLOO");
showDialogReport(id,name);
}
#Override
public void onUserIconClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,UserProfile.class);
i.putExtra("userId",id);
startActivity(i);
}
#Override
public void onUsernameClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,UserProfile.class);
i.putExtra("userId",id);
startActivity(i);
}
#Override
public void onAvaliationClicked(int position, int id, String name, View clickedview) {
}
private void showDialogReport(int id, String name) {
Log.d("HELLLO","HELLOO");
AlertDialog.Builder builder = new AlertDialog.Builder(PlantFeed.this);
builder.setTitle(name);
builder.setMessage("Tem a certeza que pretende reportar a fotografia?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//TODO reportar base de dados
}
});
builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
and then i have my customer adapter like this:
public class PlantFeedAdapter extends RecyclerView.Adapter<PlantFeedAdapter.ViewHolder> {
private OnItemClickListener listener;
public interface OnItemClickListener {
void onRowClick(int position, String name, int id, View view);
void onTitleClicked(int position, int id, View clickedview);
void onImageClicked(int position,int id, View clickedview);
void onReportClicked(int position, int id,String name, View clickedview);
void onUserIconClicked(int position, int id, View clickedview);
void onUsernameClicked(int position, int id, View clickedview);
void onAvaliationClicked(int position, int id,String name, View clickedview);
}
private ArrayList<PlantPhotoUser> photos;
private Context context;
public PlantFeedAdapter(Context context, ArrayList<PlantPhotoUser> photos, OnItemClickListener listener) {
this.photos = photos;
this.context = context;
this.listener = listener;
}
#Override
public PlantFeedAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.plant_feed_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final PlantFeedAdapter.ViewHolder viewHolder, final int i) {
viewHolder.name.setText(photos.get(i).getSpecie());
viewHolder.username.setText(photos.get(i).getUsernName());
viewHolder.data.setText(photos.get(i).getDate().split("T")[0]);
Log.d("data123",(photos.get(i).getDate().toString()));
String urlFoto = "http://fe1b7efd.ngrok.io/" + photos.get(i).getPath();
if(urlFoto.toLowerCase().contains("public/")){
urlFoto = urlFoto.replace("public/","");
}
viewHolder.userIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onUserIconClicked(viewHolder.getAdapterPosition(), photos.get(i).getUserId(), view);
}
}
});
viewHolder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onUsernameClicked(viewHolder.getAdapterPosition(),photos.get(i).getUserId(), view);
}
}
});
viewHolder.plantImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onImageClicked(viewHolder.getAdapterPosition(), photos.get(i).getIdPlant(), view);
}
}
});
viewHolder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onTitleClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),v);
}
}
});
viewHolder.reportImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onReportClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
}
}
});
/*viewHolder.avaliationFoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onAvaliationClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
}
}
});*/
Picasso.with(context)
.load(urlFoto)
.resize(300, 300)
.into(viewHolder.plantImg);
}
#Override
public int getItemCount() {
return photos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView name;
private ImageView userIcon;
private TextView avaliationFoto;
private ImageView plantImg;
private ImageView foto;
private TextView username;
private ImageView reportImage;
private TextView data;
public ViewHolder(View view) {
super(view);
data = (TextView)view.findViewById(R.id.data);
name = (TextView) view.findViewById(R.id.plantName);
userIcon = (ImageView)view.findViewById(R.id.userIcon);
plantImg = (ImageView)view.findViewById(R.id.plantPhoto);;
username = (TextView)view.findViewById(R.id.password);
reportImage = (ImageView)view.findViewById(R.id.cameraForbiden);
}
}
}
finally my row xml, wher i think there is the problem
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#cfcfcf">
<LinearLayout
android:layout_margin="10dp"
android:background="#ffffff"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.android.volley.toolbox.NetworkImageView
android:layout_weight="1"
android:layout_width="120dp"
android:layout_height="100dp"
android:padding="0dp"
app:srcCompat="#mipmap/ic_launcher"
android:id="#+id/plantPhoto"
android:background="#c7c7c7"
/>
<LinearLayout
android:layout_weight="20"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/plantName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="15dp"
android:text="TextView"
android:textColor="#000"
android:textSize="20dp" />
<ImageView
android:id="#+id/starIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:gravity="right"
android:src="#drawable/ic_star" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:padding="15dp">
<com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
android:id="#+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toStartOf="#+id/cameraForbiden"
android:text="TextView"
android:textColor="#color/base" />
<ImageView
android:id="#+id/cameraForbiden"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:src="#drawable/ic_no_photos" />
<ImageView
android:id="#+id/userIcon"
android:layout_width="15dp"
android:layout_height="15dp"
android:gravity="left"
android:layout_alignParentBottom="true"
android:src="#drawable/ic_user" />
<com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/userIcon"
android:text="Filipe"
android:textColor="#color/base" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
the problem is on this element:
<com.android.volley.toolbox.NetworkImageView
android:layout_weight="1"
android:layout_width="120dp"
android:layout_height="100dp"
android:padding="0dp"
app:srcCompat="#mipmap/ic_launcher"
android:id="#+id/plantPhoto"
android:background="#c7c7c7"
/>
Add centerCrop() with Picasso
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
Change this lines in Your Adapter and in ViewHolder because type cast is wrong. :
private ImageView plantImg;
plantImg = (ImageView)view.findViewById(R.id.plantPhoto);;
to
private NetworkImageView plantImg;
plantImg= (NetworkImageView) findViewById(R.id
.plantPhoto); then set image .
Edit
`private ImageLoader mImageLoader;
mImageLoader = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
.getImageLoader();
mImageLoader.get(url, ImageLoader.getImageListener(mNetworkImageView,
R.mipmap.truiton_short, android.R.drawable
.ic_dialog_alert));
mNetworkImageView.setImageUrl(url, mImageLoader);`
use this link http://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/ for further guide.
OK, this is my last try of to know why the mp.setVolume() does not work, after that I'll throw in the towel. I already asked this to half world and seems that no one know. Ok, this time I'll post the whole code, if anyone know why the mp.setVolume() method does not work anyway, PLEASE, let me know. I really thank.
Note - the sounds are stored in the raw folder
Code:
class to store constants
public abstract class Constantes {
public static String[] labels = {
"Som 1",
"Som 2",
"Som 3",
"Som 4",
"Som 5"
};
public static int[] rawIds = {
R.raw.alarm,
R.raw.battery_caution,
R.raw.beep_beep,
R.raw.call_connect,
R.raw.camera_focus
};
}
mediaPlayer class
public class LoopMediaPlayer {
private Context ctx = null;
private int rawId = 0;
private MediaPlayer currentPlayer = null;
private MediaPlayer nextPlayer = null;
public static LoopMediaPlayer create(Context ctx, int rawId) {
return new LoopMediaPlayer(ctx, rawId);
}
private LoopMediaPlayer(Context ctx, int rawId) {
this.ctx = ctx;
this.rawId = rawId;
currentPlayer = MediaPlayer.create(this.ctx, this.rawId);
currentPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
currentPlayer.start();
}
});
createNextMediaPlayer();
}
private void createNextMediaPlayer() {
nextPlayer = MediaPlayer.create(ctx, rawId);
currentPlayer.setNextMediaPlayer(nextPlayer);
currentPlayer.setOnCompletionListener(onCompletionListener);
}
private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
currentPlayer = nextPlayer;
createNextMediaPlayer();
}
};
public void stopPlayer() {
if (currentPlayer != null && currentPlayer.isPlaying()) {
currentPlayer.stop();
currentPlayer.release();
}
if (nextPlayer != null && nextPlayer.isPlaying()) {
nextPlayer.stop();
nextPlayer.release();
}
}
public void setPlayerVolume(float volume) {
//I already tried this
// float finalV = (float) (1 - (Math.log(MainActivity.mxVol - volume) / Math.log(MainActivity.mxVol)));
// currentPlayer.setVolume(1- finalV, 1- finalV);
// nextPlayer.setVolume(1- finalV, 1- finalV);
//
//and this too
//// float finalV = ((volume * 100) / MainActivity.mxVol) / 100;
currentPlayer.setVolume(volume, volume);
nextPlayer.setVolume(volume, volume);
}
}
main activity
#SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {
private TextView tvCurVol;
private SeekBar skVol;
private int iniVol = -1;
private SonsAdapter adapter;
private SparseArray<LoopMediaPlayer> players = new SparseArray<>();
private int pos = -1;
public static int mxVol = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inits();
}
private AdapterView.OnItemClickListener onItemClick() {
return new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (players.get(i) == null) {
LoopMediaPlayer player = LoopMediaPlayer.create(MainActivity.this, Constantes.rawIds[i]);
players.put(i, player);
} else {
LoopMediaPlayer player = players.get(i);
player.stopPlayer();
players.remove(i);
}
}
};
}
private AdapterView.OnItemLongClickListener onItemLongClick() {
return new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
if (players.get(i) != null) {
SonsModel model = (SonsModel) adapter.getItem(i);
pos = i;
int curVol = model.getVolume();
skVol.setProgress(curVol);
skVol.setEnabled(true);
skVol.setOnSeekBarChangeListener(onProgressChange());
return true;
}
return false;
}
};
}
private SeekBar.OnSeekBarChangeListener onProgressChange() {
return new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
LoopMediaPlayer player = players.get(pos);
SonsModel model = (SonsModel) adapter.getItem(pos);
/* I tried change volume this way and so how on method
setPlayerVolume() of LoopMediaPlayer class */
float volume = ((i * 100) / mxVol) / 100;
player.setPlayerVolume(volume);
model.setVolume(i);
tvCurVol.setText("Volume Atual - " + i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekBar.setEnabled(false);
}
};
}
private void inits() {
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
ListView lvSons = (ListView) findViewById(R.id.lvSons);
tvCurVol = (TextView) findViewById(R.id.tvCurVol);
skVol = (SeekBar) findViewById(R.id.skVol);
mxVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
TextView tvMxVol = (TextView) findViewById(R.id.tvMxVol);
tvMxVol.setText("Volume Maximo - " + mxVol);
skVol.setMax(mxVol);
skVol.setEnabled(false);
iniVol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
tvCurVol.setText("Volume Atual - " + iniVol);
adapter = new SonsAdapter(this, createModelList());
lvSons.setAdapter(adapter);
lvSons.setOnItemClickListener(onItemClick());
lvSons.setOnItemLongClickListener(onItemLongClick());
}
private List<SonsModel> createModelList() {
List<SonsModel> modelList = new ArrayList<>();
for (int i = 0; i < Constantes.labels.length; i++) {
modelList.add(new SonsModel(Constantes.labels[i], Constantes.rawIds[i], iniVol));
}
return modelList;
}
}
adapter
public class SonsAdapter extends BaseAdapter {
private Context ctx;
private List<SonsModel> sonsList;
public SonsAdapter(Context ctx, List<SonsModel> sonsList) {
this.ctx = ctx;
this.sonsList = sonsList;
}
#Override
public int getCount() {
return sonsList.size();
}
#Override
public Object getItem(int i) {
return sonsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(ctx).inflate(R.layout.adapter_row, viewGroup, false);
holder.tvRow = (TextView) view.findViewById(R.id.tvRow);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
SonsModel model = sonsList.get(i);
holder.tvRow.setText(model.getLabel());
return view;
}
private class ViewHolder {
TextView tvRow;
}
}
finally last class: som model
public class SonsModel {
private String label;
private int rawId;
private int volume;
public SonsModel(String label, int rawId, int volume) {
this.label = label;
this.rawId = rawId;
this.volume = volume;
}
public String getLabel() {
return label;
}
public int getRawId() {
return rawId;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
}
Layouts
main activity layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.seekbarmediavolume.MainActivity"
tools:ignore="HardcodedText">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16sp"
android:gravity="center_horizontal"
android:text="Sons"
android:textSize="22sp" />
<TextView
android:id="#+id/tvMxVol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16sp"
android:gravity="center_horizontal"
android:textSize="22sp" />
<ListView
android:id="#+id/lvSons"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<TextView
android:id="#+id/tvCurVol"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16sp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:textSize="22sp" />
<SeekBar
android:id="#+id/skVol"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
adapter row layout
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tvRow"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:textColor="#f00"
android:textSize="16sp" />