I am trying to create a custom listview with a checkbox and a string list of "observations" retrieved from my sqlite database. The idea is that when I click on the "retrieve" button, all checked items are shown in a toast message.
I can populate the listview through my customadapter just fine, but it doesnt seem to recognise the status of each checkbox, as no toast messages are shown, regardless of whether they are checked.
Please can someone show me where I am going wrong?
Here is my custom listview xm that I have called list_o:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:id="#+id/obsgrid">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chkbx"
android:layout_row="0"
android:layout_column="0" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/obs"
android:layout_row="0"
android:layout_column="1" />
Here is my custom adapter:
class CustomAdObs extends ArrayAdapter<String> {
private String [] observation;
private Boolean [] checked;
private Context context;
public CustomAdObs(Context context, String[] observation) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater siteInflater = LayoutInflater.from(getContext());
View customView = siteInflater.inflate(R.layout.list_o, parent, false);
TextView observationTV = (TextView) customView.findViewById(R.id.obs);
CheckBox checkCB = (CheckBox) customView.findViewById(R.id.chkbx);
checkCB.setTag(Integer.valueOf(position));
observationTV.setText(observation[position]);
checkCB.setChecked(checked[position]);
return customView;
}
}
Finally here is my activity:
public class selobs extends Activity {
List< List<String> > listArray = new ArrayList< List<String> >();
List<String> array1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode. setThreadPolicy(policy);
setContentView(R.layout.activity_selobs);
final Button retrieve= (Button) findViewById(R.id.btnret);
final EditText txtob = (EditText) findViewById(R.id.editText23);
filladapter();
retrieve.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
ListView obsListView = (ListView) findViewById(R.id.obsList);
View v;
for (int i = 0; i < obsListView.getCount(); i++) {
v = obsListView.getAdapter().getView(i, null, null);
CheckBox check = (CheckBox) v.findViewById(R.id.chkbx);
TextView obsItem = (TextView) v.findViewById(R.id.obs);
if (check.isChecked()) {
String p = obsItem.getText().toString();
Toast.makeText(selobs.this, p, Toast.LENGTH_LONG).show();
}
}
}
}
);
}
public void filladapter(){
myDBhandler1 dbHandler;
dbHandler = new myDBhandler1(selobs.this, null, null, 1);
listArray = dbHandler.databaseToStringObs();
List array1 = listArray.get(0);
String[] observ = (String[]) array1.toArray(new String[0]);
Boolean[] checked = new Boolean[0];
Arrays.fill(checked, Boolean.FALSE);
final ListAdapter ObsAdapter = new CustomAdObs(this, observ, checked);
final ListView obsListView = (ListView) findViewById(R.id.obsList);
obsListView.setAdapter(ObsAdapter);
obsListView.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(selobs.this, item, Toast.LENGTH_LONG).show();
TextView txtobs = (TextView) findViewById(R.id.editText23);
txtobs.setText(item);
}
}
);
}
}
your constructor
public CustomAdObs(Context context, String[] observation) {//here the Boolean[] checked ->is messing
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
so you replace it with this
public CustomAdObs(Context context, String[] observation, Boolean[] checked) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
why ?
because you call it like this
new CustomAdObs(this, observ, checked);
while you have just the 2 params in your constructor(Context context,String[] observation)
Related
For my Android project, I have a listview which has a checkbox for every item. The data is loaded from an SQLite database by using a CursorAdapter class. However, whenever I scroll, the checkbox positions will get moved and get carried down to the next part of the listview. How can I fix this problem?
GIF of my CheckBox Problem
Here's my Cursor Adapter Class:
public class VocabCursorAdapter extends CursorAdapter {
private static final int DIFFICULT = 0;
private static final int FAMILIAR = 1;
private static final int EASY = 2;
private static final int PERFECT = 3;
public VocabCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_vocab, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvVocabName = (TextView) view.findViewById(R.id.vocabName);
TextView tvVocabDefinition = (TextView) view.findViewById(R.id.vocabDefinition);
ImageView tvVocabLevel = (ImageView) view.findViewById(R.id.vocabLevel);
// Extract properties from cursor
String vocab = cursor.getString(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_VOCAB));
String definition = cursor.getString(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_DEFINITION));
int level = cursor.getInt(cursor.getColumnIndexOrThrow(VocabDbContract.COLUMN_NAME_LEVEL));
// Populate fields with extracted properties
tvVocabName.setText(vocab);
tvVocabDefinition.setText(definition);
if (level == DIFFICULT) {
tvVocabLevel.setImageResource(R.drawable.level_bars_difficult);
tvVocabLevel.setTag(DIFFICULT);
}
else if (level == FAMILIAR) {
tvVocabLevel.setImageResource(R.drawable.level_bars_familiar);
tvVocabLevel.setTag(FAMILIAR);
}
else if (level == EASY) {
tvVocabLevel.setImageResource(R.drawable.level_bars_easy);
tvVocabLevel.setTag(EASY);
}
else if (level == PERFECT) {
tvVocabLevel.setImageResource(R.drawable.level_bars_perfect);
tvVocabLevel.setTag(PERFECT);
}
}
And here's my list item xml, item_vocab.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:longClickable="true">
<ImageView
android:layout_width="36sp"
android:layout_height="36sp"
android:id="#+id/vocabLevel"
android:layout_gravity="right"
android:src="#drawable/level_bars"
android:scaleType="fitXY"
android:contentDescription="#string/vocab_level"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/editCheckbox"
android:layout_toStartOf="#+id/editCheckbox"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/vocabName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/vocabLevel"
android:layout_toStartOf="#+id/vocabLevel"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/vocabDefinition"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/vocabLevel"
android:layout_toStartOf="#+id/vocabLevel"
android:layout_below="#id/vocabName"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editCheckbox"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
And here's my xml which contains a listview
<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=".controller.MyVocab"
android:paddingLeft="5dp">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/mVocabList"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/empty_text_view"
android:id="#android:id/empty"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
I have looked at a lot of different solutions on StackOverflow, but I wasn't able to successfully do it in my own app. For an example, this post has a similar problem, but its solution used getView and I had trouble understanding how to implement it with newView and bindView instead.
And some other solutions might be examples where a cursoradapter is not involved. Any help is much appreciated, thanks a lot!
Edit #1: After incorporating Phan's changes, the checkbox states get resets to false rather than keeping its states when I scroll the listview (See ).
Reason : ListView re-uses the views.
Solution :
class VocabCursorAdapter extends CursorAdapter {
List<Integer> selectedItemsPositions;//to store all selected items position
public VocabCursorAdapter(Context context, Cursor c,int flags) {
super(context, c,0);
selectedItemsPositions = new ArrayList<>();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
View view = LayoutInflater.from(context).inflate(R.layout.item_vocab, viewGroup, false);
CheckBox box = (CheckBox) view.findViewById(R.id.editCheckbox);
box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
int position = (int) compoundButton.getTag();
if (b) {
//check whether its already selected or not
if (!selectedItemsPositions.contains(position))
selectedItemsPositions.add(position);
} else {
//remove position if unchecked checked item
selectedItemsPositions.remove((Object) position);
}
}
});
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//your other stuff
CheckBox box = (CheckBox) view.findViewById(R.id.editCheckbox);
box.setTag(cursor.getPosition());
if (selectedItemsPositions.contains(cursor.getPosition()))
box.setChecked(true);
else
box.setChecked(false);
}
}
Try this
public class VocabCursorAdapter extends CursorAdapter {
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>(); // array list for store state of each checkbox
public VocabCursorAdapter(Context context, Cursor c, int flags) {
for (int i = 0; i < c.getCount(); i++) { // c.getCount() return total number of your Cursor
itemChecked.add(i, false); // initializes all items value with false
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
...
final int position = cursor.getPosition(); // get position by cursor
CheckBox checkBox = (CheckBox) view.findViewById(R.id.editCheckbox);
checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (itemChecked.get(position) == true) { // if current checkbox is checked, when you click -> change it to false
itemChecked.set(position, false);
} else {
itemChecked.set(position, true);
}
}
});
checkBox.setChecked(itemChecked.get(position)); // set the checkbox state base on arraylist object state
Log.i("In VocabCursorAdapter","position: "+position+" - checkbox state: "+itemChecked.get(position));
}
}
public class ObservationselectattributeFragment extends Fragment {
DatabaseHandler mDBHandler;
ListView mListView;
SimpleCursorAdapter mSCA;
Cursor mCsr;
ArrayList<String> attributeItems = new ArrayList<>();
public ObservationselectattributeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the layout for this fragment
View view1=inflater.inflate(R.layout.fragment_observationselectattribute, container, false);
//Bundle bundle2 = getArguments();
Bundle bundle1 = getArguments();
final int firsttext= bundle1.getInt("TotalCount");
final String selectedtreatment= bundle1.getString("SelectedTreatment");
Toast.makeText(getActivity(),"value \n"+firsttext+"\n"+"treatment \n"+selectedtreatment, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(),"SelectedTreatment \n"+selectedtreatment, Toast.LENGTH_SHORT).show();
mListView = (ListView)view1.findViewById(R.id.lv001);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button addattribute = (Button)view1.findViewById(R.id.addattribute);
addattribute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String items1="";
Integer tcount1=0;
for(String item1:attributeItems){
items1+="-"+item1+"\n";
tcount1++;
}
Toast.makeText(getActivity(),"you have selected \n"+items1,Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(),"you have selected \n"+tcount1,Toast.LENGTH_LONG).show();
/*FragmentTransaction fr= getFragmentManager().beginTransaction();
fr.replace(R.id.main_container, new ShowObservationDataRecordingFragment()).addToBackStack("ObservationselectattributeFragment");
fr.commit();*/
Bundle bundle = new Bundle();
bundle.putInt("TotalCount2",firsttext);
bundle.putInt("TotalCount1", tcount1);
bundle.putString("SelectedTreatment", selectedtreatment);
Fragment showobservationdatarecordingfragment = new ShowObservationDataRecordingFragment();
showobservationdatarecordingfragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_container, showobservationdatarecordingfragment).addToBackStack("ObservationselectattributeFragment").commit();
}
});
mDBHandler = new DatabaseHandler(this.getActivity());
mCsr = mDBHandler.getAllRecords();
// Prepare a list of the columns to get the data from, for the ListViewt
String[] columns_to_get_data_from = new String[]{
DatabaseHandler.KEY_IDS,
DatabaseHandler.KEY_NAMES,
DatabaseHandler.KEY_FNAME,
DatabaseHandler.KEY_MONAME,
DatabaseHandler.KEY_SNAME
};
// Prepare a list of the Views into which to place the data
int[] itemviews_to_place_data_in = new int[]{
R.id.euserid,
R.id.eusername,
R.id.efname,
R.id.emoname,
R.id.esname
};
// get and instance of SimpleCursorAdapter
mSCA = new SimpleCursorAdapter(getActivity(),
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
0);
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = mListView.onSaveInstanceState();
// get and instance of SimpleCursorAdapter the listviewitem_record layout
mListView.setAdapter(mSCA);
// Restore previous state (including selected item index and scroll position)
mListView.onRestoreInstanceState(state);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String attributeItem1 = ((TextView)view.findViewById(R.id.euserid)).getText().toString();
String attributeItem2 = ((TextView)view.findViewById(R.id.eusername)).getText().toString();
String attributeItem3 = ((TextView)view.findViewById(R.id.efname)).getText().toString();
String attributeItem4 = ((TextView)view.findViewById(R.id.emoname)).getText().toString();
String attributeItem5 = ((TextView)view.findViewById(R.id.esname)).getText().toString();
String attributeItem = attributeItem1 + attributeItem2 + attributeItem3 + attributeItem4 + attributeItem5;
// CheckedTextView box = (CheckedTextView) view.findViewById(R.id.record_checkbox);
// box.setChecked(true);
CheckedTextView checkedTextView = (CheckedTextView) view.findViewById(R.id.record_checkbox);
if(checkedTextView.isChecked()) {
checkedTextView.setChecked(false);
} else {
checkedTextView.setChecked(true);
}
if(attributeItems.contains(attributeItem)){
attributeItems.remove(attributeItem);//uncheck item
}
else
{
attributeItems.add(attributeItem);
}
Toast.makeText(getActivity(), "Item1 = " + attributeItem1 +"\n"+ "Item2 ="+attributeItem2 +"\n"+"Item3 ="+attributeItem3+"\n"+"Item4 ="+attributeItem4+"\n"+"Item5 ="+attributeItem5, Toast.LENGTH_SHORT).show();
}
});
((HomeActivity) getActivity())
.setActionBarTitle("Select Attribute");
return view1;
}
}
From this Activity i get text from textField and display it in a ListView.
Now i want to to add check box on every entry in a listView Cell and also like to know how to display more than one text in a single ListView Cell.
Help with code will be appreciated.
Here is my code ....
public class AfterRegister extends AppCompatActivity
{
ListView listView;
EditText editText;
Button insertItemButton;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
CheckBox checkBox;
StoreRegistrationDataBase storeRegistrationDataBase;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_register);
storeRegistrationDataBase = new StoreRegistrationDataBase(this);
storeRegistrationDataBase = storeRegistrationDataBase.open();
checkBox = (CheckBox) findViewById(R.id.checkbox);
insertItemButton = (Button) findViewById(R.id.button4);
insertItemButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
editText = (EditText) findViewById(R.id.editText2);
listView = (ListView) findViewById(R.id.listView);
String getEditTextString = editText.getText().toString();
if(isAlphaNumeric(getEditTextString))
{
if(!getEditTextString.equals(""))
{
arrayList.add(getEditTextString);
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.text_view_layout, R.id.achView1, arrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
editText.setText("");
}
else
{
Toast.makeText(AfterRegister.this, "You can not insert empty field", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(AfterRegister.this, "Remove Space", Toast.LENGTH_SHORT).show();
}
}
});
listView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return false;
}
});
}
public boolean isAlphaNumeric(String s)
{
String pattern= "^[a-zA-Z0-9]*$";
if(s.matches(pattern))
{
return true;
}
return false;
}
}
You have to use a BaseAdapter and some Getter/Setter methods to add multiple texts/images/other UI elements in each item of your list view.
You have to implement multiple things to get this result. Here they are --
Create a Custom Layout for each item of your ListView.
listview_item_layout.xml
<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="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/layout_textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginRight="5dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/layout_textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginLeft="5dip"
android:textStyle="bold"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkbox"
android:text="Test"/>
</LinearLayout>
Create a custom class and add some Getter/Setter methods.
ListRowItem.java
public class ListRowItem implements Serializable{
String carrier,number;
public String getCarrier(){
return carrier;
}
public String getNumber(){
return number;
}
public void setCarrier(String ba_carrier){
carrier = ba_carrier;
}
public void setNumber(String ba_number){
number = ba_number;
}
}
Create a custom class and extend the BaseAdapter class.
public class MyBaseAdapter extends BaseAdapter {
public Context ba_context;
public ArrayList<ListRowItem> listitem = new ArrayList<>();
public LayoutInflater inflater;
ListRowItem currentlistitem;
public MyBaseAdapter(Context ma_context, ArrayList<ListRowItem> ma_listitem) {
super();
this.ba_context = ma_context;
this.listitem = ma_listitem;
inflater = (LayoutInflater) ba_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.listitem.size();
}
#Override
public Object getItem(int position) {
return this.listitem.get(position);
}
#Override
public long getItemId(int position) {
return (long) position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_item_layout, parent, false);
TextView carrier = (TextView) vi.findViewById(R.id.layout_textview1);
TextView number = (TextView) vi.findViewById(R.id.layout_textview2);
currentlistitem = listitem.get(position);
String str_carrier = currentlistitem.getCarrier();
String str_number = currentlistitem.getNumber();
carrier.setText(str_carrier);
number.setText(str_number);
return vi;
}
}
Finally, populate your ArrayList and set the Adapter in your MainActivity.
ArrayList<ListRowItem> listitem = new ArrayList<>();
Context context = TestActivity.this;
MyBaseAdapter baseAdapter;
ListRowItem lr = new ListRowItem();
lr.setNumber(number);
lr.setCarrier(carrier);
listitem.add(lr);
baseAdapter = new MyBaseAdapter(context,listitem);
setContentView(R.layout.activity_test);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(baseAdapter);
Hope this helps!!
Question part: 1
I have created an activity which contains product id and product name as list items. Each row contains an edittext which can be used to enter quantity for a particular product. The rows also contain a checkbox to select the particular product.
This is how the list looks like:
When I click on the list items, I can get the id and name of the particular list item, but I also want to get the quantity entered by the user for the list item.
This is the activity responsible for generating the listview:
public class PollStationActivity extends Activity {
// Hashmap for ListView
ArrayList<HashMap<String, String>> PSList = new ArrayList<HashMap<String, String>>();
String status_code_from_prev;
List<HashMap<String, String>> fillMaps=null;
String alert_message;
String quantity_message;
//quantity edittext
EditText quantity_edit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poll_station);
//quantity edittext
quantity_edit = (EditText)findViewById(R.id.qty_editText);
//database insertion
DatabaseHelper db = new DatabaseHelper(this);
ContentValues values = new ContentValues();
try {
db.createDataBase();
values.put("_id", "1");
values.put("name", "rose");
db.insert(values);
} catch (IOException e) {
e.printStackTrace();
}
db.close();
ArrayList<TestItem> PSList = new ArrayList<TestItem>();
try {
db.createDataBase();
PSList = db.getAllData();
} catch (IOException e) {
e.printStackTrace();
}
db.close();
fillMaps = new ArrayList<HashMap<String, String>>();
Iterator<TestItem> i = PSList.iterator();
while(i.hasNext())
{
HashMap<String, String> map = new HashMap<String, String>();
TestItem objPSItem = i.next();
map.put("name", objPSItem.NAME);
map.put("Id", objPSItem.ID);
//map.put("quantity", objPSItem.QUANTITY);
fillMaps.add(map);
}
Log.i("Size: ", ""+fillMaps.size());
//populating listview from database
ListView listView1 = (ListView) findViewById(R.id.poll_list_listView);
if (null != listView1 && null != PSList) {
listView1.setAdapter(new ListAdapter(PollStationActivity.this,
R.id.ListViewContainer, new String[fillMaps.size()]));
}
}
//class for the list and on click handler
class ListAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ListAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.values = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// return super.getView(position, convertView, parent);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.list_layout, parent,
false);
final HashMap<String, String> map = fillMaps.get(position);
TextView textView = (TextView) rowView
.findViewById(R.id.list_label_name);
textView.setText("("+map.get("Id")+") "+map.get("name"));
rowView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rowView.setBackgroundResource(R.drawable.list_bg_pressed);
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
rowView.setBackgroundResource(R.drawable.list_bg);
}
};
handler.postDelayed(r, 200);
//alert box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PollStationActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Please Note!");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to select "+"("+map.get("Id")+") "+map.get("name")+"?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
// Intent intent = new Intent(RegisterFirstActivity.this, RegisterSecondActivity.class);
//
// intent.putExtra("AC_Code", map.get(TAG_CODE));
// RegisterFirstActivity.this.startActivity(intent);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
return rowView;
}
}
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
This is the TestItem class:
public class TestItem {
public String ID;
public String NAME;
public String QUANTITY;
public boolean selected;
// Empty constructor
public TestItem(){
}
// constructor
public TestItem(String id, String name, String quantity){
this.ID = id;
this.NAME = name;
this.QUANTITY = quantity;
}
// constructor
public TestItem(String name, String quantity){
this.NAME = name;
this.QUANTITY = quantity;
}
// getting ID
public String getID(){
return this.ID;
}
// setting id
public void setID(String id){
this.ID = id;
}
// getting name
public String getName(){
return this.NAME;
}
// setting name
public void setName(String name){
this.NAME = name;
}
// getting phone number
public String getQuantity(){
return this.QUANTITY;
}
// setting quantity
public void setQuantity(String quantity){
this.QUANTITY = quantity;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
This is the activity_poll_station.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/main_bg">
<RelativeLayout
android:id="#+id/ListViewContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/poll_label_textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp" >
<ListView
android:id="#+id/poll_list_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
</RelativeLayout>
This is the list_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/library_linear_layout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentLeft="true"
android:background="#drawable/list_bg"
android:padding="5dp" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="44dp"
android:background="#null" >
<TextView
android:id="#+id/list_label_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="name"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="17sp" />
<CheckBox
android:id="#+id/item_checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
<EditText
android:id="#+id/qty_editText"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:maxLines="1"
android:inputType="number" >
</EditText>
</RelativeLayout>
</LinearLayout>
I want to how to extract text from the edittext which I have created for every list item. If I try to extract the text on
rowView.setOnClickListener(new View.OnClickListener()
like this:
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to select "+"("+map.get("Id")+") "+map.get("name")+"Quantity: "+quantity_edit.getText().toString()+"?");
The I am getting a null pointer exception getting generated due to the rowView.setOnClickListener(new View.OnClickListener()
What should I do? What should be the work around?
Thanks in advance!
//------------------------------------------------------------------------------//
Question part: 2
Now I want to do something like, I want to remove a particular row on clicking it. The row will only be deleted from the existing listview and a new list will be shown, how to do that?
Thanks once again!
You first need to get the reference to the EditText object, which you can do by using findViewById
quantity_edit = (EditText) view.findViewById("qty_editText");
you have override getView method of custom adapter. like the following.
public class SimpleAdapter1 extends ArrayAdapter<Data> {
public SimpleAdapter1(Context context, int textViewResourceId,
List<Data> catDesc) {
super(context, textViewResourceId, catDesc);
this.items = (ArrayList<Data>) catDesc;
this.context = context;
itemsid = new ArrayList<Integer>();
System.out.println(items);
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.YourLayout, null);
}
edit = (EditText) v.findViewById(R.id.editText1);
String tx = edit.getText().toString();
return v;
}
}
It will be very simple if you use custom adapter for your listview.
you can see this Custom Adapter for List View
and This one also useful for you how to get EditText value from listview
I have an Adroid Activity and I want to introduce a custom list view. This is my onCreate() activity method.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadListView();
ListView lvw = (ListView)findViewById(android.R.id.list);
lvw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String element = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), AddEntryActivity.class);
// sending data to new activity
i.putExtra("entryToEdit", element);
long idToEdit = Long.parseLong(hEntries.get(position).toString());
i.putExtra("idToEdit", idToEdit);
startActivity(i);
}
});
DbAccess oDb = new DbAccess(this);
}
As you can see LoadListView() method is called to load listview items:
private void LoadListView()
{
oDb = new DbAccess(this);
oDb.open();
List<cAttivita> entries = oDb.getAttivita();
CustomListAdapter listAdapter = new CustomListAdapter(MainActivity.this, android.R.layout.simple_list_item_1 , entries);
ListView lvwAttivita = (ListView)findViewById(android.R.id.list);
lvwAttivita.setAdapter(listAdapter);
hEntries = new HashMap();
for(int i = 0; i < entries.size(); i++)
{
hEntries.put(i, entries.get(i).getId());
}
}
CustomListAdapter class:
public CustomListAdapter(Context context, int textViewResourceId , List<cAttivita> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
if(items.get(position) != null )
{
text.setTextColor(Color.WHITE);
text.setText(items.get(position).toString());
text.setBackgroundColor(Color.RED);
int color = Color.argb( 200, 255, 64, 64 );
text.setBackgroundColor( color );
}
return mView;
}
This is activity_main.xml code:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="20px"
android:paddingTop="10dip"
android:paddingBottom="10dip"/>
<ListView xmlns:android="schemas.android.com/apk/res/android";
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Attività "/>
The problem is in the line:
TextView text = (TextView) mView.findViewById(R.id.textView);
Why text returns null?
Change the following line of code inside your getView() of your CustomAdapter.
TextView text = (TextView) mView.findViewById(android.R.id.text1);
as you are taking android.R.layout.simple_list_item_1 as layout it should be android.R.id.text1 which is declared internally in Android library.
Change my line of code inside getView() and it works for you.
Updated
I'm trying to print the data retrieved from the database on a list view. For a while my application print for each data in the database, a row on the list view. So if there are 10 data in the database, the app prints 10 rows, corresponding to each row of the database. Here is a view of how it is being printed.
The new image of how it looks now:
But, it is not printing the data as I want. I want to print a column of the row in a specific text view, but it doesnt show anything.
So the activity RatedCalss calls the method selectTopCalls() and makes a List receive the list that this method returns. And then I pass this list to the listAdapter.
Well I have this activity named RatedCalls.java:
public class RatedCalls extends Activity {
private static final String LOG_TAG = "RatedCalls";
private CallDataHelper cdh;
private ListView listview;
private ArrayList<String> ratedCallsList;
private MyListAdapter listAdapter;
private View view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(LOG_TAG, "calling from onCreate()");
cdh = new CallDataHelper(this);
startService(new Intent(this, RatedCallsService.class));
setBasicContent();
}
public void setBasicContent() {
listview = (ListView) findViewById(R.id.list_view);
ratedCallsList = this.cdh.selectTopCalls();
Log.i(LOG_TAG, "ratedCallsList size: " + ratedCallsList.size());
listAdapter = new MyListAdapter(this, this, R.id.list_view, ratedCallsList);
listview.setAdapter(listAdapter);
}
}
I have this class, a ListAdapter class named MyListAdapter.java:
public class MyListAdapter extends ArrayAdapter { //--CloneChangeRequired
private ArrayList mList;
private Context mContext;
private Activity mActivity;
private int selectedPos = -1; // init value for not-selected
private ArrayList<String> ratedCallsList;
private CallDataHelper cdh;
public void setSelectedPosition(int pos){
selectedPos = pos;
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
public MyListAdapter(Context context, Activity activity, int textViewResourceId, ArrayList list) {
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
this.mActivity = activity;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null); // --CloneChangeRequired(list_item)
}
// setting STRIP BG
if(position == selectedPos){
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(062, 076, 120) );
}else if(position%2==0){
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(226, 231, 239) );
}else{
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(200, 210, 223) );
}
setViews(position, view);
}catch(Exception e){
//Log.i(MyListAdapter.class.toString(), e.getMessage());
}
return view;
}
public void setViews(int position, View view) {
cdh = new CallDataHelper(mContext);
if(mContext.getClass().equals((RatedCalls.class))){
ratedCallsList = this.cdh.selectTopCalls();
Log.i("MYLISTADAPTER", "size " + ratedCallsList.size());
if (ratedCallsList != null) {
((TextView) view.findViewById(R.id.contact_name)).setText(ratedCallsList.get(0));
((TextView) view.findViewById(R.id.phone_number)).setText(ratedCallsList.get(1));
((TextView) view.findViewById(R.id.duration)).setText(ratedCallsList.get(2));
((TextView) view.findViewById(R.id.date)).setText(ratedCallsList.get(3));
}
}else if(mContext.getClass().equals(RatedContacts.class)){
final PublishersBO listPublisher = (PublishersBO) mList.get(position);
if (listPublisher != null) {
//--setting list_item views
((TextView) view.findViewById(R.id.contact_name)).setText(listPublisher.getName());
((TextView) view.findViewById(R.id.phone_number)).setText(listPublisher.getEmail());
//--onClickListener
view.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(mContext,RatedContacts.class);
myIntent.putExtra("NAME", listPublisher.getName());
myIntent.putExtra("ACTIVITY_NAME", mContext.getClass().toString());
mContext.startActivity(myIntent);
mActivity.finish();
}
});
}
}
}
}
The method that retrieve the data from the database is in a separated class that deals with SQLite function. This is the method:
public ArrayList<String> selectTopCalls() {
ArrayList<String> list1 = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, null, null, null, null, null,
"duration desc");
if (cursor.moveToFirst()) {
do {
//if (cursor.getString(2) != "") {
cdObj = new CallData();
list1.add(cursor.getString(2));
list1.add(cursor.getString(4));
list1.add(cursor.getString(5));
list1.add(cursor.getString(6));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list1;
}
And here is the xml file for the view named list_item.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="67px"
android:id="#+id/rlt_main"
android:layout_toRightOf="#+id/iv_forward">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:id="#+id/iv_forward"
android:src="#drawable/icon"
android:layout_alignParentLeft="true">
</ImageView>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/phone_number"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/iv_forward"
android:layout_alignBottom="#+id/iv_forward">
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/duration"
android:layout_alignBottom="#+id/phone_number"
android:layout_alignRight="#+id/phone_number"
>
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/date"
android:layout_alignBottom="#+id/contact_name"
android:layout_alignRight="#+id/contact_name"
>
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/contact_name"
android:textSize="20px"
android:layout_toRightOf="#+id/iv_forward"
android:layout_alignParentTop="true">
</TextView>
So I'd like to print the data in the text views in the activity, but I dont know where to set the text, in what class, if in the MyListAdapter class or if in the activity.
Thanks.
I have made few changes to your code, check here,
https://gist.github.com/683b84af9d01bf18fe3d
Thanks.........