How to pass current data from Adapter to Adapter? - java

Heterogeneous RecyclerView
Hello friends I have a simple doubt
Here i am adding singleLineText
`addSingleLine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String singleLineText = singleline.getText().toString();
if(singleLineText.length() != 0)
{
mAdapter.addItem(singleLineText,null);
mAdapter.notifyDataSetChanged();
Log.e(TAG,"adding single line text");
}
singleline.getText().clear();
}
});`
On this part i am adding MultiLineText
` addMultiLine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String multiLineText = multiline.getText().toString();
String myList[] = multiLineText.split(",");
for(String item : myList)
{
mAdapter.addItem(null,item);
mAdapter.notifyDataSetChanged();
Log.e(TAG,"adding multi line text");
}
multiline.getText().clear();
}
});
}`
My Adapter part of code:
` public void addItem(String singleLineText, String item) {
Model model = new Model();
if(item == null) {
model.setText1(singleLineText);
model.settingSingleLineText(true); // How to identify single line
}
else
{
model.setText2(item);
model.settingMultiLineText(true); // How to identify multiple line
}
modelList.add(model);
}`
GetViewType Method:
` public int getItemViewType(int position) {
if (modelList.get(position).IfSingleLine() != null)
return VERTICAL;
else {
return HORIZONTAL;
}
}`
Model class code snippet:
private Boolean checkSingleLine = null;
public Boolean IfSingleLine()
{
return checkSingleLine;
}
public void settingSingleLineText(Boolean txt1)
{
checkSingleLine = txt1;
}
public void settingMultiLineText(Boolean txt2)
{
checkMultiLine = txt2;
}
`
Problem: How to identify the singleLineText and multiLineText by using the Model Class??

You have a problem with your if (modelList.get(position).IfSingleLine() != null). IfSingleLine() will never be null. You want to check if it is true or false and this is not how you check for that.
Change your getItemViewType to the following and you will get correct orientation result from this function.
public int getItemViewType(int position) {
if (modelList.get(position).IfSingleLine())
return VERTICAL;
else {
return HORIZONTAL;
}
}`

Related

issue with MenuInflater in the adapter function

I am working on my java code to call a function when I click on the RelativeLayout.
When I click on a RelativeLayout, I am calling toggleSelection function to insert the index in the array list and delete the index in the array list.
Adapter:
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.iconContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
toggleSelection(holder, pos);
}
});
public void toggleSelection(ViewHolder holder, int pos) {
currentSelectedIndex = pos;
if (selectedItems.get(pos, false)) {
selectedItems.delete(pos);
animationItemsIndex.delete(pos);
} else {
selectedItems.put(pos, true);
animationItemsIndex.put(pos, true);
}
Log.e("getSelectedItem...." + getSelectedItemCount, " ");
if (selectedItems.size() == 1) {
if (mInboxes.get(pos).getRead().equals("read")) {
Log.e("passed...5", " ");
}
if (holder.action_archive == null) {
Log.e("passed...6", " ");
//holder.action_archive.setVisible(true);
}
if (holder.action_delete == null) {
//holder.action_delete.setVisible(true);
}
}
notifyItemChanged(pos);
}
}
I want to set the menu items to visible when I click on RelativeLayout, but when I tried this:
MenuItem action_read = menu.findItem(R.id.action_mark_read);
if (action_read.isVisible() == true) {
...
}
It give me an error: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference.
Here is the full code:
public class InboxAdapter extends RecyclerView.Adapter<InboxAdapter.ViewHolder> {
public static List<inbox> mInboxes;
private Context mContext;
public String mailbox = "inbox";
public Window window;
public InboxAdapter adapter;
public Fragment _fragment;
public Menu menu;
public InboxAdapter(Context mContext, List<inbox> inboxes, Fragment fragment) {
this.mContext = mContext;
_fragment = fragment;
mInboxes = inboxes;
selectedItems = new SparseBooleanArray();
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.iconContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
toggleSelection(holder, pos);
}
});
#SuppressLint({"LongLogTag", "ResourceType"})
public void toggleSelection(ViewHolder holder, int pos) {
currentSelectedIndex = pos;
if (selectedItems.get(pos, false)) {
selectedItems.delete(pos);
animationItemsIndex.delete(pos);
} else {
selectedItems.put(pos, true);
animationItemsIndex.put(pos, true);
}
Log.e("getSelectedItem...." + getSelectedItemCount, " ");
MenuItem action_read = menu.findItem(R.id.action_mark_read);
MenuItem action_unread = menu.findItem(R.id.action_mark_unread);
if (selectedItems.size() == 1) {
if (mInboxes.get(pos).getRead().equals("read")) {
if (action_read.isVisible() == true) {
Log.e("passed...5", " ");
}
}
if (holder.action_archive == null) {
if (action_unread.isVisible() == true) {
Log.e("passed...6", " ");
}
}
if (holder.action_delete == null) {
Log.e("passed...7", " ");
//holder.action_delete.setVisible(true);
}
}
notifyItemChanged(pos);
}
}
Do you know how I can set the menu items to visible in the adapter function??

implementing Admob Native Advanced with RecyclerView but could not get the exact View Types

I already knew how the RecyclerView with different types of view works but this time I'm trying to add the Native Advance Admob ads to my RecyclerView. I followed theseYoutube Tutorials but there was an error printed to my logcat after the app crushed.
Logcat
java.lang.ClassCastException: com.google.android.gms.internal.ads.zzaeh cannot be cast to mgb.com.sdalyricsplus.Database.Entities.SongsEntity
at mgb.com.sdalyricsplus.newAdapters.DisplayItemAdapter.onBindViewHolder(DisplayItemAdapter.java:98)
at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
I reviewed the tutorial many times hoping that I've missed something that causes the error but it seems that I followed the tutorial correctly.
Here are my Codes
DisplayItemActivity
public class DisplayItemActivity extends AppCompatActivity{
public static final int NUMBER_OF_AD = 5;
AdLoader adLoader;
FastScrollRecyclerView recyclerView;
Global global;
RoomViewModel model;
List<Object> recyclerViewItems = new ArrayList<>();
List<UnifiedNativeAd> nativeAds = new ArrayList<>();
DisplayItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_songs);
MobileAds.initialize(this,"ca-app-pub-2493911630710964~1147957926");
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
global = (Global)getApplication();
model = ViewModelProviders.of(this).get(RoomViewModel.class);
adapter = new DisplayItemAdapter(getLayoutInflater());
recyclerView.setAdapter(adapter);
recyclerViewItems.addAll(model.selectAll());
loadNativeAds();
}
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(this, getResources().getString(R.string.native_advance));
adLoader = builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
nativeAds.add(unifiedNativeAd);
if (!adLoader.isLoading()) {
insertAdToList();
}
}
}).withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
if (!adLoader.isLoading()) {
insertAdToList();
}
}
}).build();
adLoader.loadAds(new AdRequest.Builder().build(), NUMBER_OF_AD);
}
private void insertAdToList() {
int offset = recyclerViewItems.size() / (nativeAds.size() + 1);
int index = 0;
for (UnifiedNativeAd ad : nativeAds) {
recyclerViewItems.add(index,ad);
index = index + offset;
}
adapter.setList(recyclerViewItems);
}
}
And my Adapter
DisplayItemAdapter
public class DisplayItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int MENU_ITEM_VIEW_TYPE = 0;
private final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;
private List<Object> recyclerViewItems = new ArrayList<>();
private Global global;
private String searchTxt = "";
private final String newline = System.getProperty("line.separator");
private ClickSongItemListener clickSongItemListener;
private ChangeFavoriteListener changeFavoriteListener;
private LayoutInflater layoutInflater;
public DisplayItemAdapter(LayoutInflater layoutInflater) {
this.layoutInflater = layoutInflater;
}
public void setList(List<Object> list) {
this.recyclerViewItems = list;
notifyDataSetChanged();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
global = (Global) ((Activity)parent.getContext()).getApplication();
switch (viewType) {
case UNIFIED_NATIVE_AD_VIEW_TYPE:
View adView = LayoutInflater.from(parent.getContext()).inflate(R.layout.native_ad_view,parent,false);
return new UnifiedNativeAdViewHolder(adView);
case MENU_ITEM_VIEW_TYPE :
default:
View songitem = LayoutInflater.from(parent.getContext()).inflate(R.layout.gospel_song_item,parent,false);
return new SongItemViewHolder(songitem);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case UNIFIED_NATIVE_AD_VIEW_TYPE :
UnifiedNativeAdViewHolder nativeAdViewHolder = (UnifiedNativeAdViewHolder)holder;
UnifiedNativeAd unifiedNativeAd = (UnifiedNativeAd) recyclerViewItems.get(position);
// poulateNativeAdView(unifiedNativeAd,((UnifiedNativeAdViewHolder)holder).getAdView());
FrameLayout frameLayout =
nativeAdViewHolder.view.findViewById(R.id.ad_frame_placement);
UnifiedNativeAdView adView = (UnifiedNativeAdView) layoutInflater
.inflate(R.layout.ad_unified, null);
populateUnifiedNativeAdView(unifiedNativeAd, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
break;
case MENU_ITEM_VIEW_TYPE :
default:
SongItemViewHolder songItemViewHolder = (SongItemViewHolder)holder;
setSongViews(songItemViewHolder, (SongsEntity)recyclerViewItems.get(position));
}
}
private void populateUnifiedNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdView adView) {
// Set the media view.
adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media));
// Set other ad assets.
adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
adView.setBodyView(adView.findViewById(R.id.ad_body));
adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
adView.setIconView(adView.findViewById(R.id.ad_app_icon));
adView.setPriceView(adView.findViewById(R.id.ad_price));
adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
adView.setStoreView(adView.findViewById(R.id.ad_store));
adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));
// The headline and mediaContent are guaranteed to be in every UnifiedNativeAd.
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
adView.getMediaView().setMediaContent(nativeAd.getMediaContent());
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
if (nativeAd.getBody() == null) {
adView.getBodyView().setVisibility(View.INVISIBLE);
} else {
adView.getBodyView().setVisibility(View.VISIBLE);
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
}
if (nativeAd.getCallToAction() == null) {
adView.getCallToActionView().setVisibility(View.INVISIBLE);
} else {
adView.getCallToActionView().setVisibility(View.VISIBLE);
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
}
if (nativeAd.getIcon() == null) {
adView.getIconView().setVisibility(View.GONE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(
nativeAd.getIcon().getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (nativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
}
if (nativeAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAd.getStore());
}
if (nativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView())
.setRating(nativeAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
if (nativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
adView.getAdvertiserView().setVisibility(View.VISIBLE);
}
// This method tells the Google Mobile Ads SDK that you have finished populating your
// native ad view with this native ad.
adView.setNativeAd(nativeAd);
// Get the video controller for the ad. One will always be provided, even if the ad doesn't
// have a video asset.
VideoController vc = nativeAd.getVideoController();
// Updates the UI to say whether or not this ad has a video asset.
if (vc.hasVideoContent()) {
// videoStatus.setText(String.format(Locale.getDefault(),
// "Video status: Ad contains a %.2f:1 video asset.",
// vc.getAspectRatio()));
// Create a new VideoLifecycleCallbacks object and pass it to the VideoController. The
// VideoController will call methods on this object when events occur in the video
// lifecycle.
vc.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
#Override
public void onVideoEnd() {
// Publishers should allow native ads to complete video playback before
// refreshing or replacing them with another ad in the same UI location.
super.onVideoEnd();
}
});
} else {
}
}
private void setSongViews(SongItemViewHolder viewHolder, SongsEntity note) {
Context context = viewHolder.itemView.getContext();
if (note.getMedia_extension().equals("audio")) {
Glide.with(context)
.load(R.drawable.music_icon)
.thumbnail(00.1f)
.into(viewHolder.iv_thumbnail);
}else if (note.getGenre().toLowerCase().contains("karaoke")) {
File file = new File(context.getExternalFilesDir(null)+"/.file"+note.getId());
if (file.exists()) {
Glide.with(context)
.setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.karaoke_icon))
.load(file)
.thumbnail(00.1f)
.into(viewHolder.iv_thumbnail);
}else {
Glide.with(context)
.setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.karaoke_icon))
.load(note.getMedia_url())
.thumbnail(00.1f)
.into(viewHolder.iv_thumbnail);
}
}else {
Glide.with(context)
.load(R.drawable.lyrics_icon)
.thumbnail(00.1f)
.into(viewHolder.iv_thumbnail);
}
viewHolder.title.setText(global.capitalize(note.getTitle()));
viewHolder.artist.setText(global.capitalize(note.getArtist()));
viewHolder.category.setText(note.getGenre());
viewHolder.favorite.setOnCheckedChangeListener(null);
viewHolder.favorite.setChecked(note.getFavorites());
viewHolder.views.setText(note.getFavorite_counter() <2 ? note.getFavorite_counter()+" heart" : note.getFavorite_counter()+" hearts");
String MY_ID = "JUntYdabhUh5XtMhfCIXXwNbsdW2";
if (!note.getUploader_id().equals(MY_ID))
Glide.with(context)
.setDefaultRequestOptions(new RequestOptions().placeholder(R.mipmap.sda_logo).diskCacheStrategy(DiskCacheStrategy.ALL))
.load(note.getUploader_photo_url())
.into(viewHolder.user_logo);
else
Glide.with(context)
.load(R.mipmap.sda_logo)
.into(viewHolder.user_logo);
String lyrics = note.getLyrics().toLowerCase();
String searchFilter = searchTxt.toLowerCase();
if (searchTxt.isEmpty()) {
viewHolder.phrase_end.setText(note.getLyrics());
viewHolder.phrase.setText("");
} else
if (lyrics.contains(searchFilter) && (lyrics.indexOf(searchFilter)) + searchTxt.length() <= lyrics.length()) {
viewHolder.phrase.setText(searchTxt);
String filter = note.getLyrics().substring(lyrics.indexOf(searchFilter) + searchFilter.length());
assert newline != null;
viewHolder.phrase_end.setText(filter.replaceAll(newline, " "));
}else {
viewHolder.phrase_end.setText(note.getLyrics());
viewHolder.phrase.setText("");
}
viewHolder.favorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (changeFavoriteListener != null) {
changeFavoriteListener.onChange(buttonView.getContext(),note,isChecked);
}
}
});
}
private void poulateNativeAdView(UnifiedNativeAd unifiedNativeAd, UnifiedNativeAdView adView) {
((TextView)adView.getHeadlineView()).setText(unifiedNativeAd.getHeadline());
((TextView)adView.getBodyView()).setText(unifiedNativeAd.getBody());
((TextView)adView.getCallToActionView()).setText(unifiedNativeAd.getCallToAction());
NativeAd.Image icon = unifiedNativeAd.getIcon();
if (icon == null) {
adView.getIconView().setVisibility(View.INVISIBLE);
}else {
((ImageView)adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (unifiedNativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
}else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView)adView.getPriceView()).setText(unifiedNativeAd.getPrice());
}
if (unifiedNativeAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
}else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView)adView.getStoreView()).setText(unifiedNativeAd.getStore());
}
if (unifiedNativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
}else {
adView.getStarRatingView().setVisibility(View.VISIBLE);
((RatingBar)adView.getStarRatingView()).setRating(unifiedNativeAd.getStarRating().floatValue());
}
if (unifiedNativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
}else {
adView.getAdvertiserView().setVisibility(View.VISIBLE);
((TextView)adView.getAdvertiserView()).setText(unifiedNativeAd.getAdvertiser());
}
adView.setNativeAd(unifiedNativeAd);
}
#Override
public int getItemCount() {
return recyclerViewItems.size();
}
public class SongItemViewHolder extends RecyclerView.ViewHolder {
TextView title, phrase,phrase_end;
TextView artist;
TextView category;
ToggleButton favorite;
LinearLayout layoutWrapper;
LinearLayout phrase_layout;
TextView views;
CircleImageView user_logo;
ImageView iv_thumbnail;
public SongItemViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.text_view_title);
iv_thumbnail = itemView.findViewById(R.id.iv_thumbnail);
artist = itemView.findViewById(R.id.text_view_artist);
phrase = itemView.findViewById(R.id.phrase);
phrase_end = itemView.findViewById(R.id.phrase_end);
category = itemView.findViewById(R.id.text_view_category);
favorite = itemView.findViewById(R.id.toggleButton_favorite);
layoutWrapper = itemView.findViewById(R.id.layout_wrapper);
phrase_layout = itemView.findViewById(R.id.phrase_layout);
views = itemView.findViewById(R.id.tv_view_status);
user_logo = itemView.findViewById(R.id.user_logo);
}
}
private class UnifiedNativeAdViewHolder extends RecyclerView.ViewHolder {
private View view;
public UnifiedNativeAdViewHolder(View view) {
super(view);
this.view = view;
}
}
}
the logcat says that com.google.android.gms.internal.ads.zzaeh cannot be cast to mgb.com.sdalyricsplus.Database.Entities.SongsEntity and the error was pointed to the viewbindholder
case MENU_ITEM_VIEW_TYPE :
default:
SongItemViewHolder songItemViewHolder = (SongItemViewHolder)holder;
setSongViews(songItemViewHolder, (SongsEntity)recyclerViewItems.get(position)); // this line
my suspect is the viewtype. Maybe the view type was not correctly assigned.
I tried this code also but the error still there.
#Override
public int getItemViewType(int position) {
if (position % DisplayItemActivity.NUMBER_OF_AD == 0) {
return UNIFIED_NATIVE_AD_VIEW_TYPE;
}else {
return MENU_ITEM_VIEW_TYPE;
}
}
can someone help me to find the cause of the error?
You need to merge your SongItem and UnifiedNativeAd to become 1 single data source.
Make a new object class name SongAdsData to merge your Song object and Ads from Admob into 1 single object like below:
public class SongAdsData {
public int getType() {
return type;
}
public UnifiedNativeAd getAds() {
return ads;
}
public Post getSong() {
return Song;
}
public int type; // 1 is ads and 2 is songs
public UnifiedNativeAd ads;
public Song song; // here is ur Song object as usual
}
In your adapter, modify it as below:
public class SongAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int UNIFIED_ADS_VIEW = 1;
private static final int SONG_ITEM_VIEW = 2;
private List<SongAdsData> songAdsDataList;
//here your onBindViewHolder,here your refer to item of `songAdsDataList`
// here your onCreateViewHolder
public void setSongAdsDataList(List<SongAdsData> songAdsDataForRecyclerView) {
this.songAdsDataList = songAdsDataForRecyclerView;
notifyDataSetChanged();
}
// Here is the function that insert the ads to RecyclerView
public void insertAdToRecyclerView(List<UnifiedNativeAds> nativeAds) {
int offset = songAdsDataList.size() / (nativeAds.size() + 1);
int index = 0;
for (UnifiedNativeAd ad : nativeAds) {
SongAdsData adsData = new SongAdsData();
adsData.song = null;
adsData.ads = ad;
adsData.type = 1; //1 for ads,2 for song
songAdsDataList.add(index,adsData);
index = index + offset;
}
notifyDataSetChanged();
}
#Override
public int getItemViewType (int position) {
if(songAdsDataList.get(position).getType() == 1){ // So here you compare the type of the object it the position
return UNIFIED_ADS;
}else{
return SONG_ITEM_VIEW;
}
}
#Override
public int getItemCount() {
if(songAdsDataList != null){
return songAdsDataList.size();
}else{
return 0;
}
}
}
So finally in your DisplayItemActivity
I not sure how you get your SongItem(your data from server or somewhere else),but the idea is transform your SongItem into SongAdsData that we created in the step one,
Example like this:
private void displaySongFromYourServer(List<Songs> songs) {
List<SongAdsData> songAdsDataList = new ArrayList<>();
for(Songs song : songs){
SongAdsData data = new SongAdsData();
data.ads = null;
data.song = song;
data.type = 2;
songAdsDataList.add(data);
}
songAdapter.setSongAdsDataList(songAdsDataList);
}
So by now,your Song item will become SongAdsData. At the same time, your UnifiedNativeAd object also need to transform become SongAdsData, therefore we need to
move all thing inside insertAdToList into SongAdapter(See the insertAdToRecyclerView in Song adapter above),so the it can refer to the same List of the recyclerView.
Therefore in your insertAdToList of DisplayItemActivity should become like this:
private void insertAdToList() {
songAdapter.insertAdsToRecyclerView(nativeAds); //called to the function inside songAdapter.
}
Hope you get the idea.
You need to override getItemViewType(int position) to check the instance of your Object in order to return the right view type:
#Override
public int getItemViewType(int position) {
if (this.recyclerViewItems.get(position) instanceof UnifiedNativeAd) {
return UNIFIED_NATIVE_AD_VIEW_TYPE;
}else {
return MENU_ITEM_VIEW_TYPE;
}
}

How to select selected value multivalue in recyclerview

i want to get selected ids in activity which is selected in recyclerview adapter
holder.images.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.checked.getVisibility() == View.VISIBLE) {
holder.checked.setVisibility(View.GONE);
} else if (holder.checked.getVisibility() == View.GONE) {
holder.checked.setVisibility(View.VISIBLE);
}
}
});
Use list to handle your selected items or positions
declare list for store selected items
private List<Integer> selectedPositions=new ArrayList();
update code in onBindViewHolder like below
holder.checked.setVisibility(selectedPositions.contains(position)?View.VISIBLE:View.GONE);
holder.images.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPositions.contains(position)) {
holder.checked.setVisibility(View.GONE);
selectedPositions.removeAt(selectedPositions.indexOf(position));
} else {
holder.checked.setVisibility(View.VISIBLE);
selectedPositions.add(position);
}
}
});
Here that solution i created arrylist and put data size
public static ArrayList<Integer> dataSize=new ArrayList<>();
and pass to adapter
holder.checked.setVisibility(idpositions.get(position)==0?View.GONE:View.VISIBLE);
holder.images.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (dataSize.size()>0) {
if (holder.checked.getVisibility() == View.VISIBLE) {
holder.checked.setVisibility(View.GONE);
dataSize.set(position,0);
} else if (holder.checked.getVisibility() == View.GONE) {
dataSize.add(position,data.getId());
holder.checked.setVisibility(View.VISIBLE);
}
}
}
});
and on button click simply get that arraylist and get your selected value
if(dataSize.size()>0){
for (int i = 0; i < dataSize.size(); i++) {
if (dataSize.get(i)==0){
continue;
}else {
ids= ids+String.valueOf(dataSize.get(i))+",";
}
}
Toast.makeText(this, ids, Toast.LENGTH_SHORT).show();
}
Now, you need to declare a list to hold those selected ids
private List<DATA_TYPE> selectedIds = new ArrayList();
What you can do is declare one isSelected boolean in your model. In onBindViewHolder method, set visibility as
if (YOUR_POJO.isSelected()) {
holder.checked.setVisibility(View.VISIBLE);
} else {
holder.checked.setVisibility(View.GONE);
}
When you click on image check if it was already selected based on that you can add/remove its id
holder.images.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(YOUR_POJO.isSelected()){
YOUR_POJO.setSelected(false);
if (selectedIds.contains(YOUR_POJO.getId()){
selectedIds.remove(YOUR_POJO.getId());
}
} else {
YOUR_POJO.setSelected(true);
selectedIds.add(YOUR_POJO.getId());
}
notifyItemChanged(holder.getAdapterPosition(), YOUR_POJO);
}
});
Hope this helps.
Create an interface class like this;
public interface ItemSelectedListener{
void onItemSelected(int selectedposition);
}
In your adapter initialize your interface;
private List<ItemSelectedListener> mItemSelectedSubscribers = new ArrayList<ItemSelectedListener>();
Add this method in your adapter ;
public void subscribeItemSelection(ItemSelectedListenerlistener) {
mItemSelectedSubscribers .add(listener);
}
Set this loop in your click events;
for (ItemSelectedListener listener : mMediaSelectedSubscribers) {
listener.onItemSelected(position);
}
In your activity, implement your interface and you will set a implemented methods. this methods look like this;
int selectedPosition;
#Override
public void onMediaSelected(int position) {
selectedPosition = position;
}
When you do this you can use your selected position where you want in your activity
Hope this help!

List<ParseUser> .contains ParseUser always FALSE

I have an if statement written below:
//Set Friend Action OnClickListener & Image
if (ParseUser.getCurrentUser().getList("friendsArray").contains(searchResultsList.get(position))) {
Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_phone_black_24dp).into(holder.imgFriendAction);
ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.green)));
}
else if (ParseUser.getCurrentUser().getList("pendingFriendsArray").contains(searchResultsList.get(position))) {
Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_check_black_24dp).into(holder.imgFriendAction);
ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.gray_dark)));
}
else {
Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_person_add_black_24dp).into(holder.imgFriendAction);
ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.colorPrimary)));
}
The problem is that every single time I run that statement it always returns FALSE for both if statements even though I know for a fact that 'friendsArray' & 'pendingFriendsArray' return TRUE in many circumstances.
Both arrays contain pointers to the _User table.
searchResultsList is declared as follows:
private List<ParseUser> searchResultsList;
I've logged all three items (friendsArray, pendingFriendsArray & searchResultsList.get(position)) to the console and they show the following:
D/friendsArray: [com.parse.ParseUser#ae66779, com.parse.ParseUser#8371cbe, com.parse.ParseUser#32d511f, com.parse.ParseUser#5fd2c6c, com.parse.ParseUser#7dd0235, com.parse.ParseUser#9c446ca, com.parse.ParseUser#5fe03b]
D/pendingFriendsArray: [com.parse.ParseUser#7c6a358, com.parse.ParseUser#3688cb1, com.parse.ParseUser#480596]
D/searchResultsList.get(position) =: com.parse.ParseUser#5fe03b
The entire class is below:
public class SearchUserAdapter extends RecyclerView.Adapter<SearchUserAdapter.ViewHolder> {
private Context searchContext;
private List<ParseUser> searchResultsList;
OnItemClickListener onItemClickListener;
public SearchUserAdapter(Context context, List<ParseUser> dataSet) {
searchContext = context;
searchResultsList = dataSet;
}
public interface OnItemClickListener {
public void onItemClick(View view, ParseUser searchUserObject, int position);
}
public void setOnItemClickListener(final OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(searchContext).inflate(R.layout.ly_search_user, parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
//Set User Name
holder.txtUserName.setText(searchResultsList.get(position).getString("fullName"));
//Set User Location
holder.txtUserLocation.setText(GlobalFunctions.getParseUserLocationAsString(holder.txtUserName.getContext(), searchResultsList.get(position)));
//Set User Profile Image
if (searchResultsList.get(position).getParseFile("profilePicture") != null) {
Glide.with(holder.imgUserProfilePicture.getContext()).applyDefaultRequestOptions(RequestOptions.circleCropTransform()).load(searchResultsList.get(position).getParseFile("profilePicture").getUrl()).into(holder.imgUserProfilePicture);
}
else {
Glide.with(holder.imgUserProfilePicture.getContext()).applyDefaultRequestOptions(RequestOptions.circleCropTransform()).load(R.drawable.ic_profile_place_holder).into(holder.imgUserProfilePicture);
}
//Set Row OnClickListener
holder.rlUserItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (searchResultsList.get(position).getObjectId().equalsIgnoreCase(ParseUser.getCurrentUser().getObjectId())) {
Intent openProfile;
openProfile = new Intent(holder.rlUserItem.getContext(), TimelineActivity.class);
holder.rlUserItem.getContext().startActivity(openProfile);
}
else {
Intent openOtherProfile = new Intent(holder.rlUserItem.getContext(), OtherUserTimelineActivity.class);
openOtherProfile.putExtra("otherUserProfileId", searchResultsList.get(position).getObjectId());
holder.rlUserItem.getContext().startActivity(openOtherProfile);
}
}
});
//Set Friend Action OnClickListener & Image
if (ParseUser.getCurrentUser().getList("friendsArray").contains(searchResultsList.get(position))) {
Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_phone_black_24dp).into(holder.imgFriendAction);
ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.green)));
}
else if (ParseUser.getCurrentUser().getList("pendingFriendsArray").contains(searchResultsList.get(position))) {
Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_check_black_24dp).into(holder.imgFriendAction);
ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.gray_dark)));
}
else {
Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_person_add_black_24dp).into(holder.imgFriendAction);
ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.colorPrimary)));
}
holder.imgFriendAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
friendActionListenerAction(holder, searchResultsList.get(position));
}
});
}
private void friendActionListenerAction(ViewHolder holder, ParseUser parseUser) {
if (ParseUser.getCurrentUser().getList("friendsArray").contains(parseUser)) {
FLKCallUtils.showCallDialog(holder.imgFriendAction.getContext());
}
else if (ParseUser.getCurrentUser().getList("pendingFriendsArray").contains(parseUser)) {
//Do nothing
}
else {
//Add Friend
FLKFriendUtils.sendFriendRequestFromUserToUser(ParseUser.getCurrentUser(), parseUser);
//Update Image
Glide.with(holder.imgFriendAction.getContext()).load(R.drawable.ic_check_black_24dp).into(holder.imgFriendAction);
ImageViewCompat.setImageTintList(holder.imgFriendAction, ColorStateList.valueOf(searchContext.getColor(R.color.gray_dark)));
}
}
#Override
public int getItemCount() {
return searchResultsList.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public MediumRobotoTextView txtUserName;
public RegularRobotoTextView txtUserLocation;
public RelativeLayout rlUserItem;
ImageView imgUserProfilePicture;
ImageView imgFriendAction;
public ViewHolder(View itemView) {
super(itemView);
rlUserItem = (RelativeLayout) itemView.findViewById(R.id.rl_user_container);
rlUserItem.setOnClickListener(this);
txtUserName = (MediumRobotoTextView) itemView.findViewById(R.id.txt_user_name);
txtUserLocation = (RegularRobotoTextView) itemView.findViewById(R.id.txt_user_location);
imgUserProfilePicture = (ImageView) itemView.findViewById(R.id.img_profile_picture);
imgUserProfilePicture.setOnClickListener(this);
imgFriendAction = (ImageView) itemView.findViewById(R.id.img_friend_action);
imgFriendAction.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//TODO - do something here if you wish
}
}
Upon further investigation I found that the parse-android SDK does not fetch pointers the same every single time. For example when I fetch 'friendsArray', let's say right now, it will return
[com.parse.ParseUser#ae66779, com.parse.ParseUser#8371cbe, com.parse.ParseUser#32d511f, com.parse.ParseUser#5fd2c6c, com.parse.ParseUser#7dd0235, com.parse.ParseUser#9c446ca, com.parse.ParseUser#5fe03b]
However if I then fetch it, let's say in 5 minutes, it will return
[com.parse.ParseUser#ec99877, com.parse.ParseUser#674bcg, com.parse.ParseUser#749hhc, com.parse.ParseUser#6fh3d6dg, com.parse.ParseUser#jdj8dk, com.parse.ParseUser#4c966ca, com.parse.ParseUser#3f0eeb]
Additionally, I noted that even the pointer to searchResultsList.get(position) changes it's reference every time I loaded it.
The way I got around this was to create a function (seen below) that returns an array of the actual objectId's of the pointers inside the 'friendsArray'. This way I can guarantee that it will always be returning the same items and can therefore create an accurate 'contains' comparison.
public static List<String> friendsArrayObjectIdsArray() {
//Create Array of Friends
List<ParseUser> friendsArray = ParseUser.getCurrentUser().getList("friendsArray");
//Create Temp Array of Object Id's
List<String> tempObjectIdsArray = new ArrayList<>();
//Iterate List
for (ParseUser friendUser : friendsArray) {
tempObjectIdsArray.add(friendUser.getObjectId());
}
return tempObjectIdsArray;
}
I then run the following comparison to get the result I am looking for
if (FLKUserUtils.friendsArrayObjectIdsArray().contains(searchResultsList.get(position).getObjectId())) {
//Do something
}

Sort List by Integer

I get the Latitude and Longtitude from my Database and I calculate the distance between two persons in the RecyclerView Adapter.
I want to sort these items by distance, but I have no clue how I can do this.
My Adapter:
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder>{
Context context;
List<HomeGetter> homeGetters;
HomeCallback homeCallback;
public HomeAdapter(Context context, List<HomeGetter> homeGetters, HomeCallback homeCallback) {
this.context = context;
this.homeGetters = homeGetters;
this.homeCallback = homeCallback;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_home_profil,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
calculate_age calculate_age = new calculate_age();
final HomeGetter homeGetter = homeGetters.get(position);
String[] splittedAge = homeGetter.getBirthday().split("\\.");
try {
String age = calculate_age.getAge(context,Integer.valueOf(splittedAge[0]),Integer.valueOf(splittedAge[1]),Integer.valueOf(splittedAge[2]));
String username = homeGetter.getUsername().substring(0,1).toUpperCase() + homeGetter.getUsername().substring(1);
holder.textViewUsername.setText(username + "," + age);
} catch (ParseException e) {
e.printStackTrace();
}
Picasso.with(context).load(homeGetter.getImageURL()).resize(600,700).centerCrop().into(holder.imageView);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homeCallback.getPosition(position);
}
});
holder.textViewLocation.setText(homeGetter.getLocation());
if(homeGetter.getStatus().equals("0")){
holder.status.setImageDrawable(context.getResources().getDrawable(R.drawable.offline));
}else {
holder.status.setImageDrawable(context.getResources().getDrawable(R.drawable.online));
}
}
#Override
public int getItemCount() {
return homeGetters.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textViewUsername;
CardView cardView;
TextView textViewLocation;
ImageView status;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageViewThumb);
textViewUsername = itemView.findViewById(R.id.textViewProfilUsername);
cardView = itemView.findViewById(R.id.cardViewProfil);
textViewLocation = itemView.findViewById(R.id.textViewLocation);
status = itemView.findViewById(R.id.imageViewOnlinestatus);
}
}
}
On this line I get the distance in km:
holder.textViewLocation.setText(homeGetter.getLocation());
e.g 544
Is it possible to sort the list in the adapter?
Or how can I sort this?
So, how can I achive this?
The Activity
pullData.getData(USERNAME, "1", new Pullcallback() {
#Override
public void getSingleData(String data) {
}
#Override
public void getMultipleData(String[] multipledatas) {
GENDER = multipledatas[5];
GENDERSEARCH = multipledatas[6];
GetStrangers getStrangers = new GetStrangers(Home.this);
Map<String,String> map = new HashMap<>();
map.put("USERNAME",USERNAME);
map.put("GENDER",GENDER);
map.put("SEARCH",GENDERSEARCH);
getStrangers.strangers(map, "7", new Pullcallback() {
#Override
public void getSingleData(String data) {
}
#Override
public void getMultipleData(final String[] multipledatas) {
// username,imagelink,position,birthday
// imageURL,username,birthday,location
pullData.getData(USERNAME, "2", new Pullcallback() {
#Override
public void getSingleData(String data) {
}
#Override
public void getMultipleData(String[] multipledatas2) {
String[] split1 = multipledatas2[1].split(",");
String[] split2 = multipledatas[2].split(",");
float lat1 = Float.valueOf(split1[0]);
float lng1 = Float.valueOf(split1[1]);
float lat2 = Float.valueOf(split2[0]);
float lng2 = Float.valueOf(split2[1]);
Collections.sort(getterList, new Comparator<HomeGetter>() {
public int compare(HomeGetter s1, HomeGetter s2) {
return Integer.compare(Integer.parseInt(s1.getLocation()), Integer.parseInt(s2.getLocation()));
}
});
homeGetter = new HomeGetter(multipledatas[1],multipledatas[0],multipledatas[3],String.valueOf(Math.round(Calculator.calculateDistance(lat1,lng1,lat2,lng2))),multipledatas[4]);
getterList.add(homeGetter);
homeAdapter.notifyDataSetChanged();
loading.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
}
#Override
public void onError(String errormessage) {
}
});
}
#Override
public void onError(String errormessage) {
}
});
}
#Override
public void onError(String errormessage) {
}
});
pullData.getData(USERNAME, "2", new Pullcallback() {
#Override
public void getSingleData(String data) {
}
#Override
public void getMultipleData(String[] multipledatas) {
if(multipledatas[7].equals("0")){
Intent intentFirststep = new Intent(Home.this,Firststep.class);
startActivity(intentFirststep);
finish();
}else {
}
}
#Override
public void onError(String errormessage) {
}
});
recyclerViewHome = findViewById(R.id.recyclerViewHome);
homeAdapter = new HomeAdapter(Home.this, getterList, new HomeCallback() {
#Override
public void getPosition(int position) {
Intent stranger = new Intent(Home.this,Stranger.class);
stranger.putExtra("USERNAME",getterList.get(position).getUsername());
startActivity(stranger);
finish();
}
});
recyclerViewHome.setHasFixedSize(true);
recyclerViewHome.setLayoutManager(new GridLayoutManager(Home.this,3));
recyclerViewHome.setItemAnimator(new DefaultItemAnimator());
recyclerViewHome.setAdapter(homeAdapter);
}
But it is not working correctly it shows me 4,14,507 and 12
but it shoild sort 4,12,14,507
In your activity where you are passing your ArrayList just do this before passing it.
Collections.sort(homeGetter, new Comparator<HomeGetter>() {
public int compare(HomeGetter s1, HomeGetter s2) {
return Integer.compare(Integer.parseInt(s1.getLocation()), Integer.parseInt(s2.getLocation()));
}
});
P.S. Don't use parse if you are already storing as integers.
Happy to help.
EDIT:
Put it here-
getterList.add(homeGetter);
Collections.sort(homeGetter, new Comparator<HomeGetter>() {
public int compare(HomeGetter s1, HomeGetter s2) {
return Integer.compare(Integer.parseInt(s1.getLocation()), Integer.parseInt(s2.getLocation()));
}
});
homeAdapter.notifyDataSetChanged();
You can also sort the List<HomeGetter> homegetters using a Comparator & then initialize HomeAdapter with sorted homegetters list.
An Example:
homegetters.sort((hG1, hG2) -> hG1.getLocation().compareTo(hG2.getLocation()));
Above line will sort homegetters list based on getLocation().
Edit:
In your activity, you are sorting the List first and then adding an item into it.
You should instead add all the items first & then sort the List.

Categories