getView() not called in ArrayAdapter - java

Currently I am using a library to display a card-like-tinder-swipe functionality (here) but I'm a having a little problem with the card not displaying. I've make sure to check my getCount and initialization but still it's not displaying. I'm not sure where I did wrong and I think I need a new set pair of eyes to look at this. Been at this for days. Thank you.
app_bar_main.xml
<android.support.design.widget.CoordinatorLayout
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"
tools:context="com.jobforhire.mobile.CardSliderActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" >
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="JobForHire"
android:textColor="#android:color/white"
android:textSize="24sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/activity_job_list_container"/>
</android.support.design.widget.CoordinatorLayout>
activity_job_list_container.xml
<LinearLayout 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.jobforhire.mobile.CardSliderActivity"
xmlns:android="http://schemas.android.com/apk/res/android">
<link.fls.swipestack.SwipeStack
android:id="#+id/swipeStack"
android:layout_width="320dp"
android:layout_height="240dp"
android:padding="32dp"/>
</LinearLayout>
activity_job_list_card_view.xml
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:gravity="center_horizontal"
android:padding="25dp"
card_view:cardBackgroundColor="#color/cardview_light_background"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardUseCompatPadding="true">
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/title"
android:text="Hello"/>
</android.support.v7.widget.CardView>
CardSliderActivity.java
private int cardCount = 2;
private SwipeDeck cardStack;
private String token;
private ArrayList<String> testData;
private ArrayList<DataJobCards> testJsonData = new ArrayList<>();
private ArrayList<DataPreference> dataPreferenceArrayList = new ArrayList<>();
private ArrayList<DataPreference> dataPreferenceArrayListContainer = new ArrayList<>();
private SwipeDeckAdapter adapter;
/**
* Inflate a card deck and insert card into the deck
*/
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new RetrieveCards(this,1).execute();
setContentView(R.layout.activity_main);
Intent intent = getIntent();
token = intent.getStringExtra("access_token");
new PrefUserAsync(this,this,token).execute();
Fabric.with(this, new Answers());
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//toolbar.setTitle(R.string.card_title);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//getSupportActionBar().setCustomView(R.layout.custom_toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportActionBar().setDisplayShowTitleEnabled(false);
cardStack = (SwipeDeck) findViewById(R.id.swipe_deck);
}
#Override
public void PassCards(ArrayList<DataJobCards> arrayList) {
this.testJsonData = arrayList;
adapter = new SwipeDeckAdapter(testData,testJsonData,cardStack,this);
if(cardStack != null) {
cardStack.setAdapter(adapter);
Log.d("Check adapter ", "is !null");
}
else{
Log.d("Check adapter ", "is null");
}
}
CardDeckAdapter.java
public class CardDeckAdapter extends ArrayAdapter<DataJobCards> {
private Context context;
private ArrayList<Integer> randomImage = new ArrayList<>();
private ArrayList<DataJobCards> cardList;
private LayoutInflater inflater;
public CardDeckAdapter(Context context, ArrayList<DataJobCards> apps) {
super(context,0,apps);
this.cardList = apps;
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("Adapter ", "Executed");
for(int i = 0; i < cardList.size(); i++){
Log.d("Check ", cardList.get(i).getJobTitle());
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Log.d("getView ", "Executed");
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_job_list_card_view, parent,false);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
DataJobCards dataJobCard = getItem(position);
holder.name.setText(dataJobCard.getJobTitle());
return convertView;
}
#Override
public int getCount() {
return cardList.size();
}
#Override
public DataJobCards getItem(int position) {
return cardList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder {
TextView name;
}
}
EDIT
Still no progress with this so I placed a little bit more code from my main class which is CardSliderActivity.javajust in case there's something in my main class has anything to do with it.

I can only guess since I cannot see SwipeStack view defined in your xml. Your swipeStack object might be null so the adapter is not set. Can you verify?

You wrote activity_job_list_view.xml as filename when showing us the code. But later, in the getView method you inflate R.layout.activity_job_list_card_view. Is it possibile you got confused with the names? Or is it just a typo you made here on stackoverflow?

Related

ListViewAdapter context on fragment activity error, what should I do?

Good night android masters. Please help me. maybe those of you who understand better than me can help me solve the problem I'm facing right now.
1 https://imgur.com/S2TU08q
I made a listview on the fragment. I stopped because I was confused how I proceeded. maybe the code below can help you solve my problem!
This is the fragment I made. I name it Frag_Tour.java
public class Frag_Tour extends Fragment {
ListView listView;
ListViewAdapterTour adapter;
String[] judul1;
String[] judul2;
String[] durasi;
String[] harga;
int[] gambarTour;
ArrayList<Model> arrayList = new ArrayList<Model>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_tour, container, false);
judul1 = new String[]{"Paket Hemat", "Paket Reguler", "Paket Honeymoon"};
judul2 = new String[]{"Wisata Belitung", "Wisata Belitung", "Wisata Belitung"};
durasi = new String[]{"3 Hari 2 Malam", "4 Hari 3 Malam", "3 Hari 1 Malam"};
harga = new String[]{"Rp 750.000/pax", "Rp 750.000/pax", "Rp 750.000/pax"};
gambarTour = new int[]{
R.drawable.mercusuar_1, R.drawable.mercusuar_2, R.drawable.mercusuar_3
};
listView = rootView.findViewById(R.id.listView);
for (int i = 0; i < judul1.length; i++) {
Model model = new Model(judul1[i], judul2[i], durasi[i], harga[i], gambarTour[i]);
arrayList.add(model);
}
adapter = new ListViewAdapterTour(this, arrayList);
listView.setAdapter((ListAdapter) arrayList);
return rootView;
}
}
this is the xml file. frag_tour.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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent_view"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
[2] https://imgur.com/ehPanZM
this is the ListViewAdapter that I have created. I named it ListViewAdapterTour.java
public class ListViewAdapterTour extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
List<Model> modellist;
ArrayList<Model> arrayList;
public ListViewAdapterTour (Context context, List<Model> modellist) {
mContext = context;
this.modellist = modellist;
inflater = LayoutInflater.from(mContext);
this.arrayList = new ArrayList<Model>();
this.arrayList.addAll(modellist);
}
public class ViewHolder {
TextView Judul1, Judul2, Durasi, Harga;
ImageView GambarTour;
}
#Override
public int getCount() {
return modellist.size();
}
#Override
public Object getItem(int i) {
return modellist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.row_tour, null);
holder.Judul1 = view.findViewById(R.id.judul1);
holder.Judul2 = view.findViewById(R.id.judul2);
holder.Durasi = view.findViewById(R.id.durasi);
holder.Harga = view.findViewById(R.id.harga);
holder.GambarTour = view.findViewById(R.id.GambarTour);
view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}
holder.Judul1.setText(modellist.get(position).getJudul1());
holder.Judul2.setText(modellist.get(position).getJudul2());
holder.Durasi.setText(modellist.get(position).getDurasi());
holder.Harga.setText(modellist.get(position).getHarga());
holder.GambarTour.setImageResource(modellist.get(position).getGambartour());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (modellist.get(position).getJudul1().equals("Paket Hemat 3 Hari 2 Malam")){
Intent intent = new Intent(mContext, TourDetail.class);
intent.putExtra("contentTv","PAKET HEMAT");
mContext.startActivity(intent);
}
}
});
return view;
}
}
and this is the xml file. row_tour.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:focusableInTouchMode="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="#dimen/spacing_middle"
android:layout_weight="1"
app:cardCornerRadius="2dp"
app:cardElevation="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="170dp"
android:orientation="vertical">
<ImageView
android:id="#+id/GambarTour"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="#drawable/mercusuar_1"
tools:ignore="ContentDescription" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/overlay_dark_20" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#id/GambarTour"
android:layout_margin="#dimen/spacing_medium"
android:orientation="vertical"
tools:ignore="UselessParent">
<TextView
android:id="#+id/judul1"
style="#style/TextAppearance.AppCompat.Large"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Paket Hemat"
android:textColor="#color/White"
android:textStyle="bold" />
<TextView
android:id="#+id/judul2"
style="#style/TextAppearance.AppCompat.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wisata Belitung"
android:textColor="#color/White"
android:textStyle="bold" />
<TextView
android:id="#+id/durasi"
style="#style/TextAppearance.AppCompat.Caption"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/_3_hari_2_malam"
android:textColor="#color/White" />
</LinearLayout>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignEnd="#id/GambarTour"
android:layout_alignRight="#id/GambarTour"
android:layout_margin="#dimen/spacing_medium"
android:src="#drawable/ic_favorite_border"
android:tint="#color/White" />
<TextView
android:id="#+id/harga"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/GambarTour"
android:layout_alignRight="#id/GambarTour"
android:layout_alignBottom="#id/GambarTour"
android:layout_margin="#dimen/spacing_large"
android:background="#drawable/gradient_green"
android:padding="#dimen/spacing_xmedium"
android:text="Rp 750.000/pax"
android:textColor="#color/White" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
[3] https://imgur.com/h7WiBgK
and this is the code for the model.java that I use
package com.androidrion.sejengkalapp;
class Model {
private String judul1;
private String judul2;
private String durasi;
private String harga;
private int gambartour;
//constructor
Model(String judul1, String judul2, String durasi, String harga, int gambartour) {
this.judul1 = judul1;
this.judul2 = judul2;
this.durasi = durasi;
this.harga = harga;
this.gambartour = gambartour;
}
//getters
String getJudul1() {
return this.judul1;
}
String getJudul2() {
return this.judul2;
}
String getDurasi() {
return this.durasi;
}
String getHarga() {
return this.harga;
}
int getGambartour() {
return this.gambartour;
}
}
I hope the teachers and masters about Android can help me in solving this problem. what I want is row_tour.xml which I have designed to be listview in frag_tour.xml
[4] https://imgur.com/VLzOUiK
The context should be the activity holding the fragment. So instead of this in your adapter constructor, use getActivity()
adapter = new ListViewAdapterTour(getActivity(), arrayList);

RecyclerView not replacing detail pane with fragment on item click

Everytime I click a recycler view item on a tablet, it opens an activity rather than replacing the detail pane with a fragment.
The following line of code is what I use to detect wheter the detail pane is present:
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
Any ideas on the correct location to put this line of code?
activity XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
>
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
sw600dp activity XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/detailBackgroundToolbar"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/divider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<View
android:id="#+id/divider"
android:layout_width="1dp"
android:layout_height="0dp"
android:background="?attr/dividerColor"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<android.widget.Toolbar
android:id="#+id/detailBackgroundToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="3"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="4dp"
app:cardCornerRadius="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar_dualline"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v7.widget.CardView>
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toBottomOf="#+id/detailBackgroundToolbar" />
</android.support.constraint.ConstraintLayout>
Fragment class
public class MyFragment extends Fragment {
public MyFragment() {}
List<Product> wcList;
RecyclerView mRecyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet device.
*/
public boolean mTwoPane;
public static MyFragment newInstance() {
return new MyFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
mRecyclerView = view.findViewById(R.id.recyclerView_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), LinearLayout.VERTICAL));
myList = new ArrayList<>();
String[] items = getResources().getStringArray(R.array.product_names);
String[] itemDescriptions = getResources().getStringArray(R.array.product_descriptions);
for (int n = 0; n < items.length; n++){
Product desserts = new Product();
desserts.setProductName(items[n]);
wdessertsc.setProductDescriptions(itemDescriptions[n]);
myList.add(desserts);
}
MyListAdapter listAdapter = new MyListAdapter(getActivity(), myList);
mRecyclerView.setAdapter(listAdapter);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
super.onActivityCreated(savedInstanceState);
}
}
Adapter class
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
public boolean mTwoPane;
private Context mCtx;
private List<Product> myList;
public MyListAdapter(Context mCtx, List<Product> myList) {
this.mCtx = mCtx;
this.myList = myList;
}
#NonNull
#Override
public MyListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.listitem_dualline, parent,false);
return new MyListAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyListAdapter.MyViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
final Product product = myList.get(holder.getAdapterPosition());
holder.textviewTitle.setText(product.getProductName());
holder.textviewSubtitle.setText(product.getPRoductDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Fragment newFragment;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
newFragment = new FragmentProduct1();
} else {
newFragment = new FragmentProdcut2();
}
MyActivity activity = (MyActivity) v.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
intent = new Intent(v.getContext(), Product1Activity.class);
} else {
intent = new Intent(v.getContext(), Product2Activity.class);
}
mCtx.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return myList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayout;
TextView textviewTitle, textviewSubtitle;
StationViewHolder(View itemView) {
super(itemView);
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
relativeLayout = itemView.findViewById(R.id.listitem_relativelayout);
textviewTitle = itemView.findViewById(R.id.listitem_title);
textviewSubtitle = itemView.findViewById(R.id.listitem_subtitle);
}
}
}
This line mTwoPane = itemView.findViewById(R.id.detail_container) != null; from your view holder will always be false.
Why?
Because, your detail_container is not part of your view holder's item container, so itemView will always return null for your view. instead pass your boolean flag from your fragment to your adapter !
I think you are checking item two pan with recyclerview item xml
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
That you can check while constructing recyclerview adapter and save it from the activity content view itself.

List views and custom adapters: resource id for textview

I'm trying to implement my own ListView design with a custom adapter. But whenever I run my program, I get this error "ArrayAdapter: You must supply a resource ID for a TextView".
Here is my Custom Adapter
public class LayoutAdapter extends ArrayAdapter {
List list = new ArrayList();
public LayoutAdapter (Context context, int resource) {
super(context,resource);
}
static class DataHandler {
TextView accountName;
TextView availableBalance;
TextView totalBalance;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_layout,parent,false);
handler = new DataHandler();
handler.accountName = (TextView) row.findViewById(R.id.account_name);
handler.availableBalance = (TextView) row.findViewById(R.id.available_balance);
handler.totalBalance = (TextView) row.findViewById(R.id.total_balance);
row.setTag(handler);
}
else {
handler = (DataHandler)row.getTag();
}
Account account;
account = (Account)this.getItem(position);
handler.accountName.setText(account.returnName());
handler.availableBalance.setText("Available Balance: $"+account.returnAvailableBalance());
handler.totalBalance.setText("Total Balance: $"+account.returnTotalBalance());
return row;
}
}
Here is my custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:padding="8dp">
<TextView
android:text="#string/str_account_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/account_name"
android:height="80dp"
android:textSize="24sp"
android:gravity="center_vertical" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/account_name">
<TextView
android:text="#string/str_available_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/available_balance"
android:textSize="16sp"
android:layout_gravity="right"
android:paddingTop="30dp" />
<TextView
android:text="#string/str_total_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/total_balance"
android:textSize="16sp"
android:layout_gravity="right" />
</LinearLayout>
</RelativeLayout >
Here is my main activity
LayoutAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new LayoutAdapter(getApplicationContext(),R.layout.custom_layout);
ArrayList<Account> accounts = new ArrayList<>();
accounts.add(new Account ("Checking",5.00));
accounts.add(new Account ("Cash",50.00));
Account acc1 = new Account("Checking",5.00);
Account acc2 = new Account("Cash",50.00);
adapter.add(acc1);
adapter.add(acc2);
listView.setAdapter(adapter);

Android: NullPointerException when adding an Adapter to a ListView [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am creating a ViewPager in activity_table.xml.
This ViewPager has two pages which both share the same layout: list.xml.
This layout contains a ListView which I am trying to create an Adapter for.
The app compiles correctly but crashes when it tries to add the said Adapter to the ListView with a
NullPointerException when attempting to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference.
I have heard that I have to "load" a layout before I can use the Views it contains, but I how do I do that?
I have tried setContentView(R.layout.list), but it throws the same error...
Table.java
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(sectionsPagerAdapter);
String[] tmp = new String[mainTable.length-2];
ListView listView = (ListView)findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(this,R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
public static class TableFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section number";
public TableFragment() {
}
public static TableFragment newInstance(int sectionNumber) {
TableFragment fragment = new TableFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER,sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
title.setText("Heute");
else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2)
title.setText("Morgen");
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TableFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "today";
case 1:
return "tomorrow";
}
return null;
}
}
public class ListAdapter extends ArrayAdapter<String> {
public ListAdapter(Context context, int textViewResourceId) {
super(context,textViewResourceId);
}
public ListAdapter(Context context, int resource, String[] items) {
super(context,resource,items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item, null);
}
String p = getItem(position);
if(p!=null) {
TextView grade = (TextView) v.findViewById(R.id.grade);
TextView hour = (TextView) v.findViewById(R.id.hour);
TextView course = (TextView) v.findViewById(R.id.course);
TextView teacher = (TextView) v.findViewById(R.id.teacher);
TextView room = (TextView) v.findViewById(R.id.room);
TextView description = (TextView) v.findViewById(R.id.description);
try {
grade.setText(tableData[position][1]);
hour.setText(tableData[position][2]);
course.setText(tableData[position][3]);
teacher.setText(tableData[position][4]);
room.setText(tableData[position][5]);
description.setText(tableData[position][6]);
} catch (ArrayIndexOutOfBoundsException e) {
return v;
}
}
return v;
}
}
activity_table.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="de.fuchstim.vertretungsplan.Table">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:layout_gravity="bottom|right"
app:srcCompat="#drawable/reload_arrow_white" />
</android.support.design.widget.CoordinatorLayout>
list.xml
<?xml version="1.0" encoding="utf-8"?>
<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:text="Heute (25.10.16)"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.DialogWindowTitle"
android:textAlignment="center" />
<GridLayout android:layout_gravity="start"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/grade"
android:layout_height="wrap_content"
android:text="Klasse"
android:layout_row="0"
android:layout_column="0"
android:layout_width="0dp"
android:textSize="14sp"
android:layout_columnWeight="40"
android:paddingStart="10dp" />
<TextView
android:text="Stunde"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/hour"
android:layout_row="0"
android:layout_column="1"
android:layout_columnWeight="15"/>
<TextView
android:text="Lehrer"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/teacher"
android:layout_row="0"
android:layout_column="3"
android:layout_columnWeight="15"/>
<TextView
android:text="Kurs"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/course"
android:layout_row="0"
android:layout_column="2"
android:layout_columnWeight="15"/>
<TextView
android:text="Raum"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/room"
android:layout_row="0"
android:layout_column="4"
android:layout_columnWeight="15"/>
</GridLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:id="#+id/listView" />
</LinearLayout>
I have tried setContentView(R.layout.list), but it throws the same error...
First, you need to use setContentView(R.layout.activity_table) instead.
Second, you cannot find the ListView from the Activity, since it is contained within the Fragment layout.
See here? Your ListView is in the same layout as this title element, so you need to find the ListView here...
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
Move that ListView code from the Activity to the Fragment. And use getActivity() for the Adapter within the Fragment instead of this to get the Context.
That is where the #+id/listView value exists. That layout is searched with rootView.findViewById.
Since, you did not get null pointer at this location :
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(sectionsPagerAdapter);
So, this means you are using :
setContentView(R.layout.activity_table);
Because viewpager is only in above layout, and since listview is not in this layout xml file, you get null pointer on :
ListView listView = (ListView)findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(this,R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
because listview in null, not present in activity_table xml file.
You need to set adapter in OnCreateView() :
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list,container,false);
TextView title = (TextView) rootView.findViewById(R.id.title);
// Add below ...
String[] tmp = new String[mainTable.length-2];
ListView listView = (ListView)rootView.findViewById(R.id.listView);
ListAdapter listAdapter = new ListAdapter(getActivity(),R.layout.list_item,tmp);
listView.setAdapter(listAdapter);
// ends here ...
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
title.setText("Heute");
else if(getArguments().getInt(ARG_SECTION_NUMBER) == 2)
title.setText("Morgen");
return rootView;
}
Hope this helps !

Insert Value of Checkbox (ListView) into Database

So this has been bugging me for like a week and I haven't found the answer yet.
Basically I have this MainActivity which contains the main code and a fragment that work for the listview.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Button bNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RoomServer(), "Room Server");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
RoomServer.java
public class RoomServer extends ListFragment implements OnItemClickListener{
public RoomServer() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rs, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(getListView().CHOICE_MODE_MULTIPLE);
getListView().setTextFilterEnabled(true);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.rs_list, android.R.layout.simple_list_item_checked);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
}
Fragment_rs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.RoomServer">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
<Button
android:id="#+id/bNext_rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
android:layout_marginRight="39dp"
android:layout_marginEnd="39dp"
android:layout_marginBottom="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
activity_main.xml
<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
The items of listview r declared inside strings.XML
As u can see I'm using CHOICE_MODE_MULTIPLE to create checkbox in the listview. And now I'm stuck at how to get the value of this checkbox. I'm planning to use Volley to send value to my database by a button click. Most of the answer I saw was using the isChecked and stuff but I dont really understand how to implement it in my array adapter.
You can either implement a custom array adapter yourself, or use this method in the ListView class to get a SparseBooleanArray of the indexes of the selected items:
//Submit button example
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get base list
String[] items = getActivity().getResources().getStringArray(R.array.rs_list);
//Get selected items & set intent args
SparseBooleanArray selectedItems = getListView().getCheckedItemPositions();
ArrayList<String> argList = new ArrayList<>();
for (int i = 0; i < selectedItems.size(); i++) {
argList.add(items[selectedItems.keyAt(i)]);
}
//Start activity
Intent intent = new Intent();
intent.putStringArrayListExtra("SelectedItems", argList);
getActivity().startActivity(intent);
}
});

Categories