List views and custom adapters: resource id for textview - java

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);

Related

ViewPager inside Dialog not showing

I have a custom dialog that has a ViewPager inside of it, when the dialog shows the ViewPager is just blank, not progressing on swipe or when pressing the "Next" button I implemented. I tried slightly altering my code and it didn't work. I saw several posts like this, but none of their solutions worked. PS if some things don't make sense or have mismatched names then that's because I renamed/removed some of the files/variables to simplify.
SliderAdapter:
public class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<String> text;
public SliderAdapter(Context context, ArrayList<String> text) {
this.context = context;
this.text = text;
}
public String[] txtH = {
"test1",
"test2",
"test3"
};
#Override
public int getCount() {
return txtH.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_wr, container, false);
TextView txt1 = view.findViewById(R.id.txt11);
TextView txt2 = view.findViewById(R.id.txt22);
txt1.setText(txtH[position]);
txt2.setText(text.get(position));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
Dialog itself:
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
R.style.Dialog);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
preferences = getActivity().getSharedPreferences("label", 0);
Random random = new Random();
text.add("test1");
text.add("test2");
text.add("test3");
viewPager = view.findViewById(R.id.viewPager);
dotLayout = view.findViewById(R.id.dotLayout);
next = view.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (next.getText().toString().equals("Proceed")) {
dismiss();
} else {
viewPager.setCurrentItem(currentPage + 1);
}
}
});
back = view.findViewById(R.id.back);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPage--);
}
});
builder.setView(view)
.setCancelable(true);
addDotsIndicator(0);
viewPager.setOnPageChangeListener(viewListener);
adapter = new SliderAdapter(getActivity(), text);
return builder.create();
}
private void addDotsIndicator(int position) {
dots = new TextView[3];
dotLayout.removeAllViews();
for (int i = 0; i<dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("&#8226"));
dots[i].setTextSize(35);
dots[i].setTextColor(Color.parseColor("#404040"));
dotLayout.addView(dots[i]);
}
if(dots.length > 0) {
dots[position].setTextColor(Color.BLACK);
}
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addDotsIndicator(position);
currentPage = position;
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
} else if (currentPage == 1) {
back.setEnabled(true);
next.setEnabled(true);
back.setText("Back");
next.setText("Next");
} else if (currentPage == 2) {
back.setEnabled(true);
next.setEnabled(false);
back.setText("Back");
next.setText("Proceed");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
Dialog XML:
<RelativeLayout
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:background="#drawable/dialog_bg"
app:cardCornerRadius="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/dotLayout"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:layout_below="#+id/viewPager"
android:orientation="horizontal" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="#+id/viewPager"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Back"
android:textColor="#android:color/black" />
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/viewPager"
android:layout_margin="5dp"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Next"
android:textColor="#android:color/black" />
</RelativeLayout>
ViewPager's slide layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:background="#android:color/white">
<TextView
android:id="#+id/txt11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST"
android:textColor="#android:color/black"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.24000001" />
<TextView
android:id="#+id/txt22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Test"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/txt11"
app:layout_constraintStart_toStartOf="#+id/txt11"
app:layout_constraintTop_toBottomOf="#+id/txt11"
app:layout_constraintVertical_bias="0.26" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem is that you didn't set the ViewPager adapter
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
viewPager = view.findViewById(R.id.viewPager);
...
adapter = new SliderAdapter(getActivity(), text);
viewPager.setAdapter(adapter); // <<<<<< change here
return builder.create();
}
...
Here is my test

Android - Custom ArrayAdapter - Clicks on ListItems are not recognized

I implemented a custom ArrayAdapter which causes the problem that any click on the TextView element of the ListItem is not recognized by the ListView; However clicking on the ImageView element of the ListItem leads to the desired effect. I just couldn't figure out how this behavior is caused even tough i followed the tutorials.
Everything works just fine when i use the standard ArrayAdapater.
I am going to include the involved classes since i don't know which of them is relevant to solve this issue.
CustomArrayAdapter:
public class ClassCustomArrayAdapter extends ArrayAdapter {
private ArrayList<ArrayList<String>> contactsArray;
private Context context;
public ClassCustomArrayAdapter(Context context, int textViewResourceId, ArrayList<ArrayList<String>> contactsArray) {
super(context, textViewResourceId, contactsArray);
this.contactsArray = contactsArray;
this.context = context;
}
private class ViewHolder{
ImageView imageView;
TextView textView;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView == null) {
convertView = layoutInflater.inflate(R.layout.fragment_custom_listview_item, null);
viewHolder = new ViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.tv);
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.iv);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(String.format("%s %s", contactsArray.get(position).get(2), contactsArray.get(position).get(1)));
viewHolder.imageView.setImageResource(R.drawable.ic_baseline_person_24);
return convertView;
}
}
FragmentListContacts:
public class FragmentListContacts extends Fragment {
private ArrayList<ArrayList<String>> contacts_arraylist;
private ArrayList<ArrayList<String>> contacts_array_listview;
private ArrayAdapter<String> contact_ids;
private ArrayAdapter<ArrayList<String>> contacts_arrayadapter;
private ListView contacts_listview;
private FloatingActionButton add_contact_fab;
private Database db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list_contacts, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
contacts_listview = getActivity().findViewById(R.id.contacts_listview);
add_contact_fab = getActivity().findViewById(R.id.add_contact_fab);
initAddContactFAB();
db = new Database(getContext());
//db.insertNewContact("A", "B", "123", "321");
//db.insertNewContact("C", "D", "456", "654");
contacts_arraylist = new ArrayList<>();
contacts_arraylist.addAll(db.getContacts());
//contacts_arrayadapter = new ArrayAdapter<ArrayList<String>>(getContext(), android.R.layout.simple_list_item_1, android.R.id.text1, contacts_arraylist);
ClassCustomArrayAdapter classCustomArrayAdapter = new ClassCustomArrayAdapter(getContext(), R.layout.fragment_custom_listview_item, contacts_arraylist);
//contacts_listview.setAdapter(contacts_arrayadapter);
contacts_listview.setAdapter(classCustomArrayAdapter);
contacts_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), ActivityListNotesByContact.class);
startActivity(intent);
}
});
registerForContextMenu(contacts_listview);
}
...
}
custom_listview_item:
<?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="match_parent"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/iv"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:longClickable="true"
android:clickable="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/tv"
android:gravity="center_vertical"
android:padding="5px"
android:layout_marginLeft="5dp"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textSize="60px"
android:textColor="#000000"
android:background="#FFFFFF"
android:longClickable="true"
android:clickable="true"/>
</LinearLayout>
Thanks in advance!
the ListView setOnItemClickListener intercepts the clicks of the root view of the list item, and as you enable the TextView as clickable, then it has its own click listener that won't be intercepted by the ListView setOnItemClickListener .
Solution:
You need to make both TextView and ImageView as not clickable or focus-able
android:clickable="false"
android:focusable="false"
You can use below list item layout..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="5dp"
android:gravity="center_vertical"
android:clickable="false"
android:focusable="false"/>
<TextView
android:id="#+id/tv"
android:layout_width="match_parent"
android:layout_height="50dp"
android:clickable="false"
android:focusable="false"
android:layout_marginLeft="5dp"
android:background="#FFFFFF"
android:gravity="center_vertical"
android:textColor="#000000" />
</LinearLayout>

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.

Read all values inside a list view Android

I am using a loop to read all the spinner elements (inside a cardview) in the listview.
But the loop gives one item less i.e. the last item.
I have included all the source code.
What may be the problem?
Is there any other way to read all the items in listview?
Main Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/ll_gpa"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ListView
android:id="#+id/listSubs"
android:scrollbars="none"
android:layout_height="0dip"
android:layout_width="match_parent"
android:layout_weight="1"
/>
<Button
android:text="Calculate GPA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnGpa"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
Single Item Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv_subject"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/rl_subject"
>
<TextView
android:id="#+id/subTitle"
android:textSize="16sp"
android:text="Subject"
android:layout_toStartOf="#+id/subGrade"
android:layout_toLeftOf="#+id/subGrade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:dropDownWidth="40dp"
android:textAlignment="center"
android:entries="#array/grades"
android:id="#+id/subGrade"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
MainActivity
public class MainActivity extends AppCompatActivity {
private static SubjectArrayAdapter adapter;
private ProgressDialog progress;
JsonArray subs = new JsonArray();
JsonArray dataGrades = new JsonArray();
ListView listView;
ArrayList<SubjectClass> subjects = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
res = new GetSubNames().execute();
subs = res.getAsJsonArray("subjects");
for (int i = 0; i < subs.size(); i++){
JsonObject temp = subs.get(i).getAsJsonObject();
subjects.add(new SubjectClass(temp.get("subCode").getAsString(), temp.get("subTitle").getAsString()));
}
adapter = new SubjectArrayAdapter(subjects,GpaActivity.this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Button btnGpa = (Button) findViewById(R.id.btnGpa);
btnGpa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CalcGPA().execute();
JsonArray temparr = new JsonArray();
for (int i = 0; i < listView.getChildCount(); i++) {
// Get row's spinner
View listItem = listView.getChildAt(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
dataGrades = temparr;
}
});
}
}
Custom Class
class SubjectClass{
String title;
String code;
SubjectClass(String code, String title) {
this.code = code;
this.title = title;
}
String getTitle(){
return this.title;
}
String getCode(){
return this.code;
}
void setCode(String code){
this.code = code;
}
void setTitle(String title){
this.title = title;
}
}
Custom ArrayAdapter
public class SubjectArrayAdapter extends ArrayAdapter<SubjectClass>{
private ArrayList<SubjectClass> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
}
public SubjectArrayAdapter(ArrayList<SubjectClass> data, Context context) {
super(context, R.layout.item_subject, data);
this.dataSet = data;
this.mContext=context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
SubjectClass dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_subject, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.subTitle);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
viewHolder.txtName.setText(dataModel.getCode() + " " + dataModel.getTitle());
// Return the completed view to render on screen
return convertView;
}
}
for (int i = 0; i < listView.getCount(); i++) {
// Get row's spinner
View listItem = listView.getItemAtPosition(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
Check for above code in main activity. Use .getCount() instead .getChildCount()
and use .getItemAtIndex() instead .getChildAt().
I hope this solves the issue.

I want to Have a custom listView of an arraylist with multiple contents

I made a class named Student, I want to add some objects of students to an arrayList.
I have an activity in java Android and I want to make each object by clicking add button.and simultaneously I want to show student name and address in a custom listview above that activity,that means I want to list students arrayList in a layout.
how should I make an adapter for this arraylist ??
Can anybody complete these code ??
Button btnadd = (Button) findViewById(R.id.btnAdd);
btnadd.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
EditText etname = (EditText) findViewById(R.id.etName);
EditText etaddress = (EditText) findViewById(R.id.etAddress);
RadioGroup typeRadio = (RadioGroup)findViewById(R.id.radioType);
List<Student> rlist = new ArrayList<Student>();
rlist.add(new Student(etname.getText().toString(),
etaddress.getText().toString(),
typeRadio.toString()));
}
}
);
}
private class MyArrayAdapter<String> extends ArrayAdapter<String>{
?
?
?
}
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_layout, parent, false);
ImageView iv = (ImageView) row.findViewById(R.id.resType);
TextView tv1 = (TextView) row.findViewById(R.id.resName);
TextView tv2 = (TextView) row.findViewById(R.id.resAddress);
?
?
?
?
return row;
}
Here's the working code. You can add whatever you want for each row in custom_row.xml.
MainActivity.class
public class MainActivity extends ActionBarActivity {
ListView listView;
CustomAdapter adapter;
ArrayList<Student> studentArrayList;
EditText ename, eaddress;
Button enter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ename = (EditText)findViewById(R.id.eName);
eaddress = (EditText)findViewById(R.id.eAddress);
enter = (Button) findViewById(R.id.enter);
studentArrayList = new ArrayList<Student>();
adapter = new CustomAdapter(this,studentArrayList);
listView.setAdapter(adapter);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String got_name = ename.getText().toString();
String got_address = eaddress.getText().toString();
if (got_name!=null && got_address!=null)
{
Student student = new Student(got_name, got_address);
studentArrayList.add(student);
ename.setText(" ");
eaddress.setText(" ");
adapter.notifyDataSetChanged();
}
}
});
}
private class CustomAdapter extends BaseAdapter {
Context context;
ArrayList<Student> studentArrayList;
public CustomAdapter(MainActivity activity, ArrayList<Student> studentArrayList) {
this.context = activity;
this.studentArrayList = studentArrayList;
}
#Override
public int getCount() {
return studentArrayList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.custom_row, null);
}
TextView studentName = (TextView)v.findViewById(R.id.studentName);
TextView studentAddress = (TextView)v.findViewById(R.id.studentAddress);
studentName.setText(studentArrayList.get(i).getName());
studentAddress.setText(studentArrayList.get(i).getAddress());
return v;
}
}
}
activity_main.xml
<RelativeLayout 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" tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:id="#+id/listView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enter Name : "
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="22dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enter Address : "
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView"
android:layout_marginTop="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/eName"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/listView"
android:layout_alignEnd="#+id/listView"
android:layout_toRightOf="#+id/textView2"
android:layout_toEndOf="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/eAddress"
android:layout_alignBottom="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/enter"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="32dp" />
</RelativeLayout>
Student.class
public class Student {
String name, address;
public Student(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
custom_row.xml
<?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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="New Text"
android:id="#+id/studentName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Medium Text"
android:id="#+id/studentAddress"
android:layout_below="#+id/studentName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Output :

Categories