How to display ListItem in Fragment - java

I want to create Fragment with ListView, so, I have a ListView with listitem in my Fragment activity, but my listitem is not displayed when i open my fragment, i need help with it, how display items in fragment? When i make this ListView in Activity, all is working well, how fix this? My code here:
FollowFragment.java
public class FollowFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
getActivity().setTitle("Подписки");
return inflater.inflate(R.layout.fragment_follow,container,false);
}
}
follow_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/item_follow"/>
</FrameLayout>
item_follow.xml
<?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="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/favourite_match_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="8dp">
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/team_1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="#font/roboto_medium"
android:text="FC Chelsea"
android:textColor="#color/black"
tools:ignore="MissingConstraints" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/team_2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_medium"
android:text="Manchester City"
app:layout_constraintTop_toBottomOf="#+id/team_1"
android:textColor="#color/black"
tools:ignore="MissingConstraints" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/match_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="#font/roboto"
android:text="25 сентября 2021 года"
android:textColor="#color/colorGrey"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="#id/team_2"
tools:ignore="MissingConstraints" />
<ImageButton
android:layout_width="48dp"
android:layout_height="50dp"
android:layout_marginEnd="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:src="#drawable/ic_love"
android:background="#00000000"
app:layout_constraintLeft_toRightOf="#id/team_2"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

well that's because you didn't assign an adapter with the correct data to it yet.
your adapter should extend ArrayAdapter and override getView in which you should set your view with the correct content based on your data.
what an adapter might look like :
public class MyAdapter extends ArrayAdapter<YourDataCustomClassHere> {
ArrayList<YourDataClassHere> data;
Context context ;
public MyAdapter(#NonNull Context context, int resource, #NonNull ArrayList<YourDataCustomClassHere> objects) {
super(context, resource, objects);
this.data = objects;
this.context = context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
convertView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_follow, parent, false);
}
//example on setting one of your fields
((AppCompatTextView) convertView.findViewById(android.R.id.team_1))
.setText(data.get(position).getText());
//set Other Fields here
return convertView;
}
}
where your data class should be a custom class that holds the correct information for each item in the list and getText in data.get(position).getText() is an arbitary method I assumed that will be in your custom class to get some sort of text but you're free to replace it with what you want.
then in your onCreateView you should set the adapter to your ListView like that :
public class FollowFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
getActivity().setTitle("Подписки");
View rootView= inflater.inflate(R.layout.fragment_follow,container,false);
ListView list = rootView.findViewById(R.id.listview);
MyAdapter myadapter = new MyAdapter(getContext(),R.layout.item_follow,YourDataArrayListHere);
list.setAdapter(myadapter);
return rootView;
}
}
I trust that you'll find your way and replace YourDataArrayListHere with the correct ArrayList of your data custom class.
anyway I hope you reconsider your choice of ListView as it consume much Ram (Memory) during runtime and use a RecyclerView instead

Related

Getting 250+ items but Custom Listview not displaying anything

I just created a list view with a custom view to create a country list for select
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/primary_light"
android:orientation="vertical"
tools:context=".RnActivity.RnView.RnUser.ActivitySignUpOptions">
<ListView
android:id="#+id/country_list_for_select_list_area"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/primary"
/>
</LinearLayout>
custom view
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/view_layout_country_list_item_country_icon_image"
android:layout_width="50dp"
android:layout_height="match_parent"
android:src="#drawable/gjh_logo_b"
/>
<TextView
android:id="#+id/view_layout_country_list_item_country_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="start|center_vertical"
android:layout_weight="1"
android:text="India"
android:textSize="18sp" />
<TextView
android:id="#+id/view_layout_country_list_item_country_code"
android:layout_width="50dp"
android:layout_height="match_parent"
android:gravity="center|center_vertical"
android:layout_gravity="right"
android:text="IN"
android:textSize="18sp"
/>
</LinearLayout>
In Activity
ListView country_list_for_select_list_area;
#Override
public void lodeControls() {
country_list_for_select_list_area=findViewById(R.id.country_list_for_select_list_area);
}
#Override
public void setEvents() {
}
RxAdopterCountry countryAdopter;
#Override
public void createAdopters() {
countryAdopter=new RxAdopterCountry(getActivity(),R.layout.view_layout_country_list_item, RsXtraCountryList.getInstance().getCountryList());
}
#Override
public void setData() {
country_list_for_select_list_area.setAdapter(countryAdopter);
}
In Adopter
private final ArrayList<RentCountry> countryList;
private Context context;
public RxAdopterCountry(#NonNull Context context, int resource, ArrayList<RentCountry> countryList) {
super(context, resource);
this.context=context;
this.countryList=countryList;
}
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if(convertView==null){
convertView= LayoutInflater.from(context).inflate(R.layout.view_layout_country_list_item, parent, false);
}
ImageView view_layout_country_list_item_country_icon_image=convertView.findViewById(R.id.view_layout_country_list_item_country_icon_image);
TextView view_layout_country_list_item_country_name=convertView.findViewById(R.id.view_layout_country_list_item_country_name);
TextView view_layout_country_list_item_country_code=convertView.findViewById(R.id.view_layout_country_list_item_country_code);
view_layout_country_list_item_country_name.setText(countryList.get(position).getName());
view_layout_country_list_item_country_code.setText(countryList.get(position).getCode());
view_layout_country_list_item_country_icon_image.setImageResource(countryList.get(position).getFlag_id());
return super.getView(position, convertView, parent);
}
i debugged the whole code and there are 250 items are coming in
private final ArrayList<RentCountry> countryList;
but list view is showing nothing
What I am doing wrong? I tried everything and debugged the whole code 10 times. yes I am getting the data in the ArrayList bu still noting is appearing in the list view.
Please help
The problem with your code is you are returning super.getView(position, convertView, parent) from getView while you should be returning the View you just created that is convertView .
For super constructor call you have to use super(context, resource, countryList) so that Adapter can return the size of list.
Change getView like below
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//...
return convertView;
}
Also you should be using RecyclerView now. ListView and GridView are legacy widgets for a long time . RecyclerView is much more flexible.

Fragment viewpager No adapter attached; skipping layout

I tried a lot of solutions but no solution has worked for me.
I am getting data from the server and showing it inside a recycleview. The data shows fine but shows this error in the logcat
Access denied finding property "persist.vendor.log.tel_dbg"
E/RecyclerView: No adapter attached; skipping layout
E/RecyclerView: No adapter attached; skipping layout
sometimes when I refresh again and again the recyclerview becomes empty.
I am using viewpager consisting of 2 fragments inside a parent fragment.
this recycleview is using in a nested scrollview
some time data not showing
Code snippet:
homebuyer_adapter_recycler=new homebuyer_adapter_recycle(getActivity(), items);
LinearLayoutManager home = new LinearLayoutManager(getActivity());
home.setOrientation(LinearLayoutManager.VERTICAL);
allitemsgrid.setLayoutManager(home);
allitemsgrid.setAdapter(r);
Here is more about
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent,
final int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.items_view,parent,
false);
RecyclerView.LayoutParams lp = new
RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(lp);
ViewHolder viewHolder = new ViewHolder(v);
HERE IS MY item view
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
app:cardCornerRadius="6dp"
android:layout_marginBottom="3dp"
app:cardBackgroundColor="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp">
<com.makeramen.roundedimageview.RoundedImageView
android:layout_width="match_parent"
android:layout_height="150dp"
app:riv_corner_radius="6dp"
android:id="#+id/image_items"
android:scaleType="fitXY"
/>
<com.makeramen.roundedimageview.RoundedImageView
android:layout_width="match_parent"
android:layout_height="150dp"
app:riv_corner_radius="6dp"
android:background="#drawable/blackshade"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/items_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/_5sdp"
android:textColor="#color/white"
android:fontFamily="sans-serif-smallcaps"
android:paddingLeft="20dp"
android:text="Message" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="Timing"
android:padding="#dimen/_5sdp"
android:textColor="#color/white"
android:layout_alignParentBottom="true"
android:fontFamily="#font/mylight"
android:layout_alignParentRight="true"
android:textSize="10dp"
android:id="#+id/shoptimming"/>
</RelativeLayout>
<TextView
android:id="#+id/name_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:alpha="0.6"
android:fontFamily="#font/arimo_bold"
android:paddingLeft="20dp"
android:text="Name"
android:textColor="#color/black"
android:textSize="17dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:orientation="horizontal">
<TextView
android:id="#+id/minumum_order"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:drawablePadding="10dp"
android:fontFamily="sans-serif"
android:paddingLeft="20dp"
android:text="Minimum " />
<TextView
android:id="#+id/price_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:fontFamily="sans-serif"
android:gravity="left"
android:paddingLeft="20dp"
android:text="charges"
/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Here is my adapter class
public class homebuyer_adapter_recycle extends RecyclerView.Adapter<homebuyer_adapter_recycle.ViewHolder> {
private ArrayList<seller_information> listData;
private LayoutInflater layoutInflater;
int lastpostition=-1;
Context context;
public homebuyer_adapter_recycle(Context aContext, ArrayList<seller_information> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
context=aContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder
(#NonNull ViewGroup parent, final
int viewType) {
View v = LayoutInflater.from(parent.getContext()).
inflate(R.layout.items_view,parent, false);
ViewHolder viewHolder = new ViewHolder(v);
Log.i("inadapter","calling time");
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
phone_number_shop = listData.get(viewType).getPhonenumber();
homebuyer.Delivery_charges_shop =
listData.get(viewType).getDiliveryfee();
homebuyer.Shop_name = listData.get(viewType).getShopname();
homebuyer.minimum_order = listData.get(viewType).getMinorder();
//profession=items.get(i).getName();
// Toast.makeText(getActivity(),phn,Toast.LENGTH_SHORT).show();
all_and_cetegory_items items = new all_and_cetegory_items();
Bundle b = new Bundle();
b.putString("phone",homebuyer.phone_number_shop);
items.setArguments(b);
FragmentTransaction fragmentTransaction =
((AppCompatActivity)context).getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, items);
fragmentTransaction.addToBackStack(null).commit();
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.name.setText(listData.get(position).getShopname());
//
Picasso.with(context).load(listData.get(position)
.getShopimage()).into(holder.shopimage);
Glide.with(context).load(listData.get(position).getShopimage())
.into(holder.shopimage);
holder.dilivery.setText("Rs "+listData.get(position).getDiliveryfee()+"
Delivery fee");
holder.minorder.setText("Rs "+listData.get(position).getMinorder()+" minimum");
holder.items.setText(listData.get(position).getShopmessage());
holder.time.setText("Service Available
"+listData.get(position).getStartingtime()+" to
"+listData.get(position).getEndingtime());
Log.i("inadapter","calling time"+listData.get(position).getShopname());
}
#Override
public int getItemCount() {
return listData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView dilivery;
TextView items;
TextView minorder;
TextView time;
ImageView shopimage;
public ViewHolder(#NonNull View v) {
super(v);
name = (TextView) v.findViewById(R.id.name_item);
dilivery = (TextView) v.findViewById(R.id.price_item);
minorder = (TextView) v.findViewById(R.id.minumum_order);
items=(TextView)v.findViewById(R.id.items_all);
time=(TextView)v.findViewById(R.id.shoptimming);
shopimage=(ImageView) v.findViewById(R.id.image_items);
}
}
}
In error it is saying that the Adapter for RecylerView is not attached. So, try to add adapter to the layout using:
recyclerView.setAdapter(categoryAdapter);
I am assuming homebuyer_adapter_recycler is your adapter.
According to that, you haven't really set your adapter as the logcat is specifying.
Add the below code instead of allitemsgrid.setAdapter(r);
allitemsgrid.setAdapter(homebuyer_adapter_recycler);
If my assumption or suggestion is wrong, it is okay. It is probably because your question is not very clear and does not provide the necessary details. Please provide more details such as the adapter class code and what is allitemsgrid, homebuyer_adapter_recycler and r.

RecyclerView: No adapter attached; skipping layout and java.lang.NullPointerException

I keep getting the error "E/RecyclerView: No adapter attached; skipping layout" when the RecyclerView list is shown. I'm getting data correctly from API but I got "void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference"
I know this question has been asked a lot before but I checked most of the questions and none has worked for me.
This is my fragment:
public class HomeFragment extends Fragment {
private View view;
private RecyclerView recyclerView;
private ArrayList<Result> arrayList;
private SwipeRefreshLayout refreshLayout;
private PostAdapter postAdapter;
private MaterialToolbar toolbar;
private SharedPreferences userPref;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.layout_home,container,false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
userPref = getContext().getApplicationContext().getSharedPreferences("user", Context.MODE_PRIVATE);
recyclerView = (RecyclerView)view.findViewById(R.id.recyclerHome);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
refreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipeHome);
toolbar =(MaterialToolbar) view.findViewById(R.id.toolbarHome);
((HomeActivity)getContext()).setSupportActionBar(toolbar);
getResults();
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getResults();
}
});
}
private void getResults() {//Working Fine}
}
My adapter:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostsHolder>{
private ArrayList<Result> list;
private Context context;
public PostAdapter(Context context, ArrayList<Result> list) {
this.list = new ArrayList<Result>(list);
this.context = context;
}
#NonNull
#Override
public PostsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_home, parent, false);
return new PostsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PostsHolder holder, int position) {
Result result = list.get(position);
holder.imgPostDate.setText(result.getDate());
}
#Override
public int getItemCount() {
return list.size();
}
public static class PostsHolder extends RecyclerView.ViewHolder{
private TextView imgPostProfile,imgPostName,imgPostDate;
private ImageButton btnPostOption;
public PostsHolder(#NonNull View itemView) {
super(itemView);
imgPostProfile =(TextView) itemView.findViewById(R.id.imgPostProfile);
imgPostName = (TextView)itemView.findViewById(R.id.imgPostName);
imgPostDate =(TextView) itemView.findViewById(R.id.imgPostDate);
btnPostOption =(ImageButton) itemView.findViewById(R.id.btnPostOption);
}
}
}
I modified my code according to the answers I found to similar questions but none of them worked.
layout_home
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.MaterialToolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbarHome"
android:elevation="1dp"
android:theme="#style/Theme.MaCoSISBottomAppBar"
app:title=""
tools:targetApi="lollipop">
<!-- <ImageView-->
<!-- android:layout_width="100dp"-->
<!-- android:layout_height="40dp"-->
<!-- android:src="#drawable/logo_dark"/>-->
</com.google.android.material.appbar.MaterialToolbar>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:id="#+id/swipeHome"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerHome"
android:layout_height="match_parent"
android:layout_width="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
layout_post
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:clickable="true"
android:focusable="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/imgPostProfile"
android:layout_width="60sp"
android:layout_height="60sp"
android:background="#drawable/shape_circle"
android:text="MC"
android:gravity="center"
android:textColor="#color/colorWhite"
android:textSize="14sp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="6dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgPostName"
android:text="BBAD1252 Social Harmony and Business Skills Development"
android:textColor="#color/colorBlack"
android:textSize="14sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgPostDate"
android:text="12 Novermber 2020"
android:textColor="#color/colorLightGrey"
android:textSize="12dp" />
</LinearLayout>
<ImageButton
android:id="#+id/btnPostOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:background="#android:color/transparent"
android:layout_gravity="center_vertical"
android:src="#drawable/ic_baseline_more_vert_24"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#color/colorLightGrey"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
In onCreateViewHolder you inflated the wrong xml. It should've been R.layout.layout_post
#NonNull
#Override
public PostsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_post, parent, false);
return new PostsHolder(view);
}
To prevent from error E/RecyclerView: No adapter attached; skipping layout, you should call recyclerView.setAdapter(adapter); inside your init(); method.
Then after you have your data you should notify the adapter in order to display your data by calling adapter.notifyDataSetChanged(); or using any other notify methods. Check this answer for other notify methods.
If your getResults() is where you're calling your recyclerview.setAdapter(), you're calling setAdapter too late. You need to make sure your adapter is set during onCreateView() so that the Recyclerview isn't being skipped while drawing the layout.
No Adapter Attached; Skipping layout:
you should setadapter in your main thread methods of fragment; then add or update data to adapter
Nullpointer at settext [at adapter]: In onCreateViewHolder you inflated the wrong xml. It should be R.layout.layout_post instead of R.layout.layout_home

How to add layout.xml to another layout.xml programmatically

I have Fragment that contain Linear layout with orientation "horizontal" (ItemViewContainer).
I'm created another layout that container imageView and textView (ItemView).
I want to add the ItemView to the ItemViewContainer programmatically a few times.
How can i do that instead of adding the ItemView with from ItemViewContainer.
ItemView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/LLTopServiceRootView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:id="#+id/CVServiceIMGHolder"
android:layout_width="50dp"
android:layout_height="50dp"
android:translationZ="5dp"
card_view:cardBackgroundColor="#color/fragment_background_color"
card_view:cardCornerRadius="100dp"
card_view:elevation="5dp">
<ImageView
android:id="#+id/IVServiceIMG"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:tint="#color/text_color"
card_view:srcCompat="#drawable/lights_icon" />
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/TVServiceName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/text_color"
android:layout_gravity="center_horizontal"
android:text="Service\nName"
android:textAlignment="center" />
</LinearLayout>
ItemViewContainer
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:orientation="vertical"
android:translationZ="5dp"
app:cardBackgroundColor="#color/fragment_background_color"
app:cardCornerRadius="5dp"
card_view:elevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
android:id="#+id/LLTopServiceContainer"
</LinearLayout>
</androidx.cardview.widget.CardView>
Fragment that contain layout with the ItemViewContainer:
public class HomeFragment extends Fragment {
private View view;
private TextView mTVPageTitle, mTVHomeNavigationTXT;
private LottieAnimationView mLAVHome;
private ButtonsManager bm;
private LinearLayout mLLTopServiceContainer;
private final String TAG = "HomeLifeCycle";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);
bm = new ButtonsManager(getContext());
initView(view);
Log.d(TAG, "onCreateView: ");
return view;
}
private void initView(View view) {
if (getActivity() != null) {
mLAVHome = getActivity().findViewById(R.id.LAVHome);
mTVPageTitle = getActivity().findViewById(R.id.TVPageTitle);
mTVHomeNavigationTXT = getActivity().findViewById(R.id.TVHome);
mLLTopServiceContainer = view.findViewById(R.id.LLTopServiceContainer);
addSelectedIconStyle();
}
}
}
I want to add the itemView 4th times
You could do it dynamically like this way : Simple Android RecyclerView example
Or adding manually:
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout= (LinearLayout) findViewById(R.id.LLTopServiceContainer);
View view = (View) inflater.inflate(R.layout.item:view_name_file, linearLayout, true);

ListView doesn't display on screen

I recently started to use ListView on Android Application and I'm not making it to display at the screen.
I saw many tutorials on how to do a custom Adapter and followed it line by line, but at the end I wasn't able to make the ListView display on my screen, I even let a fixed Text in one TextView to display at the ListView but it still didn't displayed it.
This is the constructor of my entity code:
public Classificacao(int colocacao, int time, int pontos) {
this.colocacao = colocacao;
this.time = time;
this.pontos = pontos;
}
This my Custom Adapter that extends "ArrayAdapter"
private Context context;
private ArrayList<Classificacao> classificacaoList;
ClassificacaoAdapter(Context context, ArrayList<Classificacao> classificacaoList) {
super(context, R.layout.layout_classificacao, classificacaoList);
this.context = context;
this.classificacaoList = classificacaoList;
}
#SuppressLint("SetTextI18n")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.layout_classificacao, parent, false);
}
TextView colocacao = convertView.findViewById(R.id.texto1);
colocacao.setText(Integer.toString(classificacaoList.get(position).getColocacao()));
ImageView imagem = convertView.findViewById(R.id.imagem1);
imagem.setImageResource(classificacaoList.get(position).getImagem());
TextView nome = convertView.findViewById(R.id.texto2);
nome.setText(classificacaoList.get(position).getTime());
TextView pontos = convertView.findViewById(R.id.texto3);
pontos.setText(Integer.toString(classificacaoList.get(position).getPontos()));
return convertView;
}
This the layout "activity_atividade02" that have the ListView, and some others Text views that I won't display here.
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
This is the layout "layout_classificacao" that will be filled by the adapter
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="20dp">
<TextView
android:id="#+id/texto1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:textColor="#android:color/black"
android:textSize="30sp" />
<ImageView
android:id="#+id/imagem1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_weight="1"
android:contentDescription="imagem do time"
app:srcCompat="#drawable/flamengo" />
<TextView
android:id="#+id/texto2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:textColor="#color/colorPrimary"
android:textSize="30sp" />
<TextView
android:id="#+id/texto3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:textColor="#android:color/black"
android:textSize="30sp" />
</LinearLayout>
And this is the main class "Atividade02"
that start everything
public class Atividade02 extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atividade02);
listView = findViewById(R.id.listView);
ArrayList<Classificacao> classificacaoArrayList = new ArrayList<>();
classificacaoArrayList.add(new Classificacao(1, 2,46));
classificacaoArrayList.add(new Classificacao(2, 1,42));
classificacaoArrayList.add(new Classificacao(3,0,38));
classificacaoArrayList.add(new Classificacao(4,3,35));
classificacaoArrayList.add(new Classificacao(5,5,33));
classificacaoArrayList.add(new Classificacao(6,4,33));
ArrayAdapter classificacaoAdapter = new ClassificacaoAdapter(this, classificacaoArrayList);
listView.setAdapter(classificacaoAdapter);
}
}
Resuming, the ListView isn't displaying the "ClassificacaoAdapter" and I want it to do it.
Make sure adapter has the method getItemcount() and it returns the classificacaoList.size(). It should not return 0;
Well... it was a pretty obvious problem, in the main layout activity_atividade02 there was a LinearLayout above the ListView that it's layout_height was set to match_parent and it was occupying the entire layout and not letting the ListView being displayed.
I test your code as you write and found an error here and it works normally but I comment imageView line because you don't define it in Classificacao class
an error here
TextView nome = convertView.findViewById(R.id.texto2);
nome.setText(classificacaoList.get(position).getTime());
setText() accept String only ..but you pass integer rather than String you can do that
nome.setText(""+classificacaoList.get(position).getTimee());
or use
Integer.toString( classificacaoList.get(position).getTimee() )
as you use in other lines
please add getCount() method in your ClassificacaoAdapter class, it is an override method. It will return the size of the list,if you will not override this it will return 0 as your list size.
public int getCount() {
return classificacaoList .size();
}

Categories

Resources