How to show images in recyclerview with date as a header? - android

I am working on an application where I have to display images stored in phone directory.I have implemented the code to get all images in recyclerview, but I want to show the date of the image when it was taken inside header. I have searched for many days but couldn't find any specific answer. The design I am following is in this
Image
Here I am initializing my view
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.fragment_list_images,container,false);
ButterKnife.bind(this,view);
context= view.getContext();
adapter= new ImagesAdapter();
LinearLayoutManager linearVertical = new LinearLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(linearVertical);
recyclerView.setAdapter(adapter);
checkboxHeaderVideo.setClickable(false);
adapter.setData(getImages(context));
return view;
}
And here I am getting all pictures from directory
private List<ImagesModel> getImages(Context context) {
ArrayList<ImagesModel> ImagesModels= new ArrayList<>();
int int_position = 0;
Uri uri;
int column_index_data, thum, column_index_gif, thumGif;
String absolutePathOfImage = null;
String duration = null;
uri = MediaStore.Image.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Image.Media.BUCKET_DISPLAY_NAME,MediaStore.Image.Media._ID,MediaStore.Image.Thumbnails.DATA};
final String orderBy = MediaStore.Image.Media.DATE_TAKEN;
cursor = context.getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
thum = cursor.getColumnIndexOrThrow(MediaStore.Image.Thumbnails.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
File files= new File(absolutePathOfImage);
if (files.exists()){
retriever.setDataSource(absolutePathOfImage);
ArrayList<String> list = AppUtils.fileParsing(absolutePathOfImage);
String path_name =list.get(0);
Log.i("path name",path_name);
ImagesModel obj_model = new ImagesModel();
obj_model.setImageName(path_name);
obj_model.setThumbNail(cursor.getString(thum));
obj_model.setSelected(false);
obj_model.setAbsolutePath(absolutePathOfImage);
ImagesModels.add(obj_model);
}
}
listSize= ImagesModels.size();
return ImagesModels;
}
Image Adapter.
public class ImagesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<ImagesModel> modelList;
private boolean selection;
OnSelectionChangeListener selectionChangeListener;
int count=0;
public void setSelectionChangeListener(OnSelectionChangeListener selectionChangeListener) {
this.selectionChangeListener = selectionChangeListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.li_Images_list,parent,false);
return new ImagesItemHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
int size= modelList.size();
((ImagesItemHolder)holder).bindData(modelList.get(position),position,size);
}
#Override
public int getItemCount() {
return modelList.size();
}
public void setData(List<ImagesModel> list) {
this.modelList= list;
notifyDataSetChanged();
}
public boolean isSelection() {
return selection;
}
public void setSelection(boolean selection) {
this.selection = selection;
if (selectionChangeListener != null)
selectionChangeListener.onSelectionChange(selection);
notifyDataSetChanged();
}
public void clearSelection() {
for (ImagesModel obj : getData()) {
obj.setSelected(false);
}
setSelection(false);
count=0;
}
public interface OnSelectionChangeListener {
void onSelectionChange(boolean selection);
}
public List<ImagesModel> getData() {
return modelList;
}
public void setChecked(int position) {
count++;
getData().get(position).setSelected(!getData().get(position).isSelected());
if (!isAnyItemSelected()) {
setSelection(false);
} else notifyItemChanged(position);
}
boolean isAnyItemSelected() {
for (ImagesModel obj : getData()) {
if (obj.isSelected())
return true;
}
return false;
}
public void setCheckedAll(boolean selection) {
for (ImagesModel object : getData())
object.setSelected(selection);
count= getData().size();
setSelection(selection);
}
public int getSelectedItemCount(){
return count;
}
public ArrayList<ImagesModel> getAllSelectedItems() {
ArrayList<ImagesModel> selectedObjects = new ArrayList<>();
if (getData() != null && !getData().isEmpty()) {
for (ImagesModel item : getData()) {
if (item.isSelected()) selectedObjects.add(item);
}
}
return selectedObjects;
}
Problem is i don't know how to add Date as header in specific format and show related images below that specific date

Related

Updating code to save the state of the clicked items

I'm a new developer to android development. I'll like the code below (for querying and displaying images media collection) whose images checkboxes are checked when clicked, to be updated to include onsaveinstancestate to save the state of the clicked/checked items.
public class PhotosFragment extends Fragment {
ArrayList<ImageModel > imageList;
RecyclerView imageRecyclerView;
ImageAdapter imageAdapter;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_photos, container, false);
runtimePermission();
return view;
}
private void runtimePermission() {
Dexter.withContext(getContext()).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
init();
getAllImages();
setImageList();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(getContext(), "Permission is Required!", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public void init() {
imageRecyclerView = (RecyclerView) view.findViewById(R.id.photos_recycler);
imageList = new ArrayList<>();
}
public void setImageList() {
imageRecyclerView.setLayoutManager((new GridLayoutManager(getContext(), 4)));
imageAdapter = new ImageAdapter(getContext(), imageList);
imageRecyclerView.setAdapter(imageAdapter);
/* Here `isSelected` is a boolean variable. It is true when item is checked and false when not checked. When false, the if condition evaluates to true and the `selectImage()` method is called, otherwise the `unSelectImage()` is called */
imageAdapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
#Override
public void onItemViewClick(int position, View v){
try {
if (!imageList.get(position).isSelected) {
selectImage(position);
} else {
unSelectImage(position);
}
} catch (ArrayIndexOutOfBoundsException ed) {
ed.printStackTrace();
}
}
});
};
public void selectImage(int position) {
imageList.get(position).setSelected(true);
imageAdapter.notifyDataSetChanged();
}
public void unSelectImage(int position) {
imageList.get(position).setSelected(false);
imageAdapter.notifyDataSetChanged();
}
}
Querying the mediastore for images collection
public void getAllImages() {
Uri imageCollection;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
imageCollection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
imageCollection = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
String[] projection = new String[] {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.SIZE
};
String sortOrder = MediaStore.Images.Media.DATE_ADDED + " DESC";
Cursor cursor = getActivity().getContentResolver().query(imageCollection , projection, null, null, sortOrder);
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
int dateColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED);
int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idColumn);
String name = cursor.getString(nameColumn);
int duration = cursor.getInt(dateColumn);
int size = cursor.getInt(sizeColumn);
Uri uriImage = Uri.withAppendedPath(imageCollection, ""+ id);
ImageModel imageModel = new ImageModel();
imageModel.setImage(uriImage);
imageList.add(imageModel);
}
cursor.close();
}

how do i get single file size in listView

i'am trying to display all files in devices with specific extensions, but problem is i got wrong size on all files, it only display 22 bytes to all files in listView. and i want to get default picture like zip image, ISO image and image of APK.. where i do wrong
public class NotificationsFragment extends Fragment {
ListView listView;
String[] items;
private NotificationsViewModel notificationsViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
notificationsViewModel =
ViewModelProviders.of(this).get(NotificationsViewModel.class);
View root = inflater.inflate(R.layout.fragment_notifications, container, false);
listView = root.findViewById(R.id.app_list);
runtimePermission();
//final TextView textView = root.findViewById(R.id.text_notifications);
notificationsViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
//textView.setText(s);
}
});
return root;
}
public void runtimePermission() {
Dexter.withContext(getContext()).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
showList();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findList(File file) {
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
arrayList.addAll(findList(singleFile));
} else {
if (singleFile.getName().endsWith(".apk") || singleFile.getName().endsWith(".iso") || singleFile.getName().endsWith(".exe") || singleFile.getName().endsWith(".rar") || singleFile.getName().endsWith(".zip")) {
arrayList.add(singleFile);
}
}
}
return arrayList;
}
private void showList() {
final ArrayList<File> myApps = findList(Environment.getExternalStorageDirectory());
items = new String[myApps.size()];
for (int i = 0; i<myApps.size(); i++){
items[i] = myApps.get(i).getName().toString();
}
customAdapter customAdapter = new customAdapter();
listView.setAdapter(customAdapter);
}
public String readableFileSize(long size) {
if (size <= 0)
return "0";
final String[] units = new String[] { "byte", "kb", "mb", "gb", "tb" };
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
class customAdapter extends BaseAdapter {
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = getLayoutInflater().inflate(R.layout.download_item, null);
TextView songName = myView.findViewById(R.id.download_name);
ShapeableImageView appImage = myView.findViewById(R.id.download_img);
TextView sizeApp = myView.findViewById(R.id.app_details);
TextView install = myView.findViewById(R.id.install_btn);
songName.setSelected(true);
songName.setText(items[position]);
sizeApp.setText(readableFileSize(items.length));
// it gives 22 bytes to all list, which is not true
//How to get default image of file into listview??
return myView;
}
}
}
items is your list. So items.length is the length of the list, not the length of a file. Try sizeApp.setText(readableFileSize(items[position].length)).

How to update inner adapter item in android nested recycler view

I would like to update panel wise items in inner adapter item android recyclerview. When we pass the data dynamically.Data displaying is working fine. When we go to update the inner adapter item, it's not getting updated. But last item was getting update fine.
Activity.
public class PannelCreation extends AppCompatActivity {
RecyclerView userPanelRecycler;
List<String> roomPanels = new ArrayList<>();
List<JSONObject> roomItemObject = new ArrayList<JSONObject>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pannel_creation);
userPanelRecycler = findViewById(R.id.user_panel_recycler);
for(int i=0; i<=5;i++){
roomPanels.add("Panels "+i)
}
PanelAdapter panelAdapter = new PanelAdapter(getApplicationContext(),roomPanels);
userPanelRecycler.setLayoutManager(new LinearLayoutManager(this));
userPanelRecycler.setHasFixedSize(true);
userPanelRecycler.setAdapter(panelAdapter);
}
}
// OuterAdapter
class PanelAdapter extends RecyclerView.Adapter<PanelAdapter.ViewHolder>{
Context context;
List<String> roomPanelList;
RecyclerView.RecycledViewPool recycledViewPool;
List<ItemData> itemDataList = new ArrayList<>();
public PanelAdapter(Context context, List<String> roomPanels) {
this.context = context;
this.roomPanelList = roomPanels;
recycledViewPool = new RecyclerView.RecycledViewPool();
}
#NonNull
#Override
public PanelAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.panel_wise_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.itemsRecycler.setRecycledViewPool(recycledViewPool);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull PanelAdapter.ViewHolder holder, int position) {
holder.userPanelName.setText(roomPanelList.get(position));
String cur_panelName = roomPanelList.get(position);
itemsAdapter = new ItemsAdapter(context);
holder.itemsRecycler.setLayoutManager(new GridLayoutManager(context,3));
holder. itemsRecycler.setHasFixedSize(true);
holder.itemsRecycler.setAdapter(itemsAdapter);
holder.itemsRecycler.setNestedScrollingEnabled(false);
try {
roomItemObject.clear();
JSONArray metaArray = new JSONArray(metaData);
int count = 0;
for(int i = 0;i<metaArray.length();i++){
JSONObject object = metaArray.getJSONObject(i);
String name = object.getString("name");
String[] rNum = name.split("_");
if(rNum[0].equalsIgnoreCase(roomNumber)){
roomItemObject.add(object);
}
count = count+1;
}
if(count == metaArray.length()){
int count1 = 0;
itemDataList.clear();
for(int i =0; i < roomItemObject.size();i++){
JSONObject itemObject1 = roomItemObject.get(i);
String groupNames = itemObject1.getString("groupNames");
String types = itemObject1.getString("type");
String metaValue = itemObject1.getString("metadata");
JSONObject panelObject = new JSONObject(metaValue);
String panel_name = panelObject.getString("panelName");
JSONObject valueObject = new JSONObject(panel_name);
String value = valueObject.getString("value");
if(value.equalsIgnoreCase(cur_panelName)){
String labels = itemObject1.getString("label");
String names = itemObject1.getString("name");
String state = itemObject1.getString("state");
String groupName = itemObject1.getString("groupNames");
String tags = itemObject1.getString("tags");
ItemData itemData = new ItemData();
itemData.setLabelName(labels);
itemData.setState(state);
itemData.setItemName(names);
itemData.setTags(tags);
itemData.setTypes(types);
itemData.setGroup(groupName);
itemDataList.add(itemData);
itemsAdapter.addItems(itemDataList);
itemsAdapter.notifyDataSetChanged();
}
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return roomPanelList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder{
RecyclerView itemsRecycler;
TextView userPanelName;
Button deletePanel;
public ViewHolder(#NonNull View itemView) {
super(itemView);
itemsRecycler = itemView.findViewById(R.id.panel_item_recycler);
userPanelName = itemView.findViewById(R.id.test_panel_name);
deletePanel = itemView.findViewById(R.id.delete_panel);
}
}
}
//Inner Adapter
class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ItemHolder>{
Context mContext;
List<ItemData> innerItemDataList = new ArrayList<>();
List<JSONObject> itemObjectList = new ArrayList<JSONObject>();
List<JSONObject> recObjectList = new ArrayList<>();
ItemData itemData;
public ItemsAdapter(Context context) {
this.mContext = context;
this.itemData = new ItemData();
}
public void addItems(List<ItemData> itemData){
this.innerItemDataList.clear();
this.innerItemDataList.addAll(itemData);
notifyDataSetChanged();
}
#NonNull
#Override
public ItemsAdapter.ItemHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.panel_wise_item,parent,false);
return new ItemHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ItemHolder holder, int position) {
itemData = innerItemDataList.get(position);
if(itemData != null){
holder.itemNames.setText(itemData.getLabelName());
}
#Override
public int getItemCount() {
return innerItemDataList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ItemHolder extends RecyclerView.ViewHolder {
TextView itemNames;
LinearLayout itemLayout;
ImageView itemImg;
public ItemHolder(#NonNull View itemView) {
super(itemView);
itemNames = itemView.findViewById(R.id.panel_item_name);
itemLayout = itemView.findViewById(R.id.panel_light_linear);
itemImg = itemView.findViewById(R.id.panel_item_img);
}
}
public void updateItem(String itemName,String state){
for(int j=0;j<innerItemDataList.size();j++){
if(itemName.equalsIgnoreCase(innerItemDataList.get(j).getItemName())){
innerItemDataList.get(j).setState(state);
notifyDataSetChanged();
}
}
}
}
//Inner adapter data model class
public class ItemData {
String labelName;
String itemName;
String state;
String group;
String tags;
String types;
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}
How to update specific item in inner adapter android nested recycler view.Can anyone guide me how to deal with update specific item. One more thing have observed inner adapter returns last position of array list only. Items are updating fine in last position of array list. When trying to updating the rest of position array list items, not getting updated.
Thanks in Advance.
Amar.
In outer adapter when ever data changes need to notify. Try this code
panelAdapter.notifyDataSetChanged();

Passing data between two RecyclerViews

I building a music player that has a tab layout. One of the tabs is "Genres"(Genre.java) that displays the genres of songs in RecyclerView( songs that are present on the external storage of the android phone, by querying it). I have set onClickListeners too for the genres in the RecyclerView. So, when I click one the genres it should take me to another activity (GenresSongs.java) that displays all the song belonging to that clicked genre.
My problem:
When I click any of the genres, it takes me to another activity but it displays the song that was last added to the array. No matter which genre I click it takes me to the same song.
What I want:
When I click one of genres in the list it should take me to the song that belongs to the clicked genre. I hope you are getting my point. I'm passing GenreID as intent.
Genre.java(class that displays the genre of all the songs) :
public class Genres extends Fragment {
private static final String TAG = "Genres";
RecyclerView recyclerView_genre;
GenresAdapter genresAdapter;
ArrayList<GenresModel> Genrelist = new ArrayList<>();
Cursor genrecursor;
long id;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.genres_activity, container, false);
recyclerView_genre = view.findViewById(R.id.recyclerView_genre);
LinearLayoutManager genreLayout = new LinearLayoutManager(getContext());
recyclerView_genre.setLayoutManager(genreLayout);
final Uri uri = MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI;
genrecursor = getActivity().getContentResolver().query(uri,null,null, null, null);
if (genrecursor != null) {
if (genrecursor.moveToFirst()) {
do {
id = genrecursor.getLong(genrecursor.getColumnIndex(MediaStore.Audio.Genres._ID));
String name = genrecursor.getString(genrecursor.getColumnIndex(MediaStore.Audio.Genres.NAME));
GenresModel genresModel = new GenresModel(id,name);
Genrelist.add(genresModel);
Collections.sort(Genrelist, new Comparator<GenresModel>() {
#Override
public int compare(GenresModel lhs, GenresModel rhs) {
return lhs.getGenreName().compareTo(rhs.getGenreName());
}
});
} while (genrecursor.moveToNext());
}
genrecursor.close();
}
genresAdapter = new GenresAdapter(getContext(), Genrelist, new GenresAdapter.GenreItemClickListener() {
#Override
public void onClickListener(GenresModel genresModel, int GenrePosition) {
Intent nIntent = new Intent(getContext(), GenresSong.class);
nIntent.putExtra("genre_ID", id);
startActivity(nIntent);
}
});
recyclerView_genre.setAdapter(genresAdapter);
genresAdapter.notifyDataSetChanged();
return view;
}
GenresAdapter.java(the adapter class of Genres.java):
public class GenresAdapter extends RecyclerView.Adapter<GenresAdapter.GenresHolder> {
private Context gContext;
private ArrayList<GenresModel> GenreList = new ArrayList<>();
private GenreItemClickListener listenerGenre;
public GenresAdapter(Context gContext, ArrayList<GenresModel> genreList, GenresAdapter.GenreItemClickListener listenerGenre) {
this.gContext = gContext;
GenreList = genreList;
this.listenerGenre = listenerGenre;
}
#Override
public GenresAdapter.GenresHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view3 = LayoutInflater.from(gContext).inflate(R.layout.row_genre, parent, false);
return new GenresHolder(view3);
}
#Override
public void onBindViewHolder(GenresAdapter.GenresHolder holder, int position) {
final GenresModel genresModel1 = GenreList.get(position);
holder.genreText.setText( genresModel1.getGenreName());
holder.bindSong(genresModel1, listenerGenre);
}
#Override
public int getItemCount() {
return GenreList.size();
}
public class GenresHolder extends RecyclerView.ViewHolder {
TextView genreText;
public GenresHolder(View itemView) {
super(itemView);
genreText = itemView.findViewById(R.id.genreText);
}
public void bindSong(final GenresModel genresModel1, final GenreItemClickListener listenerGenre) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listenerGenre.onClickListener(genresModel1, getLayoutPosition());
}
});
}
}
public interface GenreItemClickListener{
void onClickListener(GenresModel genresModel, int GenrePosition);
}
GenresSong.java(class that is supposed to display songs when genre is clicked):
public class GenresSong extends Activity {
RecyclerView recyclerView_genreSong;
ArrayList <GenreSongModel> GenreSongList = new ArrayList<>();
GenresSongAdapter genresSongAdapter;
long genreID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.genres_details);
recyclerView_genreSong = findViewById(R.id.recyclerView_genreSong);
LinearLayoutManager l1 = new LinearLayoutManager(getApplicationContext());
recyclerView_genreSong.setLayoutManager(l1);
genreID = getIntent().getExtras().getLong("genre_ID");
Uri uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreID);
String[] projection ={MediaStore.Audio.Media.TITLE};
Cursor cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
GenreSongModel s = new GenreSongModel(name);
GenreSongList.add(s);
} while (cursor.moveToNext());
}
cursor.close();
Collections.sort(GenreSongList, new Comparator<GenreSongModel>() {
#Override
public int compare(GenreSongModel lhs, GenreSongModel rhs) {
return lhs.getSongName().compareTo(rhs.getSongName());
}
});
}
genresSongAdapter = new GenresSongAdapter(getApplicationContext(), GenreSongList);
recyclerView_genreSong.setAdapter(genresSongAdapter);
genresSongAdapter.notifyDataSetChanged();
}
GenresSongAdapter.java(adapter class for GenresSong.java):
public class GenresSongAdapter extends RecyclerView.Adapter<GenresSongAdapter.GenresSongHolder> {
Context gsContext;
ArrayList<GenreSongModel> GenresSongList2 = new ArrayList<>();
public GenresSongAdapter(Context gsContext, ArrayList<GenreSongModel> genresSongList2) {
this.gsContext = gsContext;
GenresSongList2 = genresSongList2;
}
#Override
public GenresSongAdapter.GenresSongHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v5 = LayoutInflater.from(gsContext).inflate(R.layout.row_genredetails, parent, false);
return new GenresSongHolder(v5);
}
#Override
public void onBindViewHolder(GenresSongAdapter.GenresSongHolder holder, int position) {
GenreSongModel genreSongModel = GenresSongList2.get(position);
holder.genreSongName.setText(genreSongModel.getSongName());
}
#Override
public int getItemCount() {
return GenresSongList2.size();
}
public class GenresSongHolder extends RecyclerView.ViewHolder {
TextView genreSongName;
public GenresSongHolder(View itemView) {
super(itemView);
genreSongName = itemView.findViewById(R.id.genreSongName);
}
}

How to get the list of songs of an album via AlbumID?

I'm building a music player that has fragments.It has 5 fragments - Ssongs, albums, artists, playlists, genre. Song.java fragment displays all the songs from sd card in recyclerVIew. And Albums.java displays the album cover of songs(in recyclerView) present in the SD card. What I want is when I click one of the album covers it should take me to another activity(AlbumsDetails.java) that displays all the songs in recyclerView contained in that particular album (just like in music players). I passed the AlbumID as intent from Albums.java to AlbumsDetails.java. I have tried many methods but did not succeed in displaying songs of the clicked album.
Albums.java
public class Albums extends Fragment {
private static final String TAG = "Albums";
RecyclerView recyclerViewAlbum;
AlbumsAdapter albumsAdapter;
private ArrayList<SongInfoModel> SongList1 = new ArrayList<SongInfoModel>();
long albumId;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.albums_activity, container, false);
recyclerViewAlbum = view.findViewById(R.id.albums_reyclerView);
recyclerViewAlbum.setHasFixedSize(true);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),2);
recyclerViewAlbum.setLayoutManager(gridLayoutManager);
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.TITLE));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
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, album, null, duration, data,albumArtUri, null);
SongList1.add(s);
} while (cursor.moveToNext());
}
cursor.close();
Collections.sort(SongList1, new Comparator<SongInfoModel>() {
#Override
public int compare(SongInfoModel lhs, SongInfoModel rhs) {
return lhs.getAlbum().compareTo(rhs.getAlbum());
}
});
}
albumsAdapter = new AlbumsAdapter( SongList1,getContext(), new AlbumsAdapter.RecyclerItemClickListener() {
#Override
public void onClickListener(SongInfoModel song, int position) {
Intent intent = new Intent(getContext(), AlbumDetails.class);
intent.putExtra("album_id", albumId);
startActivity(intent);
Activity activity = getActivity();
if (activity instanceof MainActivity) {
}
}
});
recyclerViewAlbum.setAdapter(albumsAdapter);
albumsAdapter.notifyDataSetChanged();
return view;
}
AlbumsDetails.java(this is the class where the songs of the clicked album should be displayed) :
public class AlbumDetails extends Activity {
RecyclerView albumsDetails_reyclerView;
AlbumsDetailsAdapter albumsDetailsAdapter;
private ArrayList<SongInfoModel> SongList2 = new ArrayList<SongInfoModel>();
long albumId;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_details);
albumsDetails_reyclerView = findViewById(R.id.albumsDetails_reyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
albumsDetails_reyclerView.setLayoutManager(linearLayoutManager);
Bundle extras = getIntent().getExtras();
if(extras != null){
albumId = getIntent().getExtras().getLong("album_id");
}
albumsDetailsAdapter = new AlbumsDetailsAdapter(getApplicationContext(), SongList2, new AlbumsDetailsAdapter.RecyclerItemClickListenerAlbumsDetails() {
#Override
public void onClickListener(SongInfoModel songInfoModelAlbumDetails, int positionAlbumDetails) {
}
}){
};
albumsDetails_reyclerView.setAdapter(albumsDetailsAdapter);
albumsDetailsAdapter.notifyDataSetChanged();
}
}
AlbumsDetailsAdapter.java(adapter class of AlbumsDetails.java):
public class AlbumsDetailsAdapter extends RecyclerView.Adapter<AlbumsDetailsAdapter.AlbumsDetailsHolder> {
Context context;
ArrayList<SongInfoModel> SongListAlbumDetails = new ArrayList<>();
private RecyclerItemClickListenerAlbumsDetails listenerAlbumDetails;
public AlbumsDetailsAdapter(Context context, ArrayList<SongInfoModel> songListAlbumDetails, RecyclerItemClickListenerAlbumsDetails listenerAlbumDetails) {
this.context = context;
SongListAlbumDetails = songListAlbumDetails;
this.listenerAlbumDetails = listenerAlbumDetails;
}
#Override
public AlbumsDetailsAdapter.AlbumsDetailsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_albumdetails, parent, false);
return new AlbumsDetailsHolder(view);
}
#Override
public void onBindViewHolder(AlbumsDetailsAdapter.AlbumsDetailsHolder holder, int position) {
final SongInfoModel songInfoModelAlbumDetails = SongListAlbumDetails.get(position);
holder.AlbumSongName.setText(songInfoModelAlbumDetails.getSongName());
holder.bindAlbumsDetails(songInfoModelAlbumDetails, listenerAlbumDetails);
}
#Override
public int getItemCount() {
return SongListAlbumDetails.size();
}
public class AlbumsDetailsHolder extends RecyclerView.ViewHolder {
TextView AlbumSongName;
public AlbumsDetailsHolder(View itemView) {
super(itemView);
AlbumSongName = itemView.findViewById(R.id.AlbumSongName);
}
public void bindAlbumsDetails(final SongInfoModel songInfoModelAlbumDetails, final RecyclerItemClickListenerAlbumsDetails listenerAlbumDetails) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listenerAlbumDetails.onClickListener(songInfoModelAlbumDetails, getLayoutPosition());
}
});
}
}
public interface RecyclerItemClickListenerAlbumsDetails{
void onClickListener(SongInfoModel songInfoModelAlbumDetails, int positionAlbumDetails);
}
SongInfoModel.java(Model class):
public class SongInfoModel {
public String SongName, ArtistName, Genre, Album, SongUrl,data;
public long duration; Uri albumIDArtwork;
public Long albumID;
public SongInfoModel(String songName, String artistName, String genre, String album, String songurl, long duration, String data, Uri albumIDArtwork, Long albumID) {
SongName = songName;
ArtistName = artistName;
Genre = genre;
Album = album;
SongUrl = songurl;
this.duration = duration;
this.data = data;
this.albumIDArtwork = albumIDArtwork;
this.albumID = albumID;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Uri getAlbumIDArtwork() {
return albumIDArtwork;
}
public Long getAlbumID() {
return albumID;
}
public void setAlbumID(Long albumID) {
this.albumID = albumID;
}
public void setAlbumIDArtwork(Uri albumID) {
this.albumIDArtwork = albumID;
}
public String getSongName() {
return SongName;
}
public void setSongName(String songName) {
SongName = songName;
}
public String getArtistName() {
return ArtistName;
}
public void setArtistName(String artistName) {
ArtistName = artistName;
}
public String getGenre() {
return Genre;
}
public void setGenre(String genre) {
Genre = genre;
}
public String getAlbum() {
return Album;
}
public void setAlbum(String album) {
Album = album;
}
public String getSongUrl() {
return SongUrl;
}
public void setSongUrl(String songUrl) {
SongUrl = songUrl;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
}

Categories

Resources