CustomArrayAdapter.add() not changing my TextView - java

Java:
dateInserted = getDateFromDatePicker(datePicker);
calendarDateInserted.setTime(dateInserted);
finalDateShown = getStringRepresentationOfDate(calendarDateInserted.get(Calendar.DAY_OF_WEEK)) + " " + (calendarDateInserted.get(Calendar.MONTH) + 1) + "/" + (calendarDateInserted.get(Calendar.DATE)) + "/" + (calendarDateInserted.get(Calendar.YEAR));
Log.d("debug",finalDateShown); // Print the string to the LogCat
;
myArrayAdapter.add(new MyItem(finalDateShown));
MyArrayAdapter class:
private class MyArrayAdapter extends ArrayAdapter<MyItem> // My custom array adapter class
{
private int myResourceId = 0;
private LayoutInflater myLayoutInflater;
private RadioButton mySelectedRadioButton;
private int mSelectedPosition = -1;
private ButtonClickListener myClickListener = null;
public MyArrayAdapter(Context context, int myResourceId, List<MyItem> objects,ButtonClickListener myClickListener)
{
super(context, myResourceId, myItemList);
this.myResourceId = myResourceId;
myLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.myClickListener = myClickListener;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
final ViewHolder holder;
if (view == null)
{
view = myLayoutInflater.inflate(myResourceId, parent, false);
holder = new ViewHolder();
holder.dateTextView = (TextView) view.findViewById(R.id.dates_id);
holder.addDateButton = (Button) view.findViewById(R.id.add_date_button_id);
holder.addCommentButton = (Button)view.findViewById(R.id.add_comment_button_id);
holder.selectDateRadioButton = (RadioButton) view.findViewById(R.id.select_date_radio_button_id);
holder.addDateButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(position != mSelectedPosition && mySelectedRadioButton != null)
{
mySelectedRadioButton.setChecked(false);
}
mSelectedPosition = position;
mySelectedRadioButton = holder.selectDateRadioButton;
Log.d("debug", finalDateShown);
add(new MyItem(finalDateShown));
}
});
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
if(mSelectedPosition != position)
{
holder.selectDateRadioButton.setChecked(false);
}
else
{
holder.selectDateRadioButton.setChecked(true);
if(mySelectedRadioButton != null && holder.selectDateRadioButton != mySelectedRadioButton)
{
mySelectedRadioButton = holder.selectDateRadioButton;
}
}
return view;
} // End of getView() method
#Override
public void add(MyItem object)
{
super.add(object);
this.setNotifyOnChange(true);
}
private class ViewHolder
{
TextView dateTextView;
Button addDateButton;
Button addCommentButton;
RadioButton selectDateRadioButton;
}
}
Now the TextView is never changed to finalDateShown as it should be.
MyItem class:
class MyItem
{
public String date;
public boolean isRadioButtonChecked;
public MyItem(String date)
{
this.date = date;
this.isRadioButtonChecked = false;
}
}
listViewSingleRow:
<?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"
android:orientation="vertical" >
<TextView
android:id="#+id/dates_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/date_text"
/>
<Button
android:id="#+id/add_comment_button_id"
android:layout_width="105sp"
android:layout_height="wrap_content"
android:text="#string/add_comment_button_text"
android:layout_toRightOf="#+id/add_date_button_id"
android:layout_toEndOf="#id/add_date_button_id"
/>
<Button
android:id="#+id/add_date_button_id"
android:layout_width="80sp"
android:layout_height="wrap_content"
android:text="#string/add_date_button_text"
android:layout_toRightOf="#id/dates_id"
android:layout_toEndOf="#id/dates_id"
/>
<RadioButton
android:id="#+id/select_date_radio_button_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/add_comment_button_id"
android:layout_toEndOf="#id/add_comment_button_id"
/>
</RelativeLayout>
Every time i use myArraAdapter.add(finalDateShown) its adding it with the android:Text="SomeText" i assigned in the XML instead of finalDateShown.
So whats wrong here?
EDIT:
Activity:
public class SexAcivity extends AppCompatActivity
{
ListView listView;
MyArrayAdapter myArrayAdapter;
List<MyItem> myItemList = new ArrayList<SexAcivity.MyItem>();
public interface ButtonClickListener
{
public abstract void onButtonClick(int position);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sex_acivity);
listView = (ListView) findViewById(R.id.list_view_id);
listView.setLayoutParams(layoutParams);
headerView = ((LayoutInflater)SexAcivity.this.getSystemService(SexAcivity.this.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_view_header, null, false);
listView.addHeaderView(headerView);
myArrayAdapter = new MyArrayAdapter(SexAcivity.this,R.layout.list_view_single_row,myItemList,new ButtonClickListener()
{
#Override
public void onButtonClick(int position)
{
}
});
listView.setAdapter(myArrayAdapter);
finalDateShown = getStringRepresentationOfDate(calendarDateInserted.get(Calendar.DAY_OF_WEEK)) + " " + (calendarDateInserted.get(Calendar.MONTH) + 1) + "/" + (calendarDateInserted.get(Calendar.DATE)) + "/" + (calendarDateInserted.get(Calendar.YEAR));
Log.d("debug",finalDateShown); // Print the string to the LogCat
myArrayAdapter.add(new MyItem(finalDateShown));
myArrayAdapter.setNotifyOnChange(true);
}
}
Thats basically it.

Option A: No need to call notifyDataSet or override of the add-method. Just set myAdapter.setNotifyOnChange(true) and it will do all the magic for add, insert, clear and remove. See here. The default value is true. So I wonder why your UI does not update automatically. The list of the adapter should be set in it's constructor and passed to the super-constructor. I see that you do this. And then the adapter should be set to the ListView by calling list.setAdapter.
Option B: First add the item, then call notifyDataSetChanged.
Just a side note: In terms of object oriented programming, you should move the call to notifyDataSetChanged into your implementation of the ArrayAdapter.
private class MyArrayAdapter extends ArrayAdapter<MyItem>
{
#Override
public void add(MyItem object)
{
// add
super.add(object);
// then notify UI
this.notifyDataSetChanged();
}
}

Related

RecyclerView set the last ArrayList item data to the first item

I have a RecyclerView and an adapter which has an ArrayList of Person model.
When the app starts I type the names in the EditText and press the button:
1)
2)
3)
4)
But when I log personList data in the activity, the result is:
personList: Item 0 -----> Alireza
personList: Item 1 -----> Tohid
personList: Item 2 -----> Alireza
First item is removed and last item is repeated in the first one. (My adapter is more complex, but I have reduced the code and views to focus on the main problem)
Adapter 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="vertical">
<TextView
android:id="#+id/tv_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>
Adapter Class:
public class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Person> mList;
private View.OnClickListener listener;
public TestAdapter(ArrayList<Person> mList, View.OnClickListener listener) {
this.mList = mList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_adapter_item, parent, false);
if (viewType == Person.State.FIRST.getValue()) {
return new FirstViewHolder(itemView);
} else { // if (viewType == Person.State.SECOND.getValue())
return new SecondViewHolder(itemView);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final int pos = holder.getAdapterPosition();
final Person person = mList.get(pos);
if (holder instanceof FirstViewHolder) {
final FirstViewHolder h = (FirstViewHolder) holder;
h.tvName.setVisibility(View.GONE);
h.etName.setVisibility(View.VISIBLE);
h.etName.setText("");
h.etName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
person.setFirstName(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
h.btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
person.setState(Person.State.SECOND);
notifyItemChanged(pos);
listener.onClick(v);
}
});
} else { // if (holder instanceof SecondViewHolder)
final SecondViewHolder h = (SecondViewHolder) holder;
h.tvName.setVisibility(View.VISIBLE);
h.tvName.setText(person.getFirstName());
h.etName.setVisibility(View.GONE);
h.btnAccept.setVisibility(View.GONE);
}
}
private static class FirstViewHolder extends RecyclerView.ViewHolder {
private TextView tvName;
private EditText etName;
private Button btnAccept;
private FirstViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_name);
etName = itemView.findViewById(R.id.et_name);
btnAccept = itemView.findViewById(R.id.button);
}
}
private static class SecondViewHolder extends RecyclerView.ViewHolder {
private TextView tvName;
private EditText etName;
private Button btnAccept;
SecondViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_name);
etName = itemView.findViewById(R.id.et_name);
btnAccept = itemView.findViewById(R.id.button);
}
}
#Override
public int getItemCount() {
return mList.size();
}
#Override
public int getItemViewType(int position) {
return mList.get(position).getState().getValue();
}
}
Related Part of Activity:
ArrayList<Person> personList = new ArrayList<>();
personList.add(new Person("", Person.State.FIRST));
adapter = new TestAdapter(personList, new View.OnClickListener() {
#Override
public void onClick(View v) {
if (personList.size() < 3) {
personList.add(new Person("", Person.State.FIRST));
adapter.notifyItemInserted(personList.size());
} else {
for (int i = 0; i < personList.size(); i++) {
Log.i("personList", "Item " + i + " -----> " + personList.get(i).getName());
}
}
}
});
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
What's the problem? And how can I achieve correct and real ArrayList Data?
your problem lies with addTextChangedListener, when new items are added in recycler view old TextChangedListeners arent removed. and they keep changing your list items values. you should remove those listeners when state is changed to SECOND state(which is surprisingly tricky look at this How to remove all listeners added with addTextChangedListener). or you should add this validation when onTextChanged is triggered. if (person.getState() == Person.State.FIRST)
person.setFirstName(s.toString());

I want to display two items in one row in listview

I wanted to show 2 items on a single row in textfield,How can I place 2 items in the same row in listview?
I want something like this to be displayed :
item 1
item 2|item3
item 4
item 5 | item 6
My code :
public class MultipleItemsList extends ListActivity {
private MyCustomAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MyCustomAdapter();
int count=0;
for (int i = 1; i < 50; i++) {
if(count==0){
mAdapter.addItem("item " + i);
count++;
}
else if (count == 1) {
mAdapter.addSeparatorItem("item " + i);
count++;
}
else if(count==2){
mAdapter.addSeparatorItem1("item "+i);
count=0;
}
}
setListAdapter(mAdapter);
}
private class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_SEPARATOR1=2;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
private TreeSet<Integer> mSeparatorSet1=new TreeSet<Integer>();
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public void addSeparatorItem1(final String item){
mData.add(item);
mSeparatorSet1.add(mData.size()-1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
if(mSeparatorsSet.contains(position)){
return TYPE_SEPARATOR;
}
else if(mSeparatorSet1.contains(position)){
return TYPE_SEPARATOR1;
}
else
return TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.item1, null);
holder.textView = (TextView)convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.item2, null);
holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
break;
case TYPE_SEPARATOR1:
convertView=mInflater.inflate(R.layout.item2,null);
holder.textView=(TextView)convertView.findViewById(R.id.textSeparator1);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
}
ListView doesn't really support this kind of operation. Items in a ListView must be stacked vertically. And the inner implementation of ListView will prevent any simple attempt to convince it to lay items out differently.
Check out the GridLayout control in the compatibility library. That covers what you want to do fairly easily.
For displaying two items in one row, you must use LinearLayout as parent with weight 1. Orientation of linear layout must be horizontal.
add two childs with weight 0.5 inside the linear layout.
Definitely not the only way to do it but it will do what you ask for.
Hope it helps.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="text" />
</LinearLayout>

Unable to listen to setOnItemClickListener in ListView - Android

I have a ListView in my MainActivity which has a customAdapter to it. I am implementing a slider on each of the list items. I have also attached a footerView to my listView. Now my problem is that, the setOnClickListener is not fired, and I am not able to print the position's of the listView. It only print's for the footerView alone, which I have attached.
The code for MainActivity is
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
Then the code for my CustomAdapter is
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
Then finally the ViewPagerAdapter code is
public class MyViewPager extends ViewPager {
private static final String TAG = "MyViewPager";
private float xDown;
private float xMove;
private float yDown;
private float yMove;
private boolean isScroll = false;
private int selfIndex;
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSelfIndex(int index) {
selfIndex = index;
}
public int getSelfIndex() {
return selfIndex;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
Log.v(TAG, "on intercept");
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return super.onInterceptTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.v(TAG, "on dispatch");
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
xDown = ev.getRawX();
yDown = ev.getRawY();
Log.v(TAG, "action down: " + xDown + ", " + yDown);
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
xMove = ev.getRawX();
yMove = ev.getRawY();
Log.v(TAG, "action move: " + xMove + ", " + yMove);
if (isScroll) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
if (Math.abs(yMove - yDown) < 5 && Math.abs(xMove - xDown) > 20) {
isScroll = true;
} else {
return false;
}
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
isScroll = false;
}
return super.dispatchTouchEvent(ev);
}
}
The MainActivity layout is
<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"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
</RelativeLayout>
The layout for listview_item is
<?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="fill_parent"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
Added all XML Layouts
listview_item_main
<?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="fill_parent"
android:gravity="center"
android:minHeight="100dp" >
<TextView
android:id="#+id/tv_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/main_list_text"
android:textSize="48sp"
android:textStyle="bold" />
<EditText
android:id="#+id/et_input_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/add_contact_hint"
android:textColorHint="#color/main_list_text"
android:textColor="#color/main_list_text"
android:textSize="30sp"
android:textStyle="bold"
android:inputType="textCapCharacters"
android:background="#null"
android:textCursorDrawable="#null"
android:singleLine="true"
android:imeOptions="actionDone"
android:visibility="gone" />
</RelativeLayout>
listview_item_slide
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="100dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_menu_cancel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:focusableInTouchMode="true"
android:background="#color/gold"
android:gravity="center"
android:text="#string/cancel"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_delete"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/green"
android:gravity="center"
android:text="#string/delete"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_block"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/royalblue"
android:gravity="center"
android:text="#string/block"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
</LinearLayout>
Please help me to listen to the onItemClickListener in the MainActivity's list. I am not able to figure out where I went wrong. Thanks in advance.
you have to put your "setOnItemClickListener" to your Adapter class insted of MainActivity.
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
ViewHolder holder;
View iView = convertView;
if (convertView == null) {
iView = inflater.inflate(R.layout.listview_item, parent, false);
holder = new ViewHolder();
holder.txt_name = (TextView) iView.findViewById(R.id.name);
Typeface custom_fontG = Typeface.createFromAsset(
context.getAssets(), "KozGoPr6N-Regular.otf");
holder.txt_name.setTypeface(custom_fontG);
holder.txt_desc = (TextView) iView.findViewById(R.id.detail);
holder.ivProfile = (ImageView) iView.findViewById(R.id.flag);
iView.setTag(holder);
} else {
holder = (ViewHolder) iView.getTag();
}
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// Capture position and set results to the TextViews
holder.txt_name.setText(resultp.get(OurTeam.TAG_NAME));
holder.txt_desc.setText(resultp.get(OurTeam.TAG_DETAIL));
imageLoader.displayImage(TAG_IMAGEURL + resultp.get((OurTeam.TAG_IMG)),
holder.ivProfile, options);
// Capture ListView item click
iView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
// your code
}
});
return iView;
}
At a time you can handle click event either in Adapter class of in Activity. in your case you are doing both.
And to manage
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
Write above on click event of what ever is main view in listview_item layout (Do not forget to pass addContact and inputName views to your CustomAdapter).
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
/* mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});*/
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
and Adapter Class was..
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// your code here for list item click listener...
}
})
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
add this below line in your listview_item parent layout only.
android:descendantFocusability="blocksDescendants"
actually when the list item contains a element which can get focus then list item click listener not work.
Add this to the parent of your Listview and parent of your listview_item and try again:
android:descendantFocusability="blocksDescendants"
Like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
and this:
<?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="fill_parent"
android:descendantFocusability="blocksDescendants"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
If this does not work, call isFocusable() on your EditText and TextView
addContact.isFocusable(false);
inputName.isFocusable(false);
I am guessing you made a common error. Please check/try both changes.
1) add android:descendantFocusability="blocksDescendants" into the ListView UI ("#+id/lv_main").
Note: If this and 2nd suggestion does not work, then the Listview layout may need rework.
2) mainListView.setItemsCanFocus(false);
Note: The Listview may be confused with focusing on an item in the UI.
I think the suggested code by "Nirmal Shethwala" looks good. It has the if/else block for if (convertView == null).
EDIT: I noticed you inflated 3 xml layout files in getView(). You can only have one, and that is listview_item in your code. I know this is not well documented. I have tried this in the past. The reason is getView() method has to return only one view, and your code return convertView; like me.
Sorry I know this will take some modifications in your layout.

Using OnItemClickListener on CheckBoxes in ListView with Adapter

I have a row which is represented by an image, some text and a CheckBoxes. Whenever I'm trying to use the OnItemClickListener for the rows, the event won't fire up when clicking the CheckBoxes.
I also tried checkbox.onCheckedChangedListener but it gives me Null Pointer at findViewByID. I checked, the ID I am looking for is alright, no typos in there.
I'd like to make usage of this OnItemClickListener so later on I can play with the checkboxes. Any ideas?
Code:
ADAPTER:
public class FilterAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mFilters;
private ArrayList<Integer> mPictures;
private Typeface Bebas, DroidSans;
public FilterAdapter(Context context, ArrayList<String> filters, ArrayList<Integer> pictures) {
this.mContext = context;
this.mFilters = filters;
this.mPictures = pictures;
}
#Override
public int getCount() {
return mFilters.size();
}
#Override
public Object getItem(int position) {
return mFilters.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.category_filter_item, null);
}
DroidSans = Typeface.createFromAsset(mContext.getAssets(), "fonts/DroidSans.ttf");
ImageView filter_img = (ImageView) convertView.findViewById(R.id.category_picture);
TextView filter_category = (TextView) convertView.findViewById(R.id.filter_category);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.check_box);
filter_category.setTypeface(DroidSans);
filter_category.setText(mFilters.get(position));
filter_img.setBackgroundResource(mPictures.get(position));
return convertView;
}
}
Class where using the Adapter:
public class CheckinFilters extends Fragment {
private ListView mListView;
private FilterAdapter filterAdapter;
private ArrayList<String> l = new ArrayList<String>();
private ArrayList<Integer> drawables = new ArrayList<Integer>();
private Typeface Bebas;
private ArrayList<Integer> checkboxes = new ArrayList<Integer>();
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public CheckinFilters() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_checkin_filters, container, false);
l.add("Chill");
l.add("Eat");
l.add("Explore");
l.add("Move");
l.add("Party");
l.add("Whatever");
drawables.add(R.drawable.category_chill);
drawables.add(R.drawable.category_eat);
drawables.add(R.drawable.category_explore);
drawables.add(R.drawable.category_move);
drawables.add(R.drawable.category_party);
drawables.add(R.drawable.category_whatever);
mListView = (ListView) view.findViewById(R.id.filter_list);
filterAdapter = new FilterAdapter(view.getContext(), l, drawables);
mListView.setAdapter(filterAdapter);
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
Bebas = Typeface.createFromAsset(view.getContext().getAssets(), "fonts/BebasNeue.otf");
TextView mainHeader = (TextView) view.findViewById(R.id.filters_text);
mainHeader.setTypeface(Bebas);
SearchView filter_categories = (SearchView) view.findViewById(R.id.filter_categories);
int searchImgID = getResources().getIdentifier("android:id/search_button", null, null);
ImageView searchViewHint = (ImageView) filter_categories.findViewById(searchImgID);
searchViewHint.setImageResource(R.drawable.ab_icon_search);
int searchPlateID = filter_categories.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlateView = filter_categories.findViewById(searchPlateID);
if (searchPlateView != null) {
searchPlateView.setBackgroundResource(R.drawable.search_location_shape);
}
int searchViewID = filter_categories.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) filter_categories.findViewById(searchViewID);
textView.setTextColor(Color.GRAY);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.check_box);
return view;
}
private void save() {
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putInt("first", checkboxes.size());
for (int i = 0; i < checkboxes.size(); i++) {
editor.remove("Status_" + i);
editor.putInt("Status_" + i, checkboxes.get(i));
}
editor.commit();
}
private void load() {
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
int size = sharedPreferences.getInt("first", 0);
for (int i = 0; i < size; i++) {
checkboxes.add(sharedPreferences.getInt("Status_" + i, 0));
}
}
#Override
public void onPause() {
super.onPause();
save();
}
#Override
public void onResume() {
super.onResume();
load();
}
}
Layout I'm inflating for Adapter:
<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECF0F1">
<ImageView
android:id="#+id/category_picture"
android:layout_width="70dp"
android:layout_height="60dp"
android:background="#drawable/sm_profile"/>
<TextView
android:id="#+id/filter_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/category_picture"
android:padding="10dp"
android:text="Party"
android:textColor="#color/enloop_dark_gray"
android:textSize="18dp"/>
<CheckBox
android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="10dp"/>
</RelativeLayout>
</RelativeLayout>
Instead of using OnItemClickListener in CheckinFilters.java, you should add that code in getView() method of FilterAdapter. You are actually adding checkbox for every row but the id for all checkbox is same, so you can't apply customized code for every checkbox.
To be able to make use of all checkboxes you can put checkbox code in getView() method because it also contains an argument called position. So you can just get the position and apply OnItemClickListener to every single checkbox. That way it will work.
public class FilterAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mFilters;
private ArrayList<Integer> mPictures;
private Typeface Bebas, DroidSans;
public FilterAdapter(Context context, ArrayList<String> filters, ArrayList<Integer> pictures) {
this.mContext = context;
this.mFilters = filters;
this.mPictures = pictures;
}
#Override
public int getCount() {
return mFilters.size();
}
#Override
public Object getItem(int position) {
return mFilters.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.category_filter_item, null);
}
DroidSans = Typeface.createFromAsset(mContext.getAssets(), "fonts/DroidSans.ttf");
ImageView filter_img = (ImageView) convertView.findViewById(R.id.category_picture);
TextView filter_category = (TextView) convertView.findViewById(R.id.filter_category);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.check_box);
filter_category.setTypeface(DroidSans);
filter_category.setText(mFilters.get(position));
filter_img.setBackgroundResource(mPictures.get(position));
if(position == 0) {
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
else {
}
}
});
}
//Similarly add OnClickListener to other checkboxes.
return convertView;
}
}

Printing SQLite entries into a ListView

I am having some trouble learning the ins and outs of the SQLite world. I have some code that is allowing me to enter data into a DB. But what i want to do is return this data into a listview. At the moment all I could figure out to do was to have each row printed in a toast after a new entry is added. Can someone please show me how to alter my code to print it in a listview? Or to even look at my code and see that i am going about it in the right way. Thanks
This is the code i am using which calls a display record function
//---get all Records---
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
This is the display record function
public void DisplayRecord(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"Item: " + c.getString(1) + "\n" +
"Litres: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}
I know i need to change the second function but i dont know how to do that to make it print into a listview
this is the code of getting data from database and insert into Arraylist and insert into arrayAdapter and than display it in listview .
i just done some editing in your existing code.
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
db.open();
ArrayList<String> data_list=new ArrayList<String>();
ListView lv=(ListView)findViewById(R.id.listView1);
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do {
data_list.add(c.getString(0));
DisplayRecord(c);
} while (c.moveToNext());
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, data_list);
lv.setAdapter(aa);
lv - is the object of ListView.
Create a ListView. Then provide cursorAdapter to the ListView as it's adapter to bind the data in the database to the ListView.
There are examples in the samples folder of the SDK you downloaded in the project called ApiDemos.
You need to have, 1) listview, 2) Object class, 3) Custom Adapter
Here I have just tried to implement as per your requirement.
Since I dont have db I did not try to run. The point to is to five you idea.
Because listview is widget that we use more frequently in android. This is the best approach as per my knowledge.
Layouts that required,
activity_list.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ListActivity" >
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
row_item.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="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/Item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item" />
<TextView
android:id="#+id/Litres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="litres" />
</LinearLayout>
ListActivity.java :
public class ListActivity extends Activity {
ArrayList<RowData> rowDataArrayList = new ArrayList<RowData>();
ListView list;
ListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
listAdapter = new ListAdapter(ListActivity.this, rowDataArrayList);
list.setAdapter(listAdapter);
getDataFromDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
private void getDataFromDB() {
rowDataArrayList.clear();
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(
this);
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst()) {
do {
/**
* Set your data in class
*/
RowData rowData = new RowData();
rowData.setId(c.getString(0));
rowData.setItem(c.getString(1));
rowData.setLitres(c.getString(2));
rowDataArrayList.add(rowData);
} while (c.moveToNext());
}
db.close();
/**
* To reflect new data set change in listview
*/
listAdapter.notifyDataSetChanged();
}
}
RowData.java : Model[pojo] class to save data and to bind in custom adapter.
public class RowData {
String Id;
String Item;
String Litres;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getItem() {
return Item;
}
public void setItem(String item) {
Item = item;
}
public String getLitres() {
return Litres;
}
public void setLitres(String litres) {
this.Litres = litres;
}
}
ListAdapter.java : custom adapter to bind in listview
public class ListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<RowData> rowDataArrayList = new ArrayList<RowData>();
public ListAdapter(Context context, ArrayList<RowData> rowData) {
mContext = context;
rowDataArrayList = rowData;
}
#Override
public int getCount() {
return rowDataArrayList == null ? 0 : rowDataArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
Holder holder = new Holder();
view = View.inflate(mContext, R.layout.row_item, null);
holder.tvtItem = (TextView) view.findViewById(R.id.Item);
holder.tvtLitres = (TextView) view.findViewById(R.id.Litres);
view.setTag(holder);
} else {
view = convertView;
}
Holder holder = (Holder) view.getTag();
holder.tvtItem.setText(rowDataArrayList.get(position).getItem());
holder.tvtLitres.setText(rowDataArrayList.get(position).getLitres());
return view;
}
class Holder {
TextView tvtItem;
TextView tvtLitres;
}
}
public class ListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<RowData> rowDataArrayList = new ArrayList<RowData>();
public ListAdapter(Context context, ArrayList<RowData> rowData) {
mContext = context;
rowDataArrayList = rowData;
}
#Override
public int getCount() {
return rowDataArrayList == null ? 0 : rowDataArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
Holder holder = new Holder();
view = View.inflate(mContext, R.layout.row_item, null);
holder.tvtItem = (TextView) view.findViewById(R.id.Item);
holder.tvtLitres = (TextView) view.findViewById(R.id.Litres);
view.setTag(holder);
} else {
view = convertView;
}
Holder holder = (Holder) view.getTag();
holder.tvtItem.setText(rowDataArrayList.get(position).getItem());
holder.tvtLitres.setText(rowDataArrayList.get(position).getLitres());
return view;
}
class Holder {
TextView tvtItem;
TextView tvtLitres;
}
}

Categories

Resources