I´ve got a problem with my RecyclerView. I want to update the Cards (inside the RecyclerView) after fetching the data from the server. First I thought there´s a problem with fetching or parsing the JSON-data, or sending the data via EventBus to the Fragment but when I display the parsed Objects in a TextView in the Fragment, everything is shown up. So the real problem is the RecyclerView / Adapter.
I´ve initialized the RecyclerView with an empty ArrayList, but when and HOW do I have to update the data for the RecyclerView? I´ve also read some Posts here on Stackoverflow, but I found no suitable solution...
This is the onCreateView from UserFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View mView = inflater.inflate(R.layout.fragment_users, container, false);
mRecyclerView = (RecyclerView) mView.findViewById(R.id.rv_user);
//set LayoutManager for View
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
//set Adapter for View
mAdapter = new UserAdapter(userList);
mRecyclerView.setAdapter(mAdapter);
Log.d(TAG, "onCreateView");
return mView;
}
and this is my UserAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
public static final String TAG = "UserAdapter";
private ArrayList<User> mUser;
public UserAdapter(ArrayList<User> user) {
mUser = user;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public CardView cv;
public TextView user_name;
public TextView user_lastName;
public TextView user_city;
public ViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.rv_user);
user_name = (TextView) itemView.findViewById(R.id.tv_user_name);
user_lastName = (TextView) itemView.findViewById(R.id.tv_user_lastname);
user_city = (TextView) itemView.findViewById(R.id.tv_user_city);
Log.d(TAG, "Viewholder");
}
}
//initialize Viewholder
#Override
public UserAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout_person, viewGroup, false);
Log.d(TAG, "onCreateViewHolder");
return new ViewHolder(mView);
}
//Bind data to view
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.user_name.setText(mUser.get(position).getUser().getFirstname());
holder.user_lastName.setText(mUser.get(position).getUser().getLastname());
holder.user_city.setText(mUser.get(position).getUser().getCity());
Log.d(TAG, "onBindViewHolder");
}
public void setUserList(ArrayList<User> user){
this.mUser = user;
notifyItemRangeChanged(0, user.size());
notifyDataSetChanged();
}
public void updateData(ArrayList<User> userList) {
mUser.clear();
mUser.addAll(userList);
notifyDataSetChanged();
}
public void removeItem(int position) {
mUser.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount");
if (mUser == null) {
return 0;
} else {
return mUser.size();
}
} }
This is the onResponse in the MainActivity:
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseStr = response.body().string();
Gson gson = new Gson();
Type userListType = new TypeToken<ArrayList<User>>() {
}.getType();
final ArrayList<User> userList = gson.fromJson(responseStr, userListType);
CustomMessageEvent event = new CustomMessageEvent();
event.setUserList(userList);
EventBus.getDefault().post(event);
System.out.print(responseStr);
response.body().close();
}
}
UPDATE
XML-File (CardView)
<android.support.v7.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:id="#+id/rv_user"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_margin="3dp"
android:elevation="11dp"
android:foregroundGravity="center_horizontal"
android:scrollbars="vertical"
android:theme="#style/AppThemeFSF"
app:cardBackgroundColor="#color/cardview_light_background"
app:cardCornerRadius="4dp"
app:cardElevation="4dp"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatImageView
android:id="#+id/iv_profile_picture"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center_vertical"
android:layout_marginBottom="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Name"/>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Nachname"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Stadt"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_user_name"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Name"
android:textAppearance="?android:textAppearanceLarge"
android:textSize="14sp"/>
<TextView
android:id="#+id/tv_user_lastname"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Nachname"
android:textAppearance="?android:textAppearanceLarge"
android:textSize="14sp"/>
<TextView
android:id="#+id/tv_user_city"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Stadt"
android:textAppearance="?android:textAppearanceLarge"
android:textSize="14sp"
/>
</LinearLayout>
</LinearLayout>
Thanks in advance guys, have a great day!
The problem is that you are not subscribing to receive you event back. So, when you call:
EventBus.getDefault().post(event);
No one is getting the event! And you are not populating you list. So your adapter has nothing to show.
Subscribe for the event like this:
#Subscribe
public void receiveEvent(CustomMessageEvent event){
mAdapter.updateData(event.getUserList())
}
This method should be in your fragments. If you put this inside your adapter you are going to violate the single responsibility principle. The only responsibility that your adapter should have is to link the list to the RecyclerView.
Happy coding!
Ok guys... I´ve got the solution! And this drives me a bit crazy... The problem was not the Adapter or the ViewHolder or anything inside the Fragment. The "real" problem was the text-size from the TextView inside the CardView-Elements. I deleted this properties and now every single dataset is available!
Thank you so much for your help and your tips! You´re great!
HAPPY coding ;)
Related
I understand this might be a duplicate, but every other solution here didn't work in my case, such as changing the layout_height to wrap_content instead of match_parent.
My Firestore database has 2 values stored inside an array, and I want to display both of them (more in the future) in my RecyclerView, however, it only displays the first value, at position 0.
Here is my Activity where the Recycler and the Adapter are created:
ActivityOs
private FirestoreAdapter listAdapter;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference osRef = db.collection("cliente");
private DocumentReference docRef = osRef.document("clienteTeste");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_os);
RecyclerView recyclerView = findViewById(R.id.recyclerViewOs);
/*docRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.e("RESULTADO","result:" + document.toString());
}
}
});*/
Query query = osRef.orderBy("serviceOrder",
Query.Direction.ASCENDING);
FirestoreRecyclerOptions<ServiceDocument> options =
new FirestoreRecyclerOptions.Builder<ServiceDocument>()
.setQuery(osRef, ServiceDocument.class)
.build();
listAdapter = new FirestoreAdapter(options);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
#Override
protected void onStart() {
super.onStart();
listAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
listAdapter.stopListening();
}
The commented code shows me that the database does indeed return the 2 values stored in it.
Here is my Adapter class:
public class FirestoreAdapter extends FirestoreRecyclerAdapter<ServiceDocument, FirestoreAdapter.ViewHolder> {
public FirestoreAdapter(#NonNull FirestoreRecyclerOptions<ServiceDocument> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull ServiceDocument model) {
holder.osIdItem.setText(String.valueOf(model.serviceOrderArray.get(position).getId()));
holder.osClientItem.setText(model.serviceOrderArray.get(position).getClient().getName());
holder.osDateItem.setText(model.serviceOrderArray.get(position).getDate());
holder.osValueItem.setText(String.valueOf(model.serviceOrderArray.get(position).getTotalValue()));
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.layout_os_item, parent, false);
return new FirestoreAdapter.ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView osIdItem;
private TextView osClientItem;
private TextView osDateItem;
private TextView osValueItem;
public ViewHolder(View itemView) {
super(itemView);
osIdItem = itemView.findViewById(R.id.osIDItem);
osClientItem = itemView.findViewById(R.id.osClientNameItem);
osDateItem = itemView.findViewById(R.id.osDateItem);
osValueItem = itemView.findViewById(R.id.osValueItem);
}
}
}
And here are my layouts, activity_os.xml where my RecyclerView is created, and layout_os_item.xml where the layouts for each item of the recycler are made.
Activity_os.xml
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/activity_os"
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="wrap_content"
android:layout_marginBottom="0dp"
android:background="#color/white"
tools:context="com.leonardomaito.autocommobile.activities.OsActivity">
<include
android:id="#+id/include"
layout="#layout/layout_header_search" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/glRecyclerLimit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="124dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewOs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="650dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/glRecyclerLimit"
app:layout_constraintVertical_bias="0.0"
tools:listitem="#layout/layout_os_item" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btNewOs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Inserir OS"
android:onClick="createNewOs"
android:src="#drawable/custom_plus_icon"
app:backgroundTint="#color/autocom_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.98"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/glRecyclerLimit"
app:layout_constraintVertical_bias="0.988"
app:rippleColor="#color/autocom_blue" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout_os_item.xml
<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="wrap_content"
tools:showIn="#layout/activity_os"
android:background="#drawable/custom_card_view">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="10dp"
android:background="#drawable/custom_card_view">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/custom_os_icon"
android:paddingLeft="5dp"/>
<TextView
android:id="#+id/osIDItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="N 00000"
android:textColor="#color/autocom_blue"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="#+id/osDateItem"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/osDateItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/autocom_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.943"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.222" />
<TextView
android:id="#+id/osClientNameItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:textColor="#color/autocom_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/osIDItem"
app:layout_constraintVertical_bias="0.111" />
<TextView
android:id="#+id/osValueItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:text="R$ 10,000"
android:textColor="#color/autocom_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.791"
app:layout_constraintStart_toEndOf="#+id/osClientNameItem"
app:layout_constraintTop_toBottomOf="#+id/osDateItem"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Any help is welcome!
Edit
Current Result:
Expected Result
Basically, Item 0 or the first item is correct, however, the second item in my database should also appear in Item 1.
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 am new to using Java and Android Studio and I'm stumped. I have created an application with bottom navigation and that functions fine. I'm trying to use a floating action button to create list entries into a ListView. I've created an adapter for the ListView and an XML for it but when I actually click on the tab, nothing shows up. I think the issue may lie in using onCreate vs. onCreateView, but since I'm new I'm not really sure what I should put where. As my code stands, the fragment loads with nothing showing except for the title of the fragment. I stopped using onCreateView and put everything under onCreate because my fragment was crashing. Any help would be appreciated.
Fragment Java:
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
private FragmentDashboardBinding binding;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView ListView;
EditText editText;
public String test;
public void onCreate(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText = (EditText) getView().findViewById(R.id.editText);
listItems = new ArrayList<String>();
listItems.add("Let's see where this ends up");
ListView = (ListView) getView().findViewById(R.id.ListView);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listItems);
ListView.setAdapter(adapter);
binding.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fab:
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
}
}
}
);
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT)
.show();
}
});
dashboardViewModel = new ViewModelProvider(this).get(DashboardViewModel.class);
binding = FragmentDashboardBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textDashboard;
dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}}
Fragment XML:
<TextView
android:id="#+id/textview_first8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginStart="153dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="154dp"
android:text="#string/title_dashboard"
android:textColor="#color/teal_font"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="invisible"/>
<ListView
android:id="#+id/ListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="#+id/textview_first8"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/text_dashboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="invisible"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginEnd="32dp"
android:layout_marginBottom="88dp"
android:clickable="true"
android:src="#android:drawable/ic_menu_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
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