setText in CustomPagerAdapter - java

This is my custom ViewPager adapter. I'm trying to set a title for each page to a TextView as a function of the position of the ViewPager. Why isn't this working?
public class CustomPagerAdapter extends PagerAdapter {
private int[] image_resources = {
android.R.color.transparent,
R.drawable.image1,
};
private String[] title_resources = {
"",
"Title #1",
};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomPagerAdapter(Context ctx) {
this.ctx = ctx;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return (view == (RelativeLayout) o);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageview = (ImageView) item_view.findViewById(R.id.image_view);
imageview.setImageResource(image_resources[position]);
TextView title = (TextView) item_view.findViewById(R.id.title_view);
title.setText(title_resources[position]);
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout) object);
}
}
I keep getting the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.app.feed.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:114)
The error is definitely being thrown at the following line: title.setText(title_resources[position]);

Nevermind. I got it working by adding the TextView to the pager_item.xml as correctly hinted at by j2emanue. Previously, I had my TextView in the layout of the page within which the ViewPager was located, which was incorrect.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/image_view"
android:scaleType="centerCrop" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/title_view"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Related

CardView not showing inside fragment

I am a novice Java/Android studio student, just blindly following examples on the internet.
I wanted to make a CardView inside a fragment, but most of the examples out there were putting cardview inside an activity, so I searched and changed the appropriate codes. After some time tinkering, I managed to make it build without errors.
However, cardview is not showing up in RecyclerView.
I suspect it is a layout issue, but after all the changes with layout_height and layout_width, I can't get cardview to be seen.
Any help will be appreciated.
My code:
HomeFragment.java
public class HomeFragment extends Fragment implements View.OnClickListener {
final int ITEM_SIZE = 5;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
Button bh = v.findViewById(R.id.bh);
bh.setOnClickListener(this);
RecyclerView rv = (RecyclerView) v.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
rv.setHasFixedSize(true);
rv.setLayoutManager(layoutManager);
List<Item> items = new ArrayList<>();
Item[] item = new Item[ITEM_SIZE];
item[0] = new Item(R.drawable.a, "#1");
item[1] = new Item(R.drawable.b, "#2");
item[2] = new Item(R.drawable.c, "#3");
item[3] = new Item(R.drawable.d, "#4");
item[4] = new Item(R.drawable.e, "#5");
RecyclerAdapter adaptor = new RecyclerAdapter(getActivity(), items, R.layout.fragment_home);
rv.setAdapter(adaptor);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bh:
((BottomNavigationView)getActivity().findViewById(R.id.nav_view)).setSelectedItemId(R.id.navigation_settings);
break;
}
}
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
Context context;
List<Item> items;
int item_layout;
public RecyclerAdapter(Context context, List<Item> items, int item_layout) {
this.context = context;
this.items = items;
this.item_layout = item_layout;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_home, null);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Item item = items.get(position);
Drawable drawable = ContextCompat.getDrawable(context, item.getImage());
holder.image.setBackground(drawable);
holder.title2.setText(item.getTitle());
holder.cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, item.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return this.items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
TextView title2;
CardView cardview;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
title2 = (TextView) itemView.findViewById(R.id.title2);
cardview = (CardView) itemView.findViewById(R.id.cardview);
}
}
}
Item.java
public class Item {
int image;
String title;
int getImage() { return this.image; }
String getTitle() { return this.title; }
public Item(int image, String title) {
this.image = image;
this.title = title;
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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/MainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title_home"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.952"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/bh"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_home" />
<Button
android:id="#+id/bh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="50dp"
android:text="#string/title_settings"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
card.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.card.MaterialCardView
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="200dp"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="20dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/title2"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="5dp"
android:text="TextView"
android:textSize="25sp" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
Seems you are inflating the wrong layout in RecyclerAdapter.java
try this
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
Context context;
List<Item> items;
int item_layout;
public RecyclerAdapter(Context context, List<Item> items, int item_layout) {
this.context = context;
this.items = items;
this.item_layout = item_layout;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card, null);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Item item = items.get(position);
Drawable drawable = ContextCompat.getDrawable(context, item.getImage());
holder.image.setBackground(drawable);
holder.title2.setText(item.getTitle());
holder.cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, item.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return this.items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
TextView title2;
CardView cardview;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
title2 = (TextView) itemView.findViewById(R.id.title2);
cardview = (CardView) itemView.findViewById(R.id.cardview);
}
}

Android ViewPager from custom library Bug

I learning, how to create a android library and I create a simple onboarding Library. But I have a problem with my ViewPager from my custom module.
When I swipe in right and left, my seconds item is not display or first and second view is overlay.
I don't understand where the problem comes from
[![enter image description here][2]][2]
[![ ][3]][3]
Main class in my library:
public class OnBoardingView extends FrameLayout implements LifecycleObserver {
public OnBoardingView(#NonNull Context context) {
super(context, null);
this.initialize(context, null);
}
public OnBoardingView(#NonNull Context context, #NonNull AttributeSet attrs) {
super(context, attrs);
this.initialize(context, attrs);
}
private void initialize(#NonNull Context context, #Nullable AttributeSet attrs) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.onboarding_view_root, this);
List<String> list = new ArrayList<String>();
list.add("Hello world 1");
list.add("Hello world 2");
list.add("Hello world 3");
ViewPager viewPager = findViewById(R.id._screenPager);
OnBoardingAdapter<String> onBoardingAdapter = new OnBoardingAdapter<String>(context, list);
viewPager.setAdapter(onBoardingAdapter);
}
}
My adapter:
public class OnBoardingAdapter<T> extends PagerAdapter {
private Context context;
private List<T> onBoardingList;
public OnBoardingAdapter(Context context, List<T> list) {
this.context = context;
this.onBoardingList = list;
}
#Override
public int getCount() {
return this.onBoardingList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view.getClass() == object.getClass();
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
View view = LayoutInflater.from(context).inflate(R.layout.onboarding_screen_view, null);
container.addView(view);
return view;
}
}
My XML file to content ViewPager :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="#+id/_screenPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
My Xml for each page:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="onboarding_screen_view" />
</LinearLayout>
And in main main_activity file I call this to display my module:
<com.domaine.onboarding.OnBoardingView
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Try to return view instead of container
If you want to achieve this easily try to use viewpager2, you can use adapter that similar with recyclerview adapter
https://developer.android.com/training/animation/vp2-migration

Getting Problem In RecycleView with TextInputEditText

I am a new Programmer, actually I was trying to make an app. I was trying to make an activity that uses RecyclerView to Show TextInputEditText with spinner and TextView. It means that I was trying to make an activity that uses Recyclerview and In the layout of Recycler View, I have used Text Input Edit Text and Spinner and TextView. I have put these three in a single layout. But the main problem that I facing is that when I launch my app with my code then it remains blank activity it is not showing TextInputEditText nor spinner and nor TextView.
So the conclusion is I want to show [TextInputEditText, Spinner and TextView] in RecyclerView But my code is returning Blank Activity.
Here is my code:-
It is my adapter class:-
public class SpecialHoursAdapter extends RecyclerView.Adapter<SpecialHoursAdapter.SpecialHourHolder> {
// private ArrayList[] mDataSet;
private List<SpecialHorusModal> modal = new ArrayList<>();
private Context context;
public SpecialHoursAdapter(Context context) {
this.context = context;
}
#NonNull
#Override
public SpecialHourHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.special_hours_layout_card, parent, false);
return new SpecialHourHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SpecialHourHolder holder, int position) {
}
#Override
public int getItemCount() {
return modal.size();
}
public static class SpecialHourHolder extends RecyclerView.ViewHolder {
private TextInputEditText editText;
private Spinner spinner;
private TextView textView;
public SpecialHourHolder(#NonNull View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.special_hours_editor);
spinner = itemView.findViewById(R.id.spinner_special_hours_date);
textView = itemView.findViewById(R.id.time_picker_special_horus);
}
}
}
It is My MainActivity:-
public class SpecialHoursActivity extends AppCompatActivity {
private RecyclerView containerRecyclerView;
private RecyclerView.LayoutManager first, container;
private SpecialHoursAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_special_horus);
// mainRecyclerView = findViewById(R.id.activity_special_horus_main_recyclerview);
containerRecyclerView = findViewById(R.id.layout_container_recyclerview_special_hours);
// mainRecyclerView.setHasFixedSize(true);
containerRecyclerView.setHasFixedSize(true);
first = new LinearLayoutManager(this);
container = new LinearLayoutManager(this);
// mainRecyclerView.setLayoutManager(first);
containerRecyclerView.setLayoutManager(container);
containerRecyclerView.setAdapter(adapter);
}
}
Here is my RecyclerView Layout:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/special_hours_editor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Special Hours"
android:inputType="text"
android:maxLength="20" />
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Spinner
android:id="#+id/spinner_special_hours_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/time_picker_special_horus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:gravity="end"
android:text="00:00" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
My Main Layout -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_special_horus_main_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbars="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/layout_container_recyclerview_special_hours"
android:orientation="vertical"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
I have not used any modal class because I don't know how to use it with Widgets.
you need to pass the data to your adapter
public SpecialHoursAdapter(Context context,List<SpecialHorusModal> data) {
this.context = context;
this.model=data; //it will show your recyclerview
}
we could not show the Recyclerview with empty data
You need to populate the data your Adapter holds, adapter with empty data will obviously show no items.
public class SpecialHoursAdapter extends RecyclerView.Adapter<SpecialHoursAdapter.SpecialHourHolder> {
private List<SpecialHorusModal> items = new ArrayList<>();
private Context context;
public SpecialHoursAdapter(Context context) {
this.context = context;
}
//Call this in onClick of your button, passing it the object to add
public void addItem(SpecialHoursModal item) {
items.add(item);
notifyDataSetChange(); //This is important
}
#NonNull
#Override
public SpecialHourHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.special_hours_layout_card, parent, false);
return new SpecialHourHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SpecialHourHolder holder, int position) {
//Bind the data to view for the object at this position
SpecialHorusModal item = items.get(position);
//...
}
#Override
public int getItemCount() {
return items.size();
}
public static class SpecialHourHolder extends RecyclerView.ViewHolder {
private TextInputEditText editText;
private Spinner spinner;
private TextView textView;
public SpecialHourHolder(#NonNull View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.special_hours_editor);
spinner = itemView.findViewById(R.id.spinner_special_hours_date);
textView = itemView.findViewById(R.id.time_picker_special_horus);
}
}
}
When your button is clicked, or you need to add an item:
adapter.addItem(new SpecialHorusModal(...));

Can`t Pass a Model Class to my BaseAdapter

Error Shown:
Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference.
The error surface at the gridView.setAdapter(adapter); but am able to print response from API only to pass it to the adapter for layout to handle the display.
Am suggesting converting the Model Class into a list of array of which is not actually going my way.
Have tried modelName.toArray() and many others.
Thank you as i await your response.
My Model Class
public class MensWear {
private int id, user_id;
private String first_wear;
public MensWear(int id,int user_id,String first_wear) {
this.id = id;
this.user_id = user_id;
this.first_wear = first_wear;
}
public int getId() {
return id;
}
public int getUser_id() {
return user_id;
}
public String getFirst_wear() {
return first_wear;
}
}
My Base Adapter Class
public class PhoneAdapter extends BaseAdapter {
private Context context;
private List<MensWear> mensWears;
public String imageUrlFromServer = "http:/10.0.2.2:5757/api/public/images/";
public PhoneAdapter(Context context, List<MensWear> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final MensWear mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.phone_list, null);
}
//For text
TextView prdId = view.findViewById(R.id.mensWearIdForHompePage);
prdId.setText(prdId.toString());
//For images
final ImageView imageView = view.findViewById(R.id.phoneImages);
if(!TextUtils.isEmpty(mensWear.getFirst_wear())){
Picasso.with(context).load(imageUrlFromServer+mensWear.getFirst_wear())
.into(imageView);
}
return view;
}
}
My Class extending Fragment
public class Phones extends Fragment {
private GridView gridView;
private List<MensWear> mensWears;
private PhoneAdapter adapter;
public Phones() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phones,container,false);
}
#Override
public void onViewCreated(#NonNull View view,#Nullable Bundle savedInstanceState) {
super.onViewCreated(view,savedInstanceState);
gridView = view.findViewById(R.id.gridHolder);
gridView = view.findViewById(R.id.gridHolder);
Call<MensWearResponse> wearResponseCall =
Service.getInstance().getApi().getAllMensWears();
wearResponseCall.enqueue(new Callback<MensWearResponse>() {
#Override
public void onResponse(Call<MensWearResponse> call,Response<MensWearResponse> response) {
mensWears = response.body().getMensWears();
for (MensWear mwr : mensWears){
Log.d("Name", mwr.getFirst_wear());
}
adapter = new PhoneAdapter(getActivity(), mensWears);
gridView.setAdapter(adapter);
}
#Override
public void onFailure(Call<MensWearResponse> call,Throwable t) {
}
});
}
}
My Layout Files
The Grid Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context="com.nelbuc.nelbuc.goodWears"
>
<Grid
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:columnWidth="100dp"
android:numColumns="2"
android:verticalSpacing="24dp"
android:horizontalSpacing="10dp"
android:stretchMode="spacingWidthUniform"
android:id="#+id/gridHolder"
>
</Grid>
</RelativeLayout>
The List Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/phoneList"
android:layout_width="190dp"
android:background="#fff"
android:layout_height="180dp"
>
<TextView
android:id="#+id/mensWearIdForHompePage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Apple"
android:textStyle="normal|italic"
android:textSize="25dp" />
<ImageView
android:id="#+id/phoneImages"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</RelativeLayout>
Error message clearly says that GridView is null. There is no GridView in your layout, there is only Grid. Change Grid to GridView.
In your layout, You are using only Grid. Change from Grid to GridView
Create ArrayList and add the model i.e MensWear into that list like this following and then pass this list into your adpater:
ArrayList<MensWear > arrayList_mens = new ArrayList<MensWear>();
for (MensWear mwr : mensWears)
{
Log.d("Name", mwr.getFirst_wear());
arrayList_mens.add(mwr);
}

Custom view returns NULL when initialized

I want to create a custom reusable view to show in a gridlayout.
I can't seem to get the view to initialize. It always returns null in my Activity
Can anyone help me understand what I am doing wrong? I feel like it is in my Tile constructor.
My Activity:
private void addTile() {
TileView tile = new TileView(this);
tile.setTextTitle("CALLS");
tile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tilePressed(v);
}
});
mGridLayout.addView(tile);
}
The GridLayout portion of the Activity's XML:
<GridLayout
android:id="#+id/glTileArea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/COLOR_LIGHT_GREEN"
android:columnCount="2"
android:rowCount="2" >
</GridLayout>
My reusable view:
public class TileView extends View{
private View mView;
private Context mContext;
private TextView mTitle;
public TileView(Context context) {
super(context);
this.mContext = context;
}
public View TileView(){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
mView = inflater.inflate(R.layout.sample_tile_view,null);
mTitle = (TextView) mView.findViewById(R.id.tvTitle);
return mView;
}
public void setTextTitle(String text){
mTitle.setText(text);
}
}
The XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/COLOR_BLUE"
android:orientation="vertical">
<TextView
android:id="#+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="TITLE"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/COLOR_WHITE"
android:textStyle="bold"/>
</LinearLayout>
Error that I get:
Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference at com.mycompany.myapp.Views.TileView.setTextTitle
(TileView.java:77)
Problem is due to:
tile.setTextTitle("CALLS");
line. mTitle is null because TileView() method is not called anywhere in which initializing TextView.
Either call TileView() before calling setTextTitle method:
tile.TileView();
tile.setTextTitle("CALLS");
or call TileView method in constructor :
public TileView(Context context) {
super(context);
this.mContext = context;
this.TileView(); //<< call here
}
Try to move the code in TileView() to TileView(Context context)
public TileView(Context context) {
super(context);
this.mContext = context;
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
mView = inflater.inflate(R.layout.sample_tile_view,null);
mTitle = (TextView) mView.findViewById(R.id.tvTitle);
}

Categories

Resources