I am making a app in which a activity shows some blog post data in card view. Everything Works Fine until if i have only 9 blog posts to show but when tenth post added then card-view gets messed up like 10 post shows both in 1st cardview item and in last cardview item.
below is the code to fill the Recyclerview Cardview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction);
LinearLayoutManager lm = new LinearLayoutManager(this);
lm.setReverseLayout(true);
lm.setStackFromEnd(true);
recyclerView = findViewById(R.id.blog_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(lm);
mref = FirebaseDatabase.getInstance().getReference().child("IHIAUPDATES");
}
public static class bloglistviewholder extends RecyclerView.ViewHolder {
static View mview;
public bloglistviewholder(View itemView) {
super(itemView);
mview = itemView;
}
public static void setTitle(String title){
TextView post_title = mview.findViewById(R.id.blog_title);
post_title.setText(title);
}
public static void setPosteon(String postedon){
TextView post_title = mview.findViewById(R.id.blog_postedon);
post_title.setText(postedon);
}
public static void setPostby(String postedby){
TextView post_title = mview.findViewById(R.id.blog_postedby);
post_title.setText(postedby);
}
public static void setPost(String post){
TextView post_content = mview.findViewById(R.id.blog_post);
post_content.setText(post);
}
public static void setImageurl(Context ctx, String imageurl){
ImageView post_image = mview.findViewById(R.id.blog_pic);
Picasso.with(ctx).load(imageurl).into(post_image)
;
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<blog_list,bloglistviewholder> rAdapter = new FirebaseRecyclerAdapter<blog_list, bloglistviewholder>(
blog_list.class,
R.layout.blog_row,
bloglistviewholder.class,
mref.orderByKey()
) {
#Override
protected void populateViewHolder(bloglistviewholder viewHolder, blog_list model, int position) {
bloglistviewholder.setTitle(model.getTitle());
bloglistviewholder.setPost(model.getPost());
bloglistviewholder.setPostby(model.getPostedby());
bloglistviewholder.setPosteon(model.getPostedon());
bloglistviewholder.setImageurl(getApplicationContext(),model.getImageurl());
}
};
recyclerView.setAdapter(rAdapter);
}
Xml blog_row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/blog_pic"
android:layout_width="120dp"
android:layout_height="90dp"
android:padding="4dp" />
<TextView
android:id="#+id/blog_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/blog_pic"
android:text="Apple MacBook Air Core i5 5th Gen - (8 GB/128 GB SSD/Mac OS Sierra)"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/blog_postedon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/blog_title"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/blog_pic"
android:text="13.3 Inch, 256 GB"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small" />
<TextView
android:id="#+id/blog_postedby"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/blog_postedon"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/blog_pic"
android:background="#color/colorPrimary"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="4.7"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/blog_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/blog_postedby"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/blog_pic"
android:text="INR 56990"
android:textAppearance="#style/TextAppearance.AppCompat" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
what could be wrong?
am i doing something wrong?
what could be wrong?
You have a logic problem where you insert your data into the database, causing the same first item to show up as the 10th item. However, since you haven't shown the code, it's impossible to guess beyond that.
What have you done to debug your code?
am i doing something wrong?
Well, you have a bug ... so ... yes? :P
Related
Please help Me,
I am trying to create a specific type of recycler view which can have always 3 items in all kind of mobile phone. Whether that mobile is having 4 inch display or 6.5 inch display.
Please tell me if that is possible or not.
my code of xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:id="#+id/recomended"
android:layout_margin="6dp"
android:background="#drawable/graycurverdbtn"
android:layout_height="170dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="85dp"
android:scaleType="fitCenter"
android:src="#drawable/mountain">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:gravity="center"
>
<TextView
android:id="#+id/pinkbtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/pinkcurvedbtn"
android:gravity="center"
android:padding="3dp"
android:text="Recomended"
android:textColor="#color/white"
android:textSize="9dp">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_below="#id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="8dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="normal"
android:layout_margin="6dp"
android:layout_gravity="center"
android:textSize="10sp"
android:textColor="#color/black"
android:text="Pest control">
</TextView>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey"></View>
<TextView
android:layout_margin="8dp"
android:id="#+id/shopname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textStyle="bold"
android:textColor="#color/black"
android:text="K02BgbhdAf">
</TextView>
<TextView
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/graylocation"
android:text="Airport Road"
android:id="#+id/address"
android:textSize="18sp"
android:textStyle="normal">
</TextView>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
This is my Adapter code
public class OurrecomendedAdapter extends RecyclerView.Adapter<OurrecomendedAdapter.MyViewHolder> {
private List<HomeResponse.Recommend> ourrecomendedlist = new ArrayList<>();
private Context context;
public static int recomendedid=0;
public OurrecomendedAdapter(List<HomeResponse.Recommend> list, Context context) {
this.ourrecomendedlist = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recomemdedservices_item, parent, false);
// itemView.setLayoutParams(new ViewGroup.LayoutParams((int) (parent.getWidth() * 0.3),ViewGroup.LayoutParams.MATCH_PARENT));
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.title.setText(ourrecomendedlist.get(position).getCategory().getSlug());
holder.shopname.setText(ourrecomendedlist.get(position).getCategory().getName());
Picasso.get().load(ourrecomendedlist.get(position).getImage()).into(holder.image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
}
});
holder.recomended.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ourrecomendedlist.get(position).getCategory().getName().toString().equalsIgnoreCase("salon for women") || ourrecomendedlist.get(position).getCategory().getName().toString().equalsIgnoreCase("salon for men")){
AppCompatActivity activity = (AppCompatActivity) context;
WomensalonlistFragment subc = new WomensalonlistFragment();
Bundle args = new Bundle();
args.putString("id", ourrecomendedlist.get(position).getProductcategoryId().toString());
args.putString("title", ourrecomendedlist.get(position).getName());
subc.setArguments(args);
activity.getSupportFragmentManager().beginTransaction().addToBackStack(null).
replace(R.id.nav_host_fragment, subc).commit();
}
else
{
typeListid= ourrecomendedlist.get(position).getId().toString();
Intent intent= new Intent(context, ProductdetailsActivity.class);
intent.putExtra("productId",typeListid);
context.startActivity(intent);
HomeFragment.vendormainid=ourrecomendedlist.get(position).getId().toString();
}
}
});
}
#Override
public int getItemCount() {
return this.ourrecomendedlist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name,title,shopname,address,pinkbtn;
Button addtocart;
ImageView image;
RelativeLayout recomended;
MyViewHolder(View itemView) {
super(itemView);
addtocart=itemView.findViewById(R.id.addtocart);
image=itemView.findViewById(R.id.image);
title=itemView.findViewById(R.id.title);
shopname=itemView.findViewById(R.id.shopname);
address=itemView.findViewById(R.id.address);
recomended=itemView.findViewById(R.id.recomended);
name=itemView.findViewById(R.id.name);
pinkbtn=itemView.findViewById(R.id.pinkbtn);
}
}
}
in this i need to display our output as 3 items in each aspect-ratio mobile.
but I'm unable to achieve that. If I'm opening in big screen mobile then it's showing 3.5 items and in small device some times it's showing 2.75 items.
Kindly help me in that how to achieve that exact output.
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}
I've set the visibility of RecyclerView to gone. How would I be able to remove the empty space it takes?
I tried putting layout_height as wrap_content, but it still doesn't show anything.
Recycler View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Card View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:id="#+id/cardView"
android:backgroundTint="#5A10E7"
android:elevation="90dp"
android:orientation="vertical"
android:textColor="#FFFFFF"
app:cardCornerRadius="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.282">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/Requestfulfilled"
android:layout_width="139dp"
android:layout_height="41dp"
android:layout_weight="1"
android:backgroundTint="#4CAF50"
android:clickable="true"
android:defaultFocusHighlightEnabled="true"
android:hint="Request Fullfilled"
android:text="Fulfilled"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/DeleteRequest"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="#+id/RlocationView"
app:layout_constraintTop_toBottomOf="#+id/RlocationView" />
<Button
android:id="#+id/DeleteRequest"
android:layout_width="139dp"
android:layout_height="41dp"
android:backgroundTint="#F44336"
android:clickable="true"
android:defaultFocusHighlightEnabled="true"
android:hint="Delete"
android:text="Delete"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/RlocationView"
app:layout_constraintHorizontal_bias="0.894"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.904" />
<TextView
android:id="#+id/RemailView"
android:layout_width="340dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Email"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RdateView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/RbloodView"
android:layout_width="116dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Blood Group"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RlocationView"
app:layout_constraintEnd_toStartOf="#+id/RdateView"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RemailView" />
<TextView
android:id="#+id/RdateView"
android:layout_width="164dp"
android:layout_height="42dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Date of Requirement"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RlocationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/RbloodView"
app:layout_constraintTop_toBottomOf="#+id/RemailView" />
<TextView
android:id="#+id/RlocationView"
android:layout_width="340dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Location"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/Requestfulfilled"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RdateView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Code to set Card visibility as GONE:
public class yourRequestActivity extends AppCompatActivity {
private RecyclerView cardView;
private DatabaseReference dbRefForReq, dbRefForResp;
private FirebaseAuth mAuth;
private String AuthUserEmail, UserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request_response_view);
mAuth = FirebaseAuth.getInstance();
AuthUserEmail = mAuth.getCurrentUser().getEmail();
UserID = mAuth.getCurrentUser().getUid();
dbRefForResp = FirebaseDatabase.getInstance().getReference().child("Responses").child(String.valueOf(UserID));
dbRefForReq = FirebaseDatabase.getInstance().getReference().child("Blood Requests");
dbRefForReq.keepSynced(true);
cardView = (RecyclerView) findViewById(R.id.recycleView);
cardView.setHasFixedSize(true);
cardView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<getDbContents> options =
new FirebaseRecyclerOptions.Builder<getDbContents>()
.setQuery(dbRefForReq, getDbContents.class)
.build();
FirebaseRecyclerAdapter<getDbContents, contentHolder> adapter = new FirebaseRecyclerAdapter<getDbContents, contentHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final contentHolder holder, final int position, #NonNull final getDbContents model) {
final int finalPosition = position + 1;
if (model.getUser().equals(AuthUserEmail)) {
dbRefForReq.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot checkFulfillment = dataSnapshot.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment");
if (checkFulfillment.exists()) {
if (checkFulfillment.child("Fulfilled").getValue().equals("yes")) {
/*------------- Set current user card as visible -----------------*/
holder.frameView.setVisibility(View.VISIBLE);
holder.fulfilled.setVisibility(View.GONE);
holder.requestFulfilled.setVisibility(View.VISIBLE);
holder.userEmail.setText(AuthUserEmail);
holder.bloodGroup.setText(model.getBloodGroup());
holder.dateOfRequirement.setText(model.getDate());
holder.Location.setText(model.getLocation());
////////////////////////////////////////////////////////////////////
}
} else {
holder.frameView.setVisibility(View.VISIBLE);
holder.fulfilled.setVisibility(View.VISIBLE);
holder.requestFulfilled.setVisibility(View.GONE);
/*------------- Set current user card as visible -----------------*/
holder.userEmail.setText(AuthUserEmail);
holder.bloodGroup.setText(model.getBloodGroup());
holder.dateOfRequirement.setText(model.getDate());
holder.Location.setText(model.getLocation());
////////////////////////////////////////////////////////////////////
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else if (model.getUser().equals(null)) {
holder.userEmail.setText("You have not posted any request");
} else {
holder.frameView.setVisibility(View.GONE);
}
/* Fulfilled and Delete button Functionality */
holder.fulfilled.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map<String, Object> response = new HashMap<>();
response.put("Fulfilled", "yes");
/*-----------------Remove Responses------------------*/
dbRefForResp.removeValue();
///////////////////////////////////////////////////////
/*-----------------Update and insert child with fulfilled status as yes------------------*/
dbRefForReq.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment").setValue(response).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(yourRequestActivity.this, "Request fulfillment status posted", Toast.LENGTH_SHORT).show();
}
});
////////////////////////////////////////////////////////////////////
holder.fulfilled.setVisibility(View.GONE);
holder.requestFulfilled.setVisibility(View.VISIBLE);
}
});
}
#NonNull
#Override
public contentHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.your_request_card, viewGroup, false);
contentHolder contentViewHolder = new contentHolder(view);
return contentViewHolder;
}
};
cardView.setAdapter(adapter);
adapter.startListening();
}
public class contentHolder extends RecyclerView.ViewHolder {
TextView userEmail, bloodGroup, dateOfRequirement, Location, requestFulfilled;
Button fulfilled;
FrameLayout frameView;
public contentHolder(#NonNull View itemView) {
super(itemView);
userEmail = itemView.findViewById(R.id.RemailView);
bloodGroup = itemView.findViewById(R.id.RbloodView);
dateOfRequirement = itemView.findViewById(R.id.RdateView);
Location = itemView.findViewById(R.id.RlocationView);
requestFulfilled = (TextView) itemView.findViewById(R.id.fulfilledTextMessage);
frameView = (FrameLayout) itemView.findViewById(R.id.cardFrame);
fulfilled = (Button) itemView.findViewById(R.id.Requestfulfilled);
}
}
}
I want to remove the blank space which occurs while visibility is set to GONE, as shown in the snapshot below.
Image of empty space on removing top card
Image before setting visibility GONE
Simply remove the object from the list if its user is not equal to AuthUserEmail and notify your adapter.
NO NEED TO MAKE VISBILITY GONE OF THE HOLDER VIEW
Your RecyclerView takes space even if visibility is set to gone. It still takes space because there are items that RecyclerView wants to display. Although you can fix this by removing the items RecyclerView wants to show. It would take a lot of memory if you want show that RecyclerView again because you still have to add the items back. What I would recommend is to wrap your RecyclerView with a layout eg. LinearLayout and set that layout's visibility to gone.
Try doing this:
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Place your RecyclerView here -->
<!-- change visibility of container view -->
</LinearLayout>
*Edit: You didn't explain it well. I get what you want now. You simply have to remove the item from your RecyclerView list. The best way to do this is by using DiffUtil. This a great tutorial online showing how you can implement it in Java. https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction
Cover your RecyclerView with a FrameLayout and then set your visibility over there.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
If this doesnt works then:
Cover your Cardview which is the layout that you designed for your Recyclerview with a FrameLayout. Anyone of them will surely work out for you.
I have an adapter class which loads items dynamically and shows them in a RecyclerView. My problem is that when I swipe up and down the recycler view the images get mixed and are shown in wrong positions (i.e. in other item's view).
For example, I have an item X and another item Y. Now when I swipe up and down the image which was to be shown in item Y get shown in item X and the same happens with other attributes.
Here is my adapter class:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private DatabaseReference refDNewsTable= FirebaseDatabase.getInstance().getReference().child("news_feeds");
private StorageReference refStorage = FirebaseStorage.getInstance().getReferenceFromUrl("firebase_url_comes_here");
private Context mContext;
private List<NewsModel> newsList;
public class NewsViewHolder extends RecyclerView.ViewHolder {
public TextView nHeading, nDes,nDaTi;
public ImageView nImg;
public NewsViewHolder(View view) {
super(view);
nHeading = (TextView) view.findViewById(R.id.tv_newsHeadline);
nDes = (TextView) view.findViewById(R.id.tv_nDes);
nImg = (ImageView) view.findViewById(R.id.iv_nImg);
nDaTi=(TextView) view.findViewById(R.id.tv_nDaTi);
}
}
public NewsAdapter(Context mContext, List<NewsModel> newsList) {
this.mContext = mContext;
this.newsList = newsList;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_model, parent, false);
return new NewsViewHolder(itemView);
}
#Override
public void onBindViewHolder(final NewsViewHolder holder, int position) {
NewsModel news = newsList.get(position);
holder.nHeading.setText(news.getnHeading());
if(news.hasDes()) {
holder.nDes.setText(news.getnDes());
}else{
holder.nDes.setVisibility(View.GONE);
}
if(news.hasImg()){
// Reference to an image file in Firebase Storage
StorageReference imgReference =refStorage.child(news.getnId());
// Load the image using Glide
Glide.with(mContext)
.using(new FirebaseImageLoader())
.load(imgReference)
.into(holder.nImg);
}else{
holder.nImg.setVisibility(View.GONE);
}
holder.nDaTi.setText(news.getnDaTi());
}
public void downloadFile(final NewsViewHolder holder){
try {
final File localFile = File.createTempFile("images", "jpg");
refStorage.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
holder.nImg.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {}
}
#Override
public int getItemCount() {
return newsList.size();
}
}
And this is my news_model.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_margin="4dp"
card_view:cardPreventCornerOverlap="true"
card_view:cardElevation="16dp"
android:layout_height="wrap_content"
android:id="#+id/card_view"
android:layout_gravity="center"
card_view:cardCornerRadius="0dp">
<LinearLayout
android:orientation="vertical"
android:background="#color/cBgNews"
android:padding="0dp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:padding="10dp"
card_view:cardElevation="6dp"
card_view:cardBackgroundColor="#color/cNewsHeadline"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="0dp"
android:id="#+id/card_des"
android:layout_gravity="center"
card_view:cardCornerRadius="0dp">
<TextView
android:text="TextView"
android:textSize="17sp"
android:textStyle="normal"
android:padding="10dp"
android:maxLines="3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/cWhite"
android:gravity="start"
android:layout_margin="0dp"
android:id="#+id/tv_newsHeadline" />
</android.support.v7.widget.CardView>
<LinearLayout
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#0000"
android:paddingEnd="6dp"
android:paddingStart="6dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_marginBottom="0dp"
android:layout_height="wrap_content"
android:maxHeight="300dp"
app:srcCompat="#mipmap/ic_launcher"
android:scaleType="fitCenter"
android:layout_gravity="center_horizontal"
android:id="#+id/iv_nImg" />
<TextView
android:text="Description..."
android:maxLines="8"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:padding="10dp"
android:textColor="#color/cBlack"
android:id="#+id/tv_nDes" />
<TextView
android:text="Date and Time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10sp"
android:textColor="#999999"
android:gravity="end"
android:id="#+id/tv_nDaTi" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
NOTE: I am using firebase to receive the content directly and haven't created any kind of database in my app yet. i.e. it loads data every time it needs it directly in adapter class.
I have very popular question - why the data not showing in the RecycleView.
That is my Adapter:
public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder> {
private static final String TAG = "CommentsAdapter";
public ImageView mThumbView;
private List<PostComment> postCommentList;
public CommentsAdapter(List<PostComment> postCommentList) {
this.postCommentList = postCommentList;
}
#Override
public CommentsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_comment_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(CommentsAdapter.ViewHolder holder, int position) {
PostComment record = postCommentList.get(position);
holder.mAuthorTextView.setText(record.getUser().getFull_name());
holder.mDateTextView.setText(record.getCreated_at());
holder.mTextTextView.setText(record.getText());
}
#Override
public int getItemCount() {
Log.i(TAG + " comments size", Integer.toString(postCommentList.size()));
return postCommentList.size();
}
public void addItems(List<PostComment> postCommentList) {
this.postCommentList.addAll(postCommentList);
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mAuthorTextView;
public TextView mDateTextView;
public TextView mTextTextView;
public ViewHolder(View v) {
super(v);
mAuthorTextView = (TextView) itemView.findViewById(R.id.comment_author);
mDateTextView = (TextView) itemView.findViewById(R.id.comment_date);
mTextTextView = (TextView) itemView.findViewById(R.id.comment_text);
}
}
}
That is my view:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
....>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp">
<ImageView
android:id="#+id/comment_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="centerInside"
android:src="#drawable/cat"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/middleLayout"
android:layout_toRightOf="#+id/comment_image"
android:layout_marginTop="8dp">
<TextView
android:id="#+id/comment_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:singleLine="true"
android:text="Dark Plastic"
android:textColor="?attr/colorPrimary"
android:textSize="14dp" />
<TextView
android:id="#+id/comment_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="8dp"
android:layout_toRightOf="#+id/comment_author"
android:text="21 minutes"
android:textSize="14dp" />
</RelativeLayout>
<TextView
android:id="#+id/comment_text"
android:layout_width="wrap_content"
android:layout_toRightOf="#+id/comment_image"
android:layout_height="wrap_content"
android:maxLines="3"
android:layout_marginTop="8dp"
android:layout_below="#id/middleLayout"
android:text="sd"
android:textColor="#android:color/black"
android:textSize="16dp" />
</RelativeLayout>
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_gravity="bottom"
android:paddingLeft="16dp"
android:paddingRight="16dp"></View>
That is how I set up the adapter:
mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
post_details_comments_list.setLayoutManager(mLayoutManager);
mCommentListAdapter = new CommentsAdapter(new ArrayList<PostComment>());
post_details_comments_list.setAdapter(mCommentListAdapter);
After I set up the adapter, I the getItemCount returns the quantity of the items - so that is not null.
RecycleView layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.gms.maps.MapView
android:id="#+id/post_details_mapview"
android:layout_width="wrap_content"
android:layout_height="200dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/post_details_comments_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/TextLabelStyle"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/post_details_comments_list"
android:layout_width="match_parent"
android:scrollbars="vertical"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/edit_comment"
android:hint="#string/hint_type_comment"/>
</LinearLayout>
I make the request to the server and here is the callback, where I get the results and set up the adapter:
#Override
public void onAllPostCommentsCallback(AllComments allComments) {
Log.i(TAG + " I've the comments", allComments.getPostCommentList().toString());
mCommentListAdapter.addItems(allComments.getPostCommentList());
post_details_comments_list.setAdapter(mCommentListAdapter);
mCommentListAdapter.notifyDataSetChanged();
}
But the list is not displaying.
What can be the reason?
put null inplace of parent in View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_comment_item, parent, false);
I've already solved the issue. The problem was that I had RecycleView inside the NestedScrollView
Answer in this post helped me a lot:
How to use RecyclerView inside NestedScrollView?