Android:Inserting 1 value to Checkbox, but it's shows 2 values? - android

I just want to ask something about showing data to checkbox, right now, I just have successful to showing data into checbox but, now I get trouble, when I have 1 data in my database, the checkbox show 2 data? here's my example database
Table Jurusan
id | nama
1 ipa
then I have function to read this database
public ArrayList<Jurusan> getAllLabel_jurusan()
{
ArrayList <Jurusan> point = new ArrayList<Jurusan>();
String selectQuery = "SELECT id, nama_jurusan from jurusan";
Cursor c = database.rawQuery(selectQuery, null);
if( c.moveToFirst() );
do
{
Jurusan j = new Jurusan();
j.setId(c.getLong(0));
j.setNama_jurusan(c.getString(1));
// adding to todo list
point.add(j);
}
while(c.moveToNext());
return point;
}
and this is my MainActivity
public class MainActivity extends Activity implements OnItemSelectedListener
{
Button myButton;
String tmp_nama;
long id_tampung;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button) findViewById(R.id.findSelected);
displayListView();
checkButtonClick();
}
private void displayListView()
{
ArrayList<Jurusan> stateList = dataSource.getAllLabel_jurusan();
//GETTING THE DATA FROM DATABASE
id_tampung = stateList.get(0).getId();
tmp_nama = stateList.get(0).getNama_jurusan().toString();
//THE SET INTO CONSTRUCTOR
Jurusan _states = new Jurusan(id_tampung, tmp_nama);
//ADD TO ARRAY
stateList.add(_states);
// create an ArrayAdaptar from the String Array
//SETTING INTO CustomAdapter
dataAdapter = new MyCustomAdapter(this, R.layout.state_info,stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
private class MyCustomAdapter extends ArrayAdapter<Jurusan>
{
private ArrayList<Jurusan> stateList;
public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<Jurusan> stateList)
{
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<Jurusan>();
this.stateList.addAll(stateList);
}
private class ViewHolder
{
TextView id;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.state_info, null);
holder = new ViewHolder();
holder.id = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Jurusan state = stateList.get(position);
holder.id.setText(" (" + state.getId() + ")");
holder.name.setText(state.getNama_jurusan());
holder.name.setTag(state);
return convertView;
}
}
My question is, the checkbox should showing 1 data from database, but when i run this code, the checkbox is showing 2 data with same value, can anybody help me?
example:
checbox1 (value:ipa)
checkbox2 (value:ipa)
i hope it should be like this...
checkbox1 (value:ipa)

In your displayListView(), you're duplicating the first entry in the stateList:
ArrayList<Jurusan> stateList = dataSource.getAllLabel_jurusan();
if(stateList.size()>0)
{
//GETTING THE DATA FROM DATABASE
id_tampung = stateList.get(0).getId();
tmp_nama = stateList.get(0).getNama_jurusan().toString();
//THE SET INTO CONSTRUCTOR
Jurusan _states = new Jurusan(id_tampung, tmp_nama);
//ADD TO ARRAY
stateList.add(_states);
}
I don't know what your intention here is but you probably could just remove this if block altogether.

The problem is in your code, you are add double values in your code. i added my comment before line of code.
//statelist contains an arraylist with your required data.
ArrayList<Jurusan> stateList = dataSource.getAllLabel_jurusan();
//you are checking here for zero.
if(stateList.size()>0)
{
//GETTING THE DATA FROM DATABASE
//here you are get id;
id_tampung = stateList.get(0).getId();
//here you are get name;
tmp_nama = stateList.get(0).getNama_jurusan().toString();
//THE SET INTO CONSTRUCTOR
//making an object of jurusan
Jurusan _states = new Jurusan(id_tampung, tmp_nama);
//ADD TO ARRAY
// and adding again the same arraylist. so that cause duplication.
//stateList already contained the data , which are you add this line.
stateList.add(_states);
}
yes , please replace the function displayListView as below.
private void displayListView()
{
ArrayList<Jurusan> stateList = dataSource.getAllLabel_jurusan();
/*
//GETTING THE DATA FROM DATABASE
id_tampung = stateList.get(0).getId();
tmp_nama = stateList.get(0).getNama_jurusan().toString();
//THE SET INTO CONSTRUCTOR
Jurusan _states = new Jurusan(id_tampung, tmp_nama);
//ADD TO ARRAY
stateList.add(_states);*/
// create an ArrayAdaptar from the String Array
//SETTING INTO CustomAdapter
dataAdapter = new MyCustomAdapter(this, R.layout.state_info,stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}

Related

android listview spinner when scroll

I have a custom ListView with Spinner that fill with a ListArray.
It works fine without ListView Scroll
But when I add some items to my custom ListView and I select one item of first or second on my Spinner and I scroll down my ListView (until that row disappear) I see another Spinner on bottom items will selected (like the upper)
My selection kept but another Spinner on bottom ListView be select
My code is :
public class SoundListView extends ArrayAdapter<String>{
List<String> DataList;
private final Activity context;
private ViewGroup vg;
int startTimer, stopTimer,rPosition;
String fileTagName = "",externalTagFileName = "",tagFileName= "",fileName = "";
public SoundListView (Activity context, ArrayList arrSubject, ArrayList arrDurationSplit, ArrayList ids,ArrayList arrFileName,ArrayList arrDuration,ArrayList arrIdTag,ArrayList arrTagName,ArrayList arrMainId,ArrayList arrStartTime, ArrayList arrStopTime) {
super(context, R.layout.activity_list, arrSubject);
this.context = context;
this.arrSubject = arrSubject;
this.arrDurationSplit = arrDurationSplit;
this.arrIdTag = arrIdTag;
this.arrDuration = arrDuration;
this.arrTagName = arrTagName;
this.arrMainId = arrMainId;
this.arrStartTime = arrStartTime;
this.arrStopTime = arrStopTime;
this.arrFileName = arrFileName;
this.ids = ids;
}
private ArrayList arrSubject = new ArrayList();
private ArrayList arrDurationSplit = new ArrayList();
private ArrayList ids = new ArrayList();
private ArrayList arrIdTag = new ArrayList();
private ArrayList arrTagName = new ArrayList();
private ArrayList arrMainId = new ArrayList();
private ArrayList arrStartTime = new ArrayList();
private ArrayList arrStopTime = new ArrayList();
private ArrayList arrDuration = new ArrayList();
private ArrayList arrFileName = new ArrayList();
final private ArrayList<String> arrayTasPath = new ArrayList<String>();
static class ViewHolder {
ImageView imgPlaySound,imgShareList;
TextView txtCaption,txtDynamicTimer,txtDurationSplit,txtTotalTimer,txtHiden;
Spinner spTags;
SeekBar seekBar1;
LinearLayout linearSeek;
int position;
}
#Override
public View getView(final int position,View convertView, final ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
vg = parent;
final ArrayList arrTagNameTemp = new ArrayList();
final ArrayList arrStartTimeTemp = new ArrayList();
final ArrayList arrStopTimeTemp = new ArrayList();
arrTagNameTemp.add("all");
final ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview, null);
viewHolder = new ViewHolder();
viewHolder.position = position;
viewHolder.txtCaption = (TextView) convertView.findViewById(R.id.txtCaption);
viewHolder.txtDynamicTimer = (TextView) convertView.findViewById(R.id.txtDynamicTimer);
viewHolder.txtDurationSplit = (TextView) convertView.findViewById(R.id.txtTotalTimer);
viewHolder.imgPlaySound = (ImageView) convertView.findViewById(R.id.imgPlaySound);
viewHolder.imgShareList = (ImageView) convertView.findViewById(R.id.imgShareList);
viewHolder.linearSeek = (LinearLayout) convertView.findViewById(R.id.linearSeek);
viewHolder.spTags = (Spinner) convertView.findViewById(R.id.spTags);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, arrTagNameTemp);
viewHolder.spTags.setAdapter(adapter);
viewHolder.spTags.setSelection(0);
final int duration = Integer.valueOf(arrDuration.get(position).toString());
for(int i = 0; i < arrMainId.size(); i++)
{
if (Integer.valueOf(arrMainId.get(i).toString()) == Integer.valueOf(ids.get(position).toString()))
{
arrTagNameTemp.add(arrTagName.get(i));
arrStartTimeTemp.add(arrStartTime.get(i));
arrStopTimeTemp.add(arrStopTime.get(i));
}
}
//////////////////////////////////////////////////////////////////////////////
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txtCaption.setText(arrSubject.get(position).toString());
return convertView;
}
Can anybody help me?
First of all just tell me why are you using that much arraylists, can't you just use a single one with custom data type. In that single array all your values will be associated to each other and it will easy to manage them.
The solution for your issue that I can suggest is to create a single ArrayList with custom data type including all your values of all arraylists given above. And don not initialize your Array in Adapter. Initialize and add values where you are setting Adapter (In your Activity). you have to add a parameter in your main array let's say "selectedValue", by default it will be "all" but when user will select some value you will update the value of item on that specific position.
And then in your getView method you will check the value of "selectedValue" for each item, if it is equals to "all" then you will set it otherwise you will set the value of "selectedValue" to your spinner. Just keep one thing in mind you have to set a value to spinner of each item in both if and else clause.

How to add multiple items in Listview Android

I'm working on an Android application of booking medicine offline. I have used ListView for Cart, but whenever I add a new item in cart, my previous item get replaced.
L1 = imageacidity
L2 = imagecough
if(msg.toString().equals("L1")) {
adapter = new ContactImageAdapter(this, R.layout.list, imageacidity);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
if(msg.toString().equals("L2"))
{
adapter = new ContactImageAdapter(this, R.layout.list, imagecough);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Here I have 5 elements in imageacidity and Imagecough Array. Whenever I select 1 item, it gets added in cart, but when I try to select another item it get replaced with new one.
You have to Add the element inside your adapter.
I will post a custom Adapter and show you how to add elements properly.
Adapter:
public class YourAdapter extends BaseAdapter {
List<String> itens;
private Context mContext;
private static LayoutInflater inflater = null;
public YourAdapter(Context context, List<String> itens){
this.itens = itens;
mContext = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return itens.size();
}
public String getItem(int position) {
return itens.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, parent, false);
String msg = itens.get(position);
TextView tx = vi.findViewById(R.id.your_id);
tx.setText(msg);
return vi;
}
public void addItem(String item){
itens.add(item);
}
public void addItens(List<String> itens){
this.itens.addAll(itens);
}
}
ListView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new CustomAdapter(this,yourListOfItens);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
You can set initial data on constructor of adapter, or use methods addItem and addAll on a click button for example.
The problem you are describing of the data being removed is happening because making a new ContactImageAdapter and calling setAdapter, which will completely remove the data that was already in the ListView.
If you want to properly implement the code in the question, you need something like this.
String msg = ""; // TODO: get this String value
ListView dataList = (ListView) findViewById(R.id.list);
// TODO: Define a single List to store the data and use that in *one* adapter
List<Contact> contacts = new ArrayList<Contact>();
adapter = new ContactImageAdapter(this, R.layout.list, contacts);
dataList.setAdapter(adapter);
// TODO: Replace this with the object to add to the adapter
Contact contact = null;
if(msg.equals("L1")) {
// TODO: Use whatever values you want for "L1"
int img = R.drawable.bati_acidity_1;
String name = "Amlapitta";
String price = "price 170";
contact = new Contact(img, name, price);
}
else if(msg.equals("L2")) {
// TODO: Use whatever values you want for "L2"
int img = R.drawable.bati_acidity_2;
String name = "Amlapitta2";
String price = "price 270";
contact = new Contact(img, name, price);
}
if (contact != null) {
contacts.add(contact);
adapter.notifyDataSetChanged();
}
Another problem is that you are calling notifyDataSetChanged without actually changing the datasets of imageacidity or imagecough.
You can use an algorithm (logic) on the InputListAdapter checking and verifying if there is a MedicineVO (Value Object Pattern) item on old list before the calling notyChange(..) method. In addition, you can wrapping the logic in other class such as MedicineLogic to improve the adapter readability.
See the sample code below:
public class MedicineInputListAdapter extends ArrayAdapter<MedicineVo> {
public static final int[] COLORS = new int[] { Color.WHITE, Color.BLUE };
private Context mContext;
private List<MedicineVo> medicineVos;
private MedicineVo medicineVoActual;
public BasePreOSPreventivaCorretivaInputListAdapter(Context context, int resource, List<MedicineVo> medicineVos) {
super(context, resource, medicineVos);
this.medicineVoActual = new MedicineVo();
this.medicineVos = new ArrayList<MedicineVo>();
this.medicineVos.addAll(medicineVos);
this.mContext = context;
}
private static class ViewHolder {
TextView mMedicineTextView;
//------------------------------------------------------
// others Android view components
//------------------------------------------------------
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
//------------------------------------------------------
// mapper from xml to view and add itens to holder
//------------------------------------------------------
//------------------------------------------------------
// add event action to the mMedicineTextView
//------------------------------------------------------
viewHolder.mMedicineTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView textView = (TextView) view;
MedicineVo medicineVo = (MedicineVo) textView.getTag();
boolean selected = medicineVo.getSelected();
if (selected) {
/*do it*/
}
refreshPreOSMaterialWhenUpdate(preOSMaterialVo);
}
});
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
//------------------------------------------------------
// get item and adjust color
//------------------------------------------------------
MedicineVo item = getItem(position);
/*do it*/
return convertView;
}
public void refreshMedicineListWhenUpdate(MedicineVo medicineVo){
List<MedicineVo> newMedicineVos = new ArrayList<MedicineVo>();
for (MedicineVo medicineVoOnList : medicineVos) {
if( StringUtils.isNull(medicineVoOnList.getId()) )
continue;
if( MedicineLogic.existsOnList(medicineVos, medicineVoOnList) )
continue;
/* others checks if necessary */
newMedicineVos.add(medicineVoOnList);
}
medicineVos.addAll(newMedicineVos);
}
}
If you can't select more but only one item of your ListView, this might help.As others have commented on the question, changing the adapter of a ListView can clear the selection too, but as I supposed the code you've posted is inside onCreate (or other kind of initialization) so setting the adapter there won't affect the selection (since there can't be selection without items... :) )

refresh listview after data has changed from custom adapter

I have seen several posts on this but I cannot seem to follow one well enough to fix my problem.
I am trying to refresh my ListView after I update or delete a record. I am currently using notifyDataSetChanged() however it does not refresh upon deletion. I can delete, and then if i back our and reload my history.java it will show the updates because I am reloading all of the data.
here is my HistoryAdapter.java
public class HistoryAdapter extends BaseAdapter {
private Context mContext;
Cursor cursor;
history historyClass = new history();
MySQLiteHelper db;
public HistoryAdapter(Context context, Cursor cur){
super();
mContext = context;
cursor = cur;
db = new MySQLiteHelper(context);
}
public int getCount(){
// return the number of records in cursor
return cursor.getCount();
}
// getView method is called for each item of ListView
public View getView(final int position, View view, ViewGroup parent){
// inflate the layout for each item of listView
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.history_list_item, null);
// move the cursor to required position
cursor.moveToPosition(position);
final String id = cursor.getString(cursor.getColumnIndex("_id"));
final long deleteId = Long.parseLong(id);
// fetch the information for each card
String pricePerGallon = cursor.getString(cursor.getColumnIndex("pricePerGallon"));
String gallons = cursor.getString(cursor.getColumnIndex("gallons"));
String odometer = cursor.getString(cursor.getColumnIndex("odometer"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String filledOrNot = cursor.getString(cursor.getColumnIndex("filledOrNot"));
String comments = cursor.getString(cursor.getColumnIndex("comments"));
//String milesPerGallon = cursor.getString(cursor.getColumnIndex("miledPerGallon"));
String totalSpent = cursor.getString(cursor.getColumnIndex("totalSpent"));
// get the reference of TextViews
TextView textViewPricePerGallon = (TextView) view.findViewById(R.id.cardPrice);
TextView textViewGallons = (TextView) view.findViewById(R.id.cardGallons);
TextView textViewOdometer = (TextView) view.findViewById(R.id.cardOdometer);
TextView textViewDate = (TextView) view.findViewById(R.id.cardDate);
TextView textViewFilledOrNot = (TextView) view.findViewById(R.id.cardFilledOrNot);
TextView textViewComments = (TextView) view.findViewById(R.id.cardComments);
//TextView textViewMilesPerGallon = (TextView) view.findViewById(R.id.mpg);
TextView textViewTotalSpent = (TextView) view.findViewById(R.id.usd);
TextView textViewDeleteButton = (TextView) view.findViewById(R.id.deleteButton);
// Set the data to each TextView
textViewPricePerGallon.setText(pricePerGallon);
textViewGallons.setText(gallons);
textViewOdometer.setText(odometer);
textViewDate.setText(date);
textViewFilledOrNot.setText(filledOrNot);
textViewComments.setText(comments);
//textViewMilesPerGallon.setText(milesPerGallon);
textViewTotalSpent.setText(totalSpent);
final HistoryAdapter historyAdapter = this;
textViewDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("History Adapter", "" + deleteId);
//need to delete here
deleteRecord(deleteId);
historyAdapter.notifyDataSetChanged();
}
});
return view;
}
public Object getItem(int position){
return position;
}
public long getItemId(int position){
return position;
}
private void deleteRecord(long id){
db.deleteGasLog(id);
}
}
here is my history.java which sets the adapter and creates the listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
context = this;
initViews();
cursor = db.getAllLogs();
// Create the Adapter
historyAdapter = new HistoryAdapter(this, cursor);
// Set the adapter to ListView
listContent.setAdapter(historyAdapter);
}
I guess you will need to get a new cursor.
Try moving this
cursor = db.getAllLogs();
into the adapter and call it again before the notifyDataSetChanged() call.
You are deleting the row but you are never updating or getting a new cursor, which has the result set the adapter uses to layout the list. You need to give the adapter a new cursor after you delete a row, then call notifyDatasetChanged(). If you use SimpleCursorAdapter
instead of BaseAdapter, you can use its swapCursor() method to set the new cursor.
Make sure to call:
registerDataSetObserver(...)
from your BaseAdapter subclass.
Pass it the reference to your DataSetObserver implementation. Possibly through an inner class of HistoryAdapter:
public class HistoryAdapter extends BaseAdapter {
. . .
public class MyDataSetObserver extends DataSetObserver {
public void onChanged() {
// Data Set changed.... do something...
}
public void onValidated() {
// Your implementation here
}
}
. . .
public HistoryAdapter(Context context, Cursor cur) {
. . .
registerDataSetObserver(new MyDataSetObserver());
. . .
}
}
HTH

arrayadapter error when created outside onCreate

I have an ArrayAdapter that I use to fill a listview, but I'm unable to create it outside the oncreate event, but at that time I don't have the data.
public class CusPickup extends Activity {
private OrdersReady orderready_data[];
private ListView lView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orders);
Here I will get a null point exception.
OrderReadyAdapter adapter = new OrderReadyAdapter(this,R.layout.listview_item_row, orderready_data);
lView = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
lView.addHeaderView(header);
lView.setAdapter(adapter);
getData();
}
}
Here I get the data from HTTP get.
private final Handler handler = new Handler() {
#Override
public void handleMessage(final Message msg) {
progressDialog.dismiss();
String bundleResult = msg.getData().getString("RESPONSE");
int TotalRecords = myResult.d.results.size();
for (int i = x; i < TotalRecords; i++ ) {
orderready_data[i] = new OrdersReady(myResult.d.results.get(i).myStr, myDate ,invResult.d.results.get(i).numberStr, invResult.d.results.get(i).qtyInt, myAmount)
}
}
}
If I place the OrderReadyAdapter her I get a code error with a fix "change OrderReadyAdapter(Context, Int, OrdersReady[]) to OrderReadyAdapter(Handle, Int, OrdersReady[]) if I change it I will get more errors.
Also I'm not sure if my declaration of the private OrdersReady orderready_data[] is correct, because if I declare it in code I would declare it like this: OrdersReady orderready_data[] = new OrdersReady[TotalRecords];
Thanks for any help.
New Adapter
public class OrderReadyAdapter extends ArrayAdapter<OrdersReady>{
Context context;
int layoutResourceId;
ArrayList<OrdersReady> data = null;
public OrderReadyAdapter(Context context, int layoutResourceId, ArrayList<OrdersReady> orderReadyArray) {
super(context, layoutResourceId, orderReadyArray);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = orderReadyArray;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OrderHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OrderHolder();
holder.mytxt1 = (TextView)row.findViewById(R.id.mytxt1);
holder.mytxt2 = (TextView)row.findViewById(R.id.mytxt2);
holder.mytxt3 = (TextView)row.findViewById(R.id.mytxt3);
holder.mytxt4 = (TextView)row.findViewById(R.id.mytxt4);
holder.mytxt5 = (TextView)row.findViewById(R.id.mytxt5);
row.setTag(holder);
}
else
{
holder = (OrderHolder)row.getTag();
}
OrdersReady orderready = data.get(position);
holder.mytxt1.setText(orderready.place);
holder.mytxt2.setText(orderready.Date);
holder.mytxt3.setText(orderready.invoice);
holder.mytxt4.setText(String.valueOf(orderready.Qty));
holder.mytxt5.setText(String.valueOf(orderready.Amount));
return row;
}
static class OrderHolder
{
TextView mytxt1;
TextView mytxt2;
TextView mytxt3;
TextView mytxt4;
TextView mytxt5;
}
}
I suggest you change the OrdersReady[] into ArrayList. Initialize it in your onCreate method. Also make the orderReady adapter into a class field.
orderReadyArray = new ArrayList<OrderReady>();
ordersReadyAdapter = new OrderReadyAdapter(this,R.layout.listview_item_row, orderReadyArray);
lView = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
lView.addHeaderView(header);
lView.setAdapter(ordersReadyAdapter);
This should initialize an empty listview as you don't have the data yet.
When you receive OrdersReady data from the server, update orderReadyArray as such:
orderReadyArray.clear(); // remove old data
for (int i = x; i < TotalRecords; i++ ) {
orderReadyArray.add(data); // add new data one by one
}
ordersReadyAdapter.notifyDataSetChanged(); // this forces the listview to repaint
Alternatively:
You can create a new adapter and assign it to the listview once you receive the data:
List<OrderReady> orderReadyArray = new ArrayList<OrderReady>(); // create a new array to hold data
for (int i = x; i < TotalRecords; i++ ) {
orderReadyArray.add(data); // add new data one by one
}
OrderReadyAdapter ordersReadyAdapter = new OrderReadyAdapter(this,R.layout.listview_item_row, orderReadyArray);
lView.setAdapter(ordersReadyAdapter);
This should update your list. If you still do not see the items, the problem is in the adapter, perhaps you are inflating the row incorrectly in getView() method.

getView not getting called?

I have an adapter that extends simplecursoradapter. The new view is supposed to take a cursor from a database along with an image, populate a list with a couple of checkboxes. For some reason I can't seem to see, my getView is not even being called. I have a breakpoint inside getView and it never gets there and the list just shows up empty.
Can anyone take a look thru and see what I've done wrong
public class TakeStudentAttendance extends ListActivity {
private gradeBookDbAdapter mDbHelper;
private Long mRowId;
private TextView mNameText;
private String classname;
private Boolean new_attendance = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor stud;
mDbHelper = new gradeBookDbAdapter(this);
mDbHelper.open();
mRowId = (savedInstanceState == null) ? null
: (Long) savedInstanceState
.getSerializable(gradeBookDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras
.getLong(gradeBookDbAdapter.KEY_ROWID) : null;
}
// pull in class data
stud = mDbHelper.fetchClass(mRowId);
startManagingCursor(stud);
classname = stud.getString(
stud.getColumnIndexOrThrow(gradeBookDbAdapter.KEY_CLASSNAME));
String title = "Attendance for " + classname;
setTitle(title);
setContentView(R.layout.attendance_list);
Button doneButton = (Button) findViewById(R.id.Done);
doneButton.setOnClickListener(mAttendanceActivity);
// check previous attendance date
String prevdate = stud.getString(
stud.getColumnIndexOrThrow(gradeBookDbAdapter.KEY_PREVDATE));
stud = mDbHelper.fetchAttendanceByClass(mRowId); // this query yields _id, name,
// attend, late, dtime
if (mDbHelper.getClassDate() == prevdate){
// previous date is the same, so we're doing attendance again: retain values
new_attendance = false;
}
else {
// dates are different, so we're starting from scratch and all students are
// absent until counted present. I just need names and will populate attendance
new_attendance = true;
// upon attendance start-up, NO ONE is present. Set all entries in DB to not present (0)
setNoAttend(stud, mRowId);
// reset cursor position
stud.moveToFirst();
}
// Create an array to specify the fields we want to display in the list
String[] from = new String[]{gradeBookDbAdapter.KEY_NAME,
gradeBookDbAdapter.KEY_ROWID,
gradeBookDbAdapter.KEY_ATTEND,
gradeBookDbAdapter.KEY_LATE,
gradeBookDbAdapter.KEY_DTIME};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.stuname,
R.id.stuIndex,
R.id.attend,
R.id.late,
R.id.stuIndex};
// Now create a simple cursor adapter and set it to display
// mRowId holds the class index.
MyDataAdapter studs =
new MyDataAdapter(this, R.layout.show_attendance, stud, from, to, mRowId, new_attendance);
setListAdapter(studs);
}
Here's my adapter code:
public class MyDataAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
private Long classnum;
private gradeBookDbAdapter mDbHelper;
private Boolean newValues;
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<Boolean> itemCheckedHere = new ArrayList<Boolean>();
private ArrayList<Boolean> itemCheckedLate = new ArrayList<Boolean>();
private ArrayList<Integer> itemCheckedIdx = new ArrayList<Integer>();
int idxCol;
int idx;
// itemChecked will store the position of the checked items.
public MyDataAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, Long mRowId, Boolean new_attendance) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
mDbHelper = new gradeBookDbAdapter(context);
mDbHelper.open();
classnum = mRowId;
newValues = new_attendance;
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
itemCheckedHere.add(i, false); // initializes all items value with false
itemCheckedLate.add(i, false); // initializes all items value with false
}
}
public View getView(final int pos, View inView, ViewGroup parent) {
File file;
ImageView studentPhoto;
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(R.layout.show_attendance, null);
}
// set up name field
final TextView studentName = (TextView) inView.findViewById(R.id.stuname);
final TextView studentIndex = (TextView) inView.findViewById(R.id.stuIndex);
if (studentName != null)
{
c.moveToPosition(pos);
int index = c.getColumnIndex(gradeBookDbAdapter.KEY_NAME);
String name = c.getString(index);
studentName.setText(name);
index = c.getColumnIndex(gradeBookDbAdapter.KEY_STUDENT);
String Index = c.getString(index);
studentIndex.setText(Index);
// set up photo icon
file = new File(Environment.getExternalStorageDirectory () +
"/gradeBook/" + name + ".jpg");
studentPhoto = (ImageView) inView.findViewById(R.id.icon);
if (file.exists()) {
String fileName = file.getAbsolutePath();
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm;
bm = BitmapFactory.decodeFile(fileName, opts);
studentPhoto.setImageBitmap(bm);
}
else {
// use icon image
studentPhoto.setImageResource(R.drawable.person_icon);
}
}
final CheckBox cBoxH = (CheckBox) inView.findViewById(R.id.attend);
final CheckBox cBoxL = (CheckBox) inView.findViewById(R.id.late);
cBoxH.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.attend);
if (cb.isChecked()) {
itemCheckedHere.set(pos, true);
int Index = new Integer(studentIndex.getText().toString());
mDbHelper.insertAttend(Index, classnum, 1 );
} else if (!cb.isChecked()) {
itemCheckedHere.set(pos, false);
int Index = new Integer(studentIndex.getText().toString());
mDbHelper.deleteAttend(Index, classnum );
}
}
});
cBoxL.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.late);
if (cb.isChecked()) {
itemCheckedLate.set(pos, true);
// do some operations here
} else if (!cb.isChecked()) {
itemCheckedLate.set(pos, false);
// do some operations here
}
}
});
cBoxH.setChecked(itemCheckedHere.get(pos)); // this will Check or Uncheck the
cBoxL.setChecked(itemCheckedLate.get(pos)); // this will Check or Uncheck the
// CheckBox in ListView
// according to their original
// position and CheckBox never
// loss his State when you
// Scroll the List Items.
return inView;
}
}
This got answered in the comment, but it might as well get a real answer ^^
getCount() is actually returning 0, so the problem is in the query coming back empty, and not in the adapter.
There can be another reason, why getView is never called. In my case I had two elements in LinearLayout - TextView and ListView. The attribute layout_height of TextView was set to fill_parent and ListView element was out of screen bounds because of this. As getView method is called only when ListView item becomes visible to user, so it has never been called. Changing layout_height property to wrap_content solved this problem.
Another thing is to make sure you have called setContentView() with the appropriate argument.

Categories

Resources