Passing data between two RecyclerViews - android

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);
}
}

Related

RecyclerView, each items has its own activity

I have a RecyclerView, it has items in it. I need each item to have its own Activity, that is, we have item1 by clicking on it, Activity1 opens, there is also item2 about clicking on it, Activity2 is opened. Can this be done somehow? If so, how? I managed to make it so that when I clicked, the same Fragment opened, and the text changes depending on which item was clicked. But it doesn't quite suit me.
Fragment where the RecyclerView is located
public class FragmentAttractionRecyclerView extends Fragment {
private RecyclerView mRec;
private AttractionsAdapter adapter;
private ArrayList<AttractionsItem> exampleList;
private RecyclerView.LayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_attraction_test_2, container, false);
}
#SuppressLint("InflateParams")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
createExampleList();
buildRecyclerView();
}
public void createExampleList() {
exampleList = new ArrayList<>();
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Baby островок", "Детский", "60₽","Максимальное кол-во детей","10","Возраст","С 1-го до 6 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Виражи", "Детский", "80₽","Максимальное кол-во пассажиров","24", "Возраст","От 4-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_kid, "Вокруг света", "Детский", "50₽","Максимальное кол-во пассажиров","12","Возраст","От 3-х до 12 лет"));
exampleList.add(new AttractionsItem(R.mipmap.unnamed, R.drawable.ic_interactive, "5D кинотеатр", "Интерактивный", "120₽","Максимальное кол-во пассажиров","","Возраст","С 6 лет"));
}
public void buildRecyclerView() {
mRec = requireView().findViewById(R.id.attraction_recycler);
adapter = new AttractionsAdapter(exampleList);
mLayoutManager = new LinearLayoutManager(getContext());
mRec.setLayoutManager(mLayoutManager);
mRec.setAdapter(adapter);
}
}
Adapter for RecyclerView
public class AttractionsAdapter extends RecyclerView.Adapter<AttractionsAdapter.AttractionsViewHolder> {
public ArrayList<AttractionsItem> mFavList;
public AttractionsAdapter(ArrayList<AttractionsItem> favList) {
mFavList = favList;
}
#NonNull
#Override
public AttractionsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_attraction, parent, false);
AttractionsViewHolder evh = new AttractionsViewHolder(v);
return evh;
}
public static class AttractionsViewHolder extends RecyclerView.ViewHolder {
public ImageView card_image_1, card_image_2;
public TextView card_text_1, card_text_2, card_text_3,attraction_menu_1_1,attraction_menu_1_2;
public CardView Card;
public AttractionsViewHolder(View itemView) {
super(itemView);
card_image_1 = itemView.findViewById(R.id.card_image_1);
card_image_2 = itemView.findViewById(R.id.card_image_2);
card_text_1 = itemView.findViewById(R.id.card_text_1);
card_text_2 = itemView.findViewById(R.id.card_text_2);
card_text_3 = itemView.findViewById(R.id.card_text_3);
attraction_menu_1_1 = itemView.findViewById(R.id.attraction_menu_1_1);
attraction_menu_1_2 = itemView.findViewById(R.id.attraction_menu_1_2);
Card = itemView.findViewById(R.id.Card);
}
}
#Override
public void onBindViewHolder(AttractionsViewHolder holder, int position) {
AttractionsItem currentItem = mFavList.get(position);
holder.card_image_1.setImageResource(currentItem.getImg1());
holder.card_image_2.setImageResource(currentItem.getImg2());
holder.card_text_1.setText(currentItem.get_attraction_name());
holder.card_text_2.setText(currentItem.get_attraction_type());
holder.card_text_3.setText(currentItem.get_attraction_cost());
holder.Card.setOnClickListener(v -> {
FragmentBlancAttraction fragment = new FragmentBlancAttraction(); // you fragment
FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); // instantiate your view context
Bundle bundle = new Bundle();
bundle.putString("name", currentItem.get_attraction_name());
bundle.putString("menu_1_1", currentItem.get_attraction_menu_1_1());
bundle.putString("menu_1_2", currentItem.get_attraction_menu_1_2());
bundle.putString("menu_2_1", currentItem.get_attraction_menu_2_1());
bundle.putString("menu_2_2", currentItem.get_attraction_menu_2_2());
fragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.animator.nav_default_enter_anim, R.animator.nav_default_exit_anim,
R.animator.nav_default_pop_enter_anim, R.animator.nav_default_pop_exit_anim);
fragmentTransaction.replace(R.id.fragment, fragment);// your container and your fragment
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
});
}
#Override
public int getItemCount() {
return mFavList.size();
}
}
public class AttractionsItem
{
private int mImg_1,mImg_2;
private final String mText_attraction_name;
private final String mText_attraction_type;
private final String mText_attraction_cost;
private final String mText_attraction_menu_1_1;
private final String mText_attraction_menu_1_2;
private final String mText_attraction_menu_2_1;
private final String mText_attraction_menu_2_2;
public AttractionsItem(int img1,int img2, String text_attraction_name, String text_attraction_type, String text_attraction_cost, String text_attraction_menu_1_1, String text_attraction_menu_1_2, String text_attraction_menu_2_1, String text_attraction_menu_2_2)
{
mImg_1 = img1;
mImg_2 = img2;
mText_attraction_name = text_attraction_name;
mText_attraction_type = text_attraction_type;
mText_attraction_cost = text_attraction_cost;
mText_attraction_menu_1_1 = text_attraction_menu_1_1;
mText_attraction_menu_1_2 = text_attraction_menu_1_2;
mText_attraction_menu_2_1 = text_attraction_menu_2_1;
mText_attraction_menu_2_2 = text_attraction_menu_2_2;
}
public int getImg1()
{
return mImg_1;
}
public int getImg2()
{
return mImg_2;
}
public String get_attraction_name()
{
return mText_attraction_name;
}
public String get_attraction_type()
{
return mText_attraction_type;
}
public String get_attraction_cost()
{
return mText_attraction_cost;
}
public String get_attraction_menu_1_1()
{
return mText_attraction_menu_1_1;
}
public String get_attraction_menu_1_2()
{
return mText_attraction_menu_1_2;
}
public String get_attraction_menu_2_1()
{
return mText_attraction_menu_2_1;
}
public String get_attraction_menu_2_2()
{
return mText_attraction_menu_2_2;
}
}
The positon param inside onBindViewHolder() method tells you which item of your RecyclerView clicked.
Use this to control your program and in out of onBindViewHolder() method you can get your item position by getAdapterPosition().
holder.Card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0: {
// Start first activity.
break;
}
case 1: {
// Start Second activity.
break;
}
}
}
});

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();

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

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

Sort RecyclerView

I'm using recyclerview to show my list of ground machines. Also I have a check box widget. When check box is checked, I want to sort my list by brand of machine. In my adapter I have a method setMachine(List listMachines); which has a reference to my current list of machines. Also my sort method works fine, but when I checked my check box my list is not sorted, worst it's disappeared, and my current list of machines is zero. Can someone help me to understand why that is happening:
My RecyclerView Adapter:
public class ListMachineAdapter extends RecyclerView.Adapter<ListMachineAdapter.ViewHolder> {
private List<Machine> listOfMachines;
private ClickMachineItemListener selectMachine;
private View.OnClickListener showToast = new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewHolder vh = (ViewHolder) v.getTag();
int position = vh.getItemPosition();
selectMachine.onClick(position);
}
};
public ListMachineAdapter(List<Machine> listOfMachines) {
this.listOfMachines = listOfMachines;
}
#Override
public ListMachineAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_list_machine, parent, false);
view.setOnClickListener(showToast);
return new ViewHolder(view, viewType);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Machine machine = listOfMachines.get(position);
holder.setPosition(position);
holder.brandMachine.setText(machine.getTypeBrand());
holder.typeMachine.setText(machine.getTypeMachine());
}
#Override
public int getItemCount() {
return listOfMachines.size();
}
public void setMachine(List<Machine> listMachines){
this.listOfMachines = listMachines; // size = 0 ??
}
public void setSelectMachine(ClickMachineItemListener selectMachine){
this.selectMachine = selectMachine;
}
Also I using Singleton to store my sort method:
public class MachineManager {
private static MachineManager instance;
private List<Machine> listOfGroundMachines;
private MachineManager() {
listOfGroundMachines = new ArrayList<>();
}
public static MachineManager getInstance() {
return instance = (instance == null) ? new MachineManager() : instance;
}
public List<Machine> sortByTypeBrand() {
Collections.sort(listOfGroundMachines, new Comparator<Machine>() {
#Override
public int compare(Machine lhs, Machine rhs) {
return lhs.getTypeBrand().compareToIgnoreCase(rhs.getTypeBrand());
}
});
return listOfGroundMachines;
}
}
And this is my Activity:
public class ListGroundMachineActivity extends Activity {
private CheckBox sortByTypeMachine, sortByTypeEngine, sortByTypeBrand, sortByYear;
private List<Machine> listOfGroundMachines;
private ListMachineAdapter adapter;
private MachineManager manager;
private ClickMachineItemListener click = new ClickMachineItemListener() {
#Override
public void onClick(int position) {
Machine machine = listOfGroundMachines.get(position);
Intent intent = new Intent(ListGroundMachineActivity.this, MachineDetailsActivity.class);
intent.putExtra(Constants.TYPE, machine.getTypeMachine());
intent.putExtra(Constants.BRAND, machine.getTypeBrand());
intent.putExtra(Constants.YEAR, machine.getYear());
intent.putExtra(Constants.ENGINE, machine.getTypeEngine());
Toast.makeText(ListGroundMachineActivity.this, machine.getTypeBrand(), Toast.LENGTH_SHORT).show();
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_ground_machine);
manager = MachineManager.getInstance();
listOfGroundMachines = populateGroundListMachine();
Log.i("TAG", "List size is " + listOfGroundMachines.size());
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list_ground_machine);
adapter = new ListMachineAdapter(listOfGroundMachines);
sortByTypeMachine = (CheckBox) findViewById(R.id.sort_by_type_ground_machine);
adapter.setSelectMachine(click);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
.color(R.color.teal).build());
recyclerView.setAdapter(adapter);
sortByTypeMachine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
adapter.setMachine(manager.sortByTypeBrand());
adapter.notifyDataSetChanged();
Log.i("TAG 1", "List size is " + manager.sortByTypeBrand());
}
});
}
private List<Machine> populateGroundListMachine() {
List<Machine> listOfGroundMachineOne = new ArrayList<>();
MachineDB machineDb = new MachineDB(this);
SQLiteDatabase sqLiteDatabase = machineDb.getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(MachineDB.TABLE_GROUND_MACHINE, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String typeBrand = cursor.getString(cursor.getColumnIndex(Constants.BRAND));
String typeMachine = cursor.getString(cursor.getColumnIndex(Constants.TYPE));
String typeEngine = cursor.getString(cursor.getColumnIndex(Constants.ENGINE));
String year = cursor.getString(cursor.getColumnIndex(Constants.YEAR));
Machine machine = new Machine(typeBrand, typeMachine, typeEngine, year);
listOfGroundMachineOne.add(machine);
}
sqLiteDatabase.close();
return listOfGroundMachineOne;
}
Your listOfGroundMachines in MachineManager is only an empty arraylist:
private MachineManager() {
listOfGroundMachines = new ArrayList<>();
}
You need to create setter for that and call the setter after this code:
manager = MachineManager.getInstance();
listOfGroundMachines = populateGroundListMachine();
// here
The MachineManager listOfGroundMachines is an empty list.
You call listOfGroundMachines = populateGroundListMachine(); in your Activity class.
The list being populated with the machines is a member of ListGroundMachineActivity and not of MachineManager.

How to send data using putExtra of the an Adapter Class to a new Activity

I have a problem to send data using putExtra (of the a Adapter Class to an new Activity). I think that my problem is in Parcelable, but I cannot find where there are the problem.
Follow my class for you understand better.
Consultorio.class
public class Consultorio implements Parcelable {
private String nome;
private int photo;
public Consultorio() {
}
* #param nome
* #param photo
public Consultorio( String nome, int Photo)) {
this.nome = nome;
this.photo = photo;
}
/**
* #return
*/
public String getNome() {
return nome;
}
/**
* #param nome
*/
public void setNome(String nome) {
this.nome = nome;
}
public int getPhoto() {
return photo;
}
public void setPhoto(int photo) {
this.photo = photo;
}
//PARCELABLE
public Consultorio(Parcel parcel){
setNome(parcel.readString());
setPhoto(parcel.readInt());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(photo);
dest.writeString(nome);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator<Consultorio>() {
#Override
public Consultorio createFromParcel(Parcel source) {
return new Consultorio(source);
}
#Override
public Consultorio[] newArray(int size) {
return new Consultorio[size];
}
};
public void readFromParcel(Parcel in) {
nome = in.readString();
photo = in.readInt();
}
}
Follow My Class Fragment (because I'm using TabLayout)
public class ClinicaMedicaFragment extends Fragment {
private List<Consultorio> consultorioList = new ArrayList<Consultorio>();
private ClinicaAdapter adapter;
private Toolbar toolbar;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.clinica_medica_fragment, container, false);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.clinica_recyclerView);
toolbar = (Toolbar) v.findViewById(R.id.tb_main);
GridLayoutManager manager = new GridLayoutManager(v.getContext(),
2, GridLayoutManager.VERTICAL, false);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (position % 3 == 0 ? 2 : 1);
}
});
recyclerView.setLayoutManager(manager);
List<Consultorio> list = new ArrayList<Consultorio>();
Consultorio c0 = new Consultorio();
c0.setPhoto(R.mipmap.img1);
c0.setNome("Name 1");
Consultorio c1 = new Consultorio();
c1.setPhoto(R.mipmap.img2);
c1.setNome("Name 2");
Consultorio c2 = new Consultorio();
c2.setPhoto(R.mipmap.img3);
c2.setNome("Name 3");
list.add(c0);
list.add(c1);
list.add(c2);
consultorioList = list;
adapter = new ClinicaAdapter(list);
recyclerView.setAdapter(adapter);
return v;
}
Follow My CLASS Adapter (in this class I'm using putExtra for send datato an new Activity)
public class ClinicaAdapter extends RecyclerView.Adapter<ClinicaAdapter.ViewHolder>{
private List<Consultorio> consultorioList;
//protected Boolean isHomeList = false;
public ClinicaAdapter(List<Consultorio> data) {
consultorioList = data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.clinica_medica_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Consultorio consultorio = consultorioList.get(position);
holder.imageViewPhoto.setImageResource(consultorio.getPhoto());
holder.imageViewPhoto.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), ClinicaActivity.class);
intent.putExtra("consultorio", consultorio);
view.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return consultorioList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageViewPhoto;
public ViewHolder(View itemView) {
super(itemView);
imageViewPhoto = (ImageView) itemView.findViewById(R.id.clinc_img);
}
}
Inmy Class Activity I pick up information by
Consultorio mConsultorio;
mConsultorio = getIntent().getParcelableExtra("consultorio");
The parcelable should maintain order of write and read members. Your writeToParcel method write int photo first and then string nome, but readFromParcel method read int photo secondly.
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(nome); // <- I changed nome firstly.
dest.writeInt(photo);
}
public void readFromParcel(Parcel in) {
nome = in.readString();
photo = in.readInt();
}
I strongly recommend you to find and install Android Pacelable Code Generator plugin in Android Studio. It will automatically generate Parcelable i/o of the class for you. After installing the plugin, just right click at the class name, and click "Generate..." > "Parcelable" menu.

Categories

Resources