Unable to download Image through url into my phone in android 10 - java

I m trying to download image into phone storage through its url using glide its working fine in android 9 or below buts its not working in case of android 10,
Here is my adapter code where i added download funtion, can some One help with the code
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
ArrayList<Model> modelArrayList;
public Adapter(Context context, ArrayList<Model> modelArrayList) {
this.context = context;
this.modelArrayList = modelArrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String url = modelArrayList.get(position).getUrl();
holder.setImage(url);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sharing = new Intent (Intent.ACTION_SEND);
sharing.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharing.setType("text/plain");
String subject = "Hey Man just look at this coll meme click the link " +url;
sharing.putExtra(Intent.EXTRA_TEXT,subject);
context.startActivity(Intent.createChooser(sharing,"Shring using"));
}
});
holder.buttonDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
downloadImage(url);
}
});
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
Button button,buttonDownload;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
button = itemView.findViewById(R.id.button);
buttonDownload = itemView.findViewById(R.id.btn_download);
}
void setImage(String link){
Glide.with(context).load(link).into(imageView);
}
}
void downloadImage(String imageURL){
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "memebook" + "/";
final File dir = new File(dirPath);
final String fileName = imageURL.substring(imageURL.lastIndexOf('/') + 1);
Glide.with(context)
.load(imageURL)
.into(new CustomTarget<Drawable>() {
#Override
public void onResourceReady(#NonNull Drawable resource, #Nullable Transition<? super Drawable> transition) {
Bitmap bitmap = ((BitmapDrawable)resource).getBitmap();
Toast.makeText(context, "Saving Image...", Toast.LENGTH_SHORT).show();
saveImage(bitmap, dir, fileName);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
#Override
public void onLoadFailed(#Nullable Drawable errorDrawable) {
super.onLoadFailed(errorDrawable);
Toast.makeText(context, "Failed to Download Image! Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
private void saveImage(Bitmap image, File storageDir, String imageFileName) {
boolean successDirCreated = false;
if (!storageDir.exists()) {
successDirCreated = storageDir.mkdir();
}
successDirCreated = true;
if (successDirCreated) {
File imageFile = new File(storageDir, imageFileName);
String savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
Toast.makeText(context, "Image Saved!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, "Error while saving image!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else{
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
}
}

Related

How can we save all images and videos on button click in recyclerview?

I am creating activity like WhatsApp to edit photos.Add text, sticker and paint on image.
when click on sendbtn only current image save not all the images.
My question is how to save all images on sendBtn click.Please help me.
Screenshot link
https://i.stack.imgur.com/Jr3ZY.jpg
Thanks in advance.
Here is my adapter.
private final List<FilePickerModel> list;
Context context;
private final String from;
private final String name;
private int pos;
private RecyclerView mediaRv;
int IMAGE_ITEM = 1;
int VIDEO_ITEM = 2;
private VideoView videoView;
private videoHolder holder;
private FilePickerActivity activity;
public MediaAdapter(List<FilePickerModel> list, Context context,RecyclerView mediaRv,String from,String name) {
this.list = list;
this.context = context;
this.mediaRv = mediaRv;
this.from = from;
this.name = name;
}
public void stopPlayer(){
if (holder.mVideoView != null){
holder.mVideoView.stopPlayback();
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == IMAGE_ITEM) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.media_item, parent, false);
return new imageHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_media_item, parent, false);
return new videoHolder(view);
}
}
#Override
public int getItemViewType(int position) {
if (list.get(position).getName().contains(".mp4")) {
return VIDEO_ITEM;
} else {
return IMAGE_ITEM;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
FilePickerModel model = list.get(position);
activity = new FilePickerActivity();
if (holder.getClass() == imageHolder.class) {
//IMAGE_ITEM
EmojiPopup popup = EmojiPopup.Builder.fromRootView(((imageHolder)holder).rootView).build(((imageHolder)holder).captionEDt);
((imageHolder)holder).emojiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popup.toggle();
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_emoji_emotions_24);
}
});
if (popup.isShowing()){
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_emoji_emotions_24);
}else {
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_keyboard_24);
}
((imageHolder)holder).receiverName.setText(name);
SelectedAdapter adapter = new SelectedAdapter(list,mediaRv);
((imageHolder)holder).recyclerView.setAdapter(adapter);
((imageHolder)holder).deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int newPosition = holder.getAdapterPosition();
list.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, list.size());
adapter.notifyDataSetChanged();
}
});
try {
Uri imageUri = Uri.fromFile(model.getFile());
Bitmap bitmap = MediaStore.Images.Media.getBitmap(holder.itemView.getContext().getContentResolver(), imageUri);
((imageHolder) holder).photoEditorView.getSource().setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
((imageHolder) holder).captionEDt.setText(model.getCaption());
((imageHolder) holder).captionEDt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
model.setCaption(editable.toString());
}
});
((imageHolder) holder).mPhotoEditor = new PhotoEditor.Builder(context, ((imageHolder) holder).photoEditorView)
.setPinchTextScalable(true)
.build();
((imageHolder) holder).colorPickerView.setOnColorChangeListener(
new VerticalSlideColorPicker.OnColorChangeListener() {
#Override
public void onColorChange(int selectedColor) {
((imageHolder) holder).mSelectedColor = selectedColor;
if (((imageHolder) holder).colorPickerView.getVisibility() == View.VISIBLE) {
((imageHolder) holder).imagePhotoEditPaint.setBackgroundColor(selectedColor);
((imageHolder) holder).mPhotoEditor.setBrushColor(selectedColor);
}
}
});
((imageHolder) holder).imagePhotoEditBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((AppCompatActivity) context).finish();
}
});
((imageHolder) holder).imagePhotoEditUndo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((imageHolder) holder).mPhotoEditor.undo();
}
});
((imageHolder) holder).imagePhotoEditSticker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((imageHolder) holder).ShowBrush(false);
((imageHolder) holder).mStickerBSFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), ((imageHolder) holder).mStickerBSFragment.getTag());
}
});
((imageHolder) holder).imagePhotoEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextEditorDialogFragment textEditorDialogFragment = TextEditorDialogFragment.show((AppCompatActivity) context);
textEditorDialogFragment.setOnTextEditorListener(new TextEditorDialogFragment.TextEditor() {
#Override
public void onDone(String inputText, int colorCode) {
((imageHolder) holder).mPhotoEditor.addText(inputText, colorCode);
}
});
}
});
((imageHolder) holder).imagePhotoEditPaint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (((imageHolder) holder).colorPickerView.getVisibility() == View.VISIBLE) {
((imageHolder) holder).ShowBrush(false);
} else {
((imageHolder) holder).ShowBrush(true);
}
}
});
((imageHolder) holder).sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
if (from.equals("community")) {
model.setPath(((imageHolder) holder).saveImage("/Edonomy/Public/Edonomy Images"));
} else {
model.setPath(((imageHolder) holder).saveImage("/Edonomy/Chat/Edonomy Images"));
}
intent.putExtra("media", (Serializable) list);
((MediaEditActivity) context).setResult(RESULT_OK, intent);
((MediaEditActivity) context).finish();
((MediaEditActivity)context).overridePendingTransition(android.R.anim.fade_in,
android.R.anim.fade_out);
}
});
} else {
//VIDEO_ITEM
}
}
#Override
public int getItemCount() {
return list.size();
}
static class imageHolder extends RecyclerView.ViewHolder implements StickerBSFragment.StickerListener {
private final ImageView imagePhotoEditBack;
private final ImageView imagePhotoEditUndo;
private final ImageView imagePhotoEditSticker;
private final ImageView imagePhotoEditText;
private final ImageView imagePhotoEditPaint;
private final StickerBSFragment mStickerBSFragment;
private final VerticalSlideColorPicker colorPickerView;
private final PhotoEditorView photoEditorView;
private PhotoEditor mPhotoEditor;
private int mSelectedColor;
private final EmojiEditText captionEDt;
private final ImageView sendBtn;
private final ImageView deleteBtn;
private final RecyclerView recyclerView;
private final EmojiTextView receiverName;
private final ImageView emojiBtn;
private final LinearLayout rootView;
private boolean isShown = true;
public imageHolder(#NonNull View itemView) {
super(itemView);
imagePhotoEditBack = itemView.findViewById(R.id.img_photo_edit_back);
imagePhotoEditUndo = itemView.findViewById(R.id.img_photo_edit_undo);
ImageView imagePhotoEditRedo = itemView.findViewById(R.id.img_photo_edit_redo);
ImageView imagePhotoEditCrop = itemView.findViewById(R.id.img_photo_edit_crop);
imagePhotoEditSticker = itemView.findViewById(R.id.img_photo_edit_stickers);
imagePhotoEditText = itemView.findViewById(R.id.img_photo_edit_text);
imagePhotoEditPaint = itemView.findViewById(R.id.img_photo_edit_paint);
colorPickerView = itemView.findViewById(R.id.color_picker_view);
sendBtn = itemView.findViewById(R.id.media_send_Btn);
photoEditorView = itemView.findViewById(R.id.media_photo_editor_view);
captionEDt = itemView.findViewById(R.id.media_captionBox);
recyclerView = itemView.findViewById(R.id.select_list_rv);
deleteBtn = itemView.findViewById(R.id.img_photo_delete);
receiverName = itemView.findViewById(R.id.receiver_name_tv);
emojiBtn = itemView.findViewById(R.id.emoji_media_btn);
rootView = itemView.findViewById(R.id.image_emoji_layout);
LinearLayoutManager layoutManager1 = new LinearLayoutManager(itemView.getContext());
layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager1);
mStickerBSFragment = new StickerBSFragment();
mStickerBSFragment.setStickerListener(this);
}
private void ShowBrush(boolean enableBrush) {
if (enableBrush) {
mPhotoEditor.setBrushColor(mSelectedColor);
imagePhotoEditPaint.setBackgroundColor(mSelectedColor);
mPhotoEditor.setBrushDrawingMode(true);
colorPickerView.setVisibility(View.VISIBLE);
} else {
imagePhotoEditPaint.setBackgroundColor(itemView.getContext().getResources().getColor(android.R.color.transparent));
mPhotoEditor.setBrushDrawingMode(false);
colorPickerView.setVisibility(View.INVISIBLE);
}
}
#Override
public void onStickerClick(Bitmap bitmap) {
mPhotoEditor.addImage(bitmap);
}
#SuppressLint("MissingPermission")
public String saveImage(String path) {
File folder = new File(Environment.getExternalStorageDirectory().toString() + path);
if (!folder.isDirectory()) {
folder.mkdirs();
}
File file = new File(folder
+ File.separator + ""
+ System.currentTimeMillis() + ".png");
try {
file.createNewFile();
SaveSettings saveSettings = new SaveSettings.Builder()
.setClearViewsEnabled(true)
.setTransparencyEnabled(true)
.build();
mPhotoEditor.saveAsFile(String.valueOf(file), saveSettings, new PhotoEditor.OnSaveListener() {
#Override
public void onSuccess(#NonNull String imagePath) {
// Toast.makeText(itemView.getContext(), "Image Saved Successfully", Toast.LENGTH_SHORT).show();
/**
* send result back to the ImagePickActivity
*/
}
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(itemView.getContext(), "Failed to save Image", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(itemView.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return String.valueOf(file);
}
}

Twice data in RecyclerView

How can i fix twice data error.
After scrolling inside the RecyclerView, I am having a issue which is twice data.
Here is my Activity:
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<Contacts>> call = apiInterface.chat(getUserLogin,friendId);
call.enqueue(new Callback<List<Contacts>>() {
#Override
public void onResponse(Call<List<Contacts>> call, Response<List<Contacts>> response) {
contacts = response.body();
CustomAdapterOfChat adapter = new CustomAdapterOfChat(contacts, ChatActivity.this);
recyclerView.setAdapter(adapter);
size = String.valueOf(contacts.size());
}
#Override
public void onFailure(Call<List<Contacts>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Error\n"+t.toString(), Toast.LENGTH_LONG).show();
}
});
My customAdapter ViewHolder
public class CustomAdapterOfChat extends RecyclerView.Adapter<CustomAdapterOfChat.MyViewHolder> {
private List<Contacts> contacts;
private Context context;
String getUserLogin;
public CustomAdapterOfChat(List<Contacts> contacts, Context context) {
this.contacts = contacts;
this.context = context;
}
#Override
public CustomAdapterOfChat.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_of_chat, parent, false);
return new CustomAdapterOfChat.MyViewHolder(view);
}
#Override
public void onBindViewHolder(CustomAdapterOfChat.MyViewHolder holder, final int position) {
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =context.getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");
Log.d("USER_ID",getUserLogin);
Log.d("FRIEND_ID",contacts.get(position).getFriendId());
holder.time.setText(contacts.get(position).getDateAndTime());
if(getUserLogin.equals(contacts.get(position).getFriendId())) {
holder.msg_of_me.setVisibility(View.INVISIBLE);
holder.msg_of_them.setText(contacts.get(position).getMessage());
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra("id",contacts.get(position).getFriendId());
context.startActivity(intent);
}
});
Glide.with(context)
.load(Constant.BASE_URL+"y_chat/sign_up/"+contacts.get(position).getFriendName()+"/profile.png")
.error(R.drawable.error)
.into(holder.img);
}else{
holder.img.setVisibility(View.INVISIBLE);
holder.msg_of_them.setVisibility(View.INVISIBLE);
holder.msg_of_me.setText(contacts.get(position).getMessage());
}
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView msg_of_me,msg_of_them,time;
ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
msg_of_me = itemView.findViewById(R.id.message_text1);
msg_of_them = itemView.findViewById(R.id.message_text);
img = itemView.findViewById(R.id.img_of_them);
time = itemView.findViewById(R.id.message_time);
}
}
}
You are getting data from SharedPreferences which is time consuming task however you can edit your code this way and check the output.
public class CustomAdapterOfChat extends RecyclerView.Adapter {
private List<Contacts> contacts;
private Context context;
String getUserLogin;
public CustomAdapterOfChat(List<Contacts> contacts, Context context) {
this.contacts = contacts;
this.context = context;
//get user Id here.
SharedPreferences sharedPreferences;
sharedPreferences =context.getSharedPreferences(Constant.SHARED_PREF_NAME,
Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");
}
#Override
public CustomAdapterOfChat.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_of_chat, parent, false);
return new CustomAdapterOfChat.MyViewHolder(view);
}
#Override
public void onBindViewHolder(CustomAdapterOfChat.MyViewHolder holder, final int position) {
Log.d("USER_ID",getUserLogin);
Log.d("FRIEND_ID",contacts.get(position).getFriendId());
holder.time.setText(contacts.get(position).getDateAndTime());
if(getUserLogin.equals(contacts.get(position).getFriendId())) {
holder.msg_of_me.setVisibility(View.INVISIBLE);
holder.msg_of_them.setText(contacts.get(position).getMessage());
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra("id",contacts.get(position).getFriendId());
context.startActivity(intent);
}
});
Glide.with(context)
.load(Constant.BASE_URL+"y_chat/sign_up/"+contacts.get(position).getFriendName()+"/profile.png")
.error(R.drawable.error)
.into(holder.img);
}else{
holder.img.setVisibility(View.INVISIBLE);
holder.msg_of_them.setVisibility(View.INVISIBLE);
holder.msg_of_me.setText(contacts.get(position).getMessage());
}
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView msg_of_me,msg_of_them,time;
ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
msg_of_me = itemView.findViewById(R.id.message_text1);
msg_of_them = itemView.findViewById(R.id.message_text);
img = itemView.findViewById(R.id.img_of_them);
time = itemView.findViewById(R.id.message_time);
}
}

Exoplayer not stopping after app closes in PagerAdapter

I have problem with Exoplayer to stopping after the app is closed down, or the fragment is changed from the BottomNavigationView, I get the data from my API that is cast to a Recyclerview/Adapter that handle the data, then the data with the images and video is gettting showed with a PagerAdapter.
I also tried in the fragment to set a onDestroy, but not working.
FeedAdapter.java
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {
private final List<FeedData> feedList;
private Activity context;
private View.OnClickListener onClickListener;
private SimpleExoPlayer videoPlayer;
REST apiService =
RestClient.getClient().create(REST.class);
public FeedAdapter(Activity context, List<FeedData> feedList) {
this.context = context;
this.feedList = feedList;
this.onClickListener = onClickListener;
}
public List<FeedData> getFeedData(){
return feedList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_feed_photo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.mBinding.setFeed(feedList.get(position));
Boolean isLiked = holder.mBinding.getFeed().getIsLiked();
Boolean isSaved = holder.mBinding.getFeed().getIsSaved();
String username = holder.mBinding.getFeed().getUsername();
if (holder.mBinding.getFeed().getAvatar().length() > 0) {
Glide.with(context).load(holder.mBinding.getFeed().getAvatar())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(holder.mBinding.userAvatar);
}
holder.mBinding.username.setText(username);
holder.mBinding.description.setHashtagModeColor(ContextCompat.getColor(context, R.color.fitnessm8_green));
holder.mBinding.description.addAutoLinkMode(AutoLinkMode.MODE_HASHTAG, AutoLinkMode.MODE_MENTION);
holder.mBinding.description.setAutoLinkText(holder.mBinding.getFeed().getDescription());
holder.mBinding.likecount.setText(holder.mBinding.getFeed().getLikes().toString());
holder.mBinding.likecounttext.setText(context.getResources().getString(R.string.likes));
holder.mBinding.commentcount.setText(holder.mBinding.getFeed().getComments().size() + " " + context.getResources().getString(R.string.comments));
holder.mBinding.viewMoreComment.setText(context.getResources().getString(R.string.view) + " " + holder.mBinding.getFeed().getComments().size() + " " + context.getResources().getString(R.string.comments));
holder.mBinding.viewMoreComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
if (isLiked) {
holder.mBinding.like.setLiked(true);
} else {
holder.mBinding.like.setLiked(false);
}
if (isSaved) {
holder.mBinding.fav.setLiked(true);
} else {
holder.mBinding.fav.setLiked(false);
}
if (holder.mBinding.getFeed().getType().equals("image")) {
if (holder.mBinding.getFeed().getMediaSet().size() > 1) {
holder.mBinding.image.setVisibility(View.GONE);
MultiMediaAdapter pagerAdapter = new MultiMediaAdapter(context, holder.mBinding.getFeed().getMediaSet());
holder.mBinding.viewpagerId.setAdapter(pagerAdapter);
ScrollingPagerIndicator pagerIndicator = holder.mBinding.indicator;
pagerIndicator.attachToPager(holder.mBinding.viewpagerId);
} else {
holder.mBinding.viewpagerId.setVisibility(View.GONE);
Glide.with(context).load(holder.mBinding.getFeed().getMediaSet().get(0).getFile())
.placeholder(R.drawable.image_placeholder)
.error(R.drawable.image_placeholder)
.into(holder.mBinding.image);
}
}
if (holder.mBinding.getFeed().getType().equals("video")) {
holder.mBinding.image.setVisibility(View.GONE);
MultiMediaAdapter pagerAdapter = new MultiMediaAdapter(context, holder.mBinding.getFeed().getMediaSet());
holder.mBinding.viewpagerId.setAdapter(pagerAdapter);
ScrollingPagerIndicator pagerIndicator = holder.mBinding.indicator;
pagerIndicator.attachToPager(holder.mBinding.viewpagerId);
}
holder.mBinding.clickUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("profileUserID", holder.mBinding.getFeed().getUserId());
view.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return feedList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
ListItemFeedPhotoBinding mBinding;
public ViewHolder(View itemView) {
super(itemView);
mBinding = DataBindingUtil.bind(itemView);
}
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
MultiMediaAdapter.java
public class MultiMediaAdapter extends PagerAdapter {
private PlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private ImageView image;
Context context;
List<FeedMediaSet> Media_list;
public MultiMediaAdapter(Context context, List<FeedMediaSet> Media_list) {
this.context = context;
this.Media_list = Media_list;
}
#Override
public int getCount() {
return Media_list.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
FeedMediaSet mediaObj = Media_list.get(position);
if (mediaObj.getType().equals("image")) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_item_media_photo,container,false);
image = view.findViewById(R.id.image);
Glide.with(context).load(mediaObj.getFile())
.placeholder(R.drawable.image_placeholder)
.error(R.drawable.image_placeholder)
.into(image);
container.addView(view);
return view;
} else if (mediaObj.getType().equals("video")) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_item_media_video,container,false);
simpleExoPlayerView = view.findViewById(R.id.playerView);
image = view.findViewById(R.id.image);
image.setVisibility(View.GONE);
initializePlayer(mediaObj.getFile(), mediaObj.getExtra());
container.addView(view);
return view;
}
return null;
}
private void initializePlayer(String uri, String extra) {
player = ExoPlayerFactory.newSimpleInstance(context);
try {
Uri mp4VideoExtraUri = Uri.parse(uri);
InputStream inputStream = context.getContentResolver().openInputStream(mp4VideoExtraUri);
Drawable yourDrawable = Drawable.createFromStream(inputStream, extra);
simpleExoPlayerView.setDefaultArtwork(yourDrawable);
} catch (FileNotFoundException e) {
Drawable yourDrawable = context.getResources().getDrawable(R.drawable.image_attach);
simpleExoPlayerView.setDefaultArtwork(yourDrawable);
}
DataSource.Factory mediaDataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, context.getResources().getString(R.string.app_name)));
MediaSource videoSource = new ProgressiveMediaSource.Factory(mediaDataSourceFactory)
.createMediaSource(Uri.parse(uri));
player.setPlayWhenReady(false);
player.prepare(videoSource);
if (simpleExoPlayerView != null) simpleExoPlayerView.setPlayer(player);
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
releasePlayer();
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
simpleExoPlayerView.setPlayer(null);
}
}
}

Phone directories in Android and problems with getting anything from them

Hi Stackoverflow community!
At first I want to say that I am a rookie in programming. Recently I tried to get photos from my phone directories by my app. It seems pretty hard to do, because I have only succeded in displaying my Camera directory, but not for example Download or Screenshots. It is really strange that Android Studio cannot resolve DOWNLOAD word in the line directories.add(filePaths.DOWNLOAD);
What is wrong with my code??? Or with me and my lack of experience...
My code:
public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";
//constants
private static final int NUM_GRID_COLUMNS = 3;
//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = (ImageView) view.findViewById(R.id.galleryImageView);
gridView = (GridView) view.findViewById(R.id.gridView);
directorySpinner = (Spinner) view.findViewById(R.id.spinnerDirectory);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");
ImageView shareClose = (ImageView) view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the gallery fragment.");
getActivity().finish();
}
});
TextView nextScreen = (TextView) view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if (isRootTask()) {
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
} else {
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}
}
});
init();
return view;
}
private boolean isRootTask() {
if (((ShareActivity) getActivity()).getTask() == 0) {
return true;
} else {
return false;
}
}
private void init() {
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
directories.add(filePaths.CAMERA);
directories.add(filePaths.DOWNLOAD);
ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
Log.d(TAG, "init: directory: " + directories.get(i));
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupGridView(String selectedDirectory) {
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth / NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);
//set the first image to be displayed when the activity fragment view is inflated
try {
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " + e.getMessage());
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));
setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});
}
private void setImage(String imgURL, ImageView image, String append) {
Log.d(TAG, "setImage: setting image");
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
mProgressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mProgressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
FilePaths sorry for not formatting
public class FilePaths {
//"storage/emulated/0"
public String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public String PICTURES = ROOT_DIR + "/Pictures";
public String CAMERA = ROOT_DIR + "/DCIM/camera";
public String FIREBASE_IMAGE_STORAGE = "photos/users/";
}
Well, the reason is simple. It's because you haven't defined the variable DOWNLOAD in the FilePaths.class. You also shouldn't point to the path like this, instead of that, use one or more of this variables:
Environment.getDataDirectory()
Environment.getDownloadCacheDirectory()
Environment.getExternalStorageDirectory()
Environment.getRootDirectory()
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS)
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES)
So your FilePaths should looks like this:
public class FilePaths {
//"storage/emulated/0"
public String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public String DOWNLOADS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
public String PICTURES = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
public String CAMERA = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
public String ALARMS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);
public String DOCUMENTS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
public String MOVIES = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
public String MUSIC = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
public String NOTIFICATIONS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS);
public String PODCASTS = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS);
public String RINGTONES = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES);
public String FIREBASE_IMAGE_STORAGE = "photos/users/";
}
It is in general not a good idea to use class names for your own class that are similar to java classes! Calling your class FilePaths will lead to confusion.
Change the name of your class to MyFilePaths (or something else!).
Then you can make the java file "MyFilePaths.java". Make the class public and make your variables static final:
public class MyFilePaths {
//"storage/emulated/0"
public static final String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public static final String PICTURES = ROOT_DIR + "/Pictures";
public static final String CAMERA = ROOT_DIR + "/DCIM/camera";
public static final String FIREBASE_IMAGE_STORAGE = "photos/users/";
}
Now you can do this:
directories.add(MyFilePaths.CAMERA);
Edit
In your code you call:
FilePaths filePaths = new FilePaths();
But your FilePaths class does not have a public constructor.

How to autoplay songs in recyclerView?

I am building a music player app and have populated the recyclerView with songs from sd card. I have set the onClickListeners too. So when I click one item (song), song at that particular position starts playing. What I want is when it completes playing, I want the next song to be played automatically like in modern music players. I know I have to use OnCompletionListener, but I can't figure it out.
I'm new to Android.
Songs.java (this is a fragment):
public class Songs extends Fragment {
public static final String Broadcast_PLAY_NEW_AUDIO = "com.musicplayer.musicana.PlayNewAudio";
public static final String TAG = "Songs";
RecyclerView recyclerView;
private ArrayList<SongInfoModel> SongList = new ArrayList<SongInfoModel>();
SongAdapter songAdapter;
ScaleInAnimationAdapter alphaAdapter;
MediaPlayer mediaPlayer;
MainActivity mainActivity;
private MediaPlayerService player;
boolean serviceBound = false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs_activity, container, false);
// Activity activity = getActivity();
final MainActivity activity=(MainActivity)getActivity();
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
songAdapter = new SongAdapter(getContext(), SongList, new SongAdapter.RecyclerItemClickListener() {
#Override
public void onClickListener(SongInfoModel song, int position) {
Toast.makeText(getContext(), song.getSongName(), Toast.LENGTH_SHORT).show();
Activity activity = getActivity();
if (activity instanceof MainActivity) {
mainActivity = (MainActivity) activity;
mainActivity.setsongText(song);
((MainActivity) activity).ButtonPause();
}
prepareSong(song);
}
#Override
public void onLongClickListener(SongInfoModel song, int position) {
Toast.makeText(getContext(), "You long clicked me, thank you!", Toast.LENGTH_SHORT).show();
}
});
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
Long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
Long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
SongInfoModel s = new SongInfoModel(name, artist, null, null, null, duration, data,albumArtUri);
SongList.add(s);
} while (cursor.moveToNext());
}
cursor.close();
Collections.sort(SongList, new Comparator<SongInfoModel>() {
#Override
public int compare(SongInfoModel lhs, SongInfoModel rhs) {
return lhs.getSongName().compareTo(rhs.getSongName());
}
});
}
alphaAdapter = new ScaleInAnimationAdapter(songAdapter);
alphaAdapter.setDuration(1000);
alphaAdapter.setInterpolator(new OvershootInterpolator());
alphaAdapter.setFirstOnly(false);
recyclerView.setAdapter(alphaAdapter);
alphaAdapter.notifyDataSetChanged();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
togglePlay(mp);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
});
activity.setOnSongClickListener(new MainActivity.OnSongCickListener() {
#Override
public void onsongClicked() {
if(mediaPlayer.isPlaying() && mediaPlayer!=null ){
mediaPlayer.pause();
activity.ButtonPlay();
} else {
mediaPlayer.start();
activity.ButtonPause();
}
}
});
return view;
}
private void prepareSong(SongInfoModel song) {
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(song.getData());
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
private void togglePlay(MediaPlayer mp) {
if (mp.isPlaying()) {
mp.stop();
mp.reset();
} else {
mp.start();
}
}
SongAdapter.java(recyclerVIews adapter):
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongHolder> {
ArrayList<SongInfoModel> SongList = new ArrayList<>();
Context context;
private RecyclerItemClickListener listener;
public SongAdapter(Context context, ArrayList<SongInfoModel> SongList, RecyclerItemClickListener listener) {
this.context = context;
this.SongList = SongList;
this.listener = listener;
}
#Override
public SongAdapter.SongHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_song, parent, false);
return new SongHolder(view);
}
#Override
public void onBindViewHolder(final SongAdapter.SongHolder holder, final int position) {
final SongInfoModel songInfoModel = SongList.get(position);
if(songInfoModel!= null){
holder.songName.setText(songInfoModel.SongName);
holder.artistName.setText(songInfoModel.ArtistName);
holder.duration.setText(String.valueOf(songInfoModel.duration));
String duration = Utility.convertDuration(songInfoModel.getDuration());
holder.duration.setText(duration);
Picasso.with(context).load(songInfoModel.getAlbumID()).placeholder(R.drawable.ic_launcher).into(holder.iv_artwork);
holder.bind(songInfoModel, listener);
}
}
#Override
public int getItemCount() {
return SongList.size();
}
public class SongHolder extends RecyclerView.ViewHolder {
TextView songName;
TextView artistName;
TextView duration;
private ImageView iv_artwork;
public SongHolder(View itemView) {
super(itemView);
songName = (TextView)itemView.findViewById(R.id.SongName);
artistName= (TextView)itemView.findViewById(R.id.ArtistName);
duration = (TextView) itemView.findViewById(R.id.duration);
iv_artwork = (ImageView) itemView.findViewById(R.id.iv_artwork);
}
public void bind(final SongInfoModel songInfoModel, final RecyclerItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onClickListener(songInfoModel, getLayoutPosition());
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
listener.onLongClickListener(songInfoModel, getLayoutPosition());
return true;
}
});
}
}
public interface RecyclerItemClickListener{
void onClickListener(SongInfoModel song, int position);
void onLongClickListener(SongInfoModel song, int position);
}
}
You can use the Completion Listener of Media Player like this
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//pass the path of the new song here
}
});
I just found out the solution! It is easy!
In SongAdapter.java : Add this,
private int selectedPosition;
public void setSelectedPosition(int selectedPosition) {
this.selectedPosition = selectedPosition;
}
public int getSelectedPosition() {
return selectedPosition;
}
In Songs.java: Add this,
private void changeSelectedSong(int index){
songAdapter.notifyItemChanged(songAdapter.getSelectedPosition());
currentIndex = index;
songAdapter.setSelectedPosition(currentIndex);
songAdapter.notifyItemChanged(currentIndex);
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(currentIndex + 1 < SongList.size()){
SongInfoModel next = SongList.get(currentIndex + 1);
changeSelectedSong(currentIndex+1);
prepareSong(next);
mainActivity.setsongText(next);
}else{
SongInfoModel next = SongList.get(0);
changeSelectedSong(0);
prepareSong(next);
mainActivity.setsongText(next);
}
}
});
And call changeSelectedSong(position) in onClick.

Categories