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.
Related
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.
I would like to use Picasso library to download and show images that are in URL's inside JSON data from my server.
I've lost all hope, I saw something about custom adapter but to no avail.
I need help here.
Here's how I do stuff now to show data from json inside onPostExecute:
protected void onPostExecute(JSONObject objdanejson){
pDialog.dismiss();
try {
android = objdanejson.getJSONArray(TAG_ZAWARTOSC);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
final String akt_tytul = c.getString(TAG_TYTUL);
final String akt_skrot = c.getString(TAG_SKROT);
final String akt_tresc = c.getString(TAG_TRESC);
final String akt_id = c.getString(TAG_ID);
final String akt_IMG = c.getString(TAG_IMG);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TYTUL, akt_tytul);
map.put(TAG_SKROT, akt_skrot);
map.put(TAG_ID, akt_id);
map.put(TAG_TRESC, akt_tresc);
map.put("http://www.apirest.poligon.webimpuls.pl/"+TAG_IMG, akt_IMG);
oslist.add(map);
lista_aktualnosci = (ListView)findViewById(R.id.lista_aktualnosci);
final ListAdapter adapter = new SimpleAdapter(aktualnosci.this, oslist,
R.layout.aktualnosc_item,
new String[]{TAG_TYTUL, TAG_SKROT, TAG_IMG}, new int[]{R.id.aktTytul, R.id.aktSkrot, R.id.aktIMG});
lista_aktualnosci.setAdapter(adapter);
lista_aktualnosci.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(aktualnosci.this, "Kliknąłeś na " + oslist.get(+position).get("akt_tytul"),Toast.LENGTH_SHORT).show();
Intent czytaj = new Intent(aktualnosci.this, aktualnosc_czytaj.class);
czytaj.putExtra("tytuł",oslist.get(+position).get("akt_tytul"));
czytaj.putExtra("tresc",oslist.get(+position).get("akt_tresc"));
czytaj.putExtra("id",oslist.get(+position).get("akt_id"));
startActivity(czytaj);
}
});
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
EDIT:
How my custom controler looks:
oslist.add(map);
lista_aktualnosci = (ListView)findViewById(R.id.lista_aktualnosci);
/* final ListAdapter adapter = new SimpleAdapter(aktualnosci.this, oslist,
R.layout.aktualnosc_item,
new String[]{TAG_TYTUL, TAG_SKROT}, new int[]{R.id.aktTytul, R.id.aktSkrot});
*/
class ListAdapter extends ArrayAdapter<ClipData.Item> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ListAdapter(Context context, int resource, List<ClipData.Item> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.aktualnosc_item, null);
}
ClipData.Item p = getItem(position);
if (p != null) {
aktTytul = (TextView)findViewById(R.id.aktTytul);
aktSkrot = (TextView)findViewById(R.id.aktSkrot);
aktIMG = (ImageView)findViewById(R.id.aktIMG);
}
return v;
}
}
lista_aktualnosci.setAdapter(adapter);
Create a class that extends Simple Adapter or Base Adapter. In getView() the adapter will ask you to create a list item when this is needed. As you create the item you can use Picasso to display the image in whatever image view you've selected for this purpose.
That being said you should ditch ListView and use RecyclerView instead - for which you can find all the information you need here
Other stuff that may improve your code are things like Retrofit and Gson.
Does that help?
you can get your image from listview. You can this code your activity after set adapter then you can set your imageview.
for(int i = 0; i < this.listView.getChildCount(); i ++) {
View view = this.listView.getChildAt(i);
ImageView img= (ImageView)view.findViewById(R.id.yourimage);
//do something your image
}
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... :) )
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);
}
I am having trouble with an update to the data in an ArrayAdapter in a ListView and even on listAdapter.notifyDataSetChanged() the changes are not being reflected in the ListView.
Whats interesting is that the initial load is fine, i get the full list of data rendered in the ListView. It is when i load the activity for the second time, where the cached ArrayList gets passed to the setDataList() method doesn't get rendered. The resulting ListView only contains the single default entry setup in the onCreate() method.
I have debugged the code and stepped through the runnable and it appears to run as i would have expected, just without the end result.
If anyone could help with this i would really appreciate it, i have googled it to death!
My code snippets:
public class CriteriaOriginIncludeActivity extends Activity {
private CriteriaOriginIncludeController m_controller;
private CriteriaOriginIncludesAdapter m_listAdapter;
private ArrayList<OriginRowData> m_listData;
private ListView m_originList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.criteria_origin_includes);
ArrayList<OriginRowData> list = new ArrayList<OriginRowData>();
list.add(new OriginRowData(new Origin(0,""), false));
m_listAdapter = new CriteriaOriginIncludesAdapter(this,
R.layout.origin_include_list_row,
R.id.lst_origin_include,
list);
m_originList = (ListView) this.findViewById(R.id.lst_origin_include);
m_originList.setAdapter(m_listAdapter);
m_controller = new CriteriaOriginIncludeController(this);
}
public void setOriginList(ArrayList<OriginRowData> list) {
if (list != null && list.size() > 0) {
m_listData = list;
} else {
m_listData = new ArrayList<OriginRowData>();
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
public void run() {
m_listAdapter.clear();
if(m_listData != null && m_listData.size() > 0){
m_listAdapter.notifyDataSetChanged();
for(int i=0;i<m_listData.size();i++)
m_listAdapter.add(m_listData.get(i));
}
m_listAdapter.notifyDataSetChanged();
}
};
}
And the adapter:
public class CriteriaOriginIncludesAdapter extends ArrayAdapter<OriginRowData> {
private ArrayList<OriginRowData> m_items;
private Context m_context;
public CriteriaOriginIncludesAdapter(Context context, int resourceId, int textViewResourceId, ArrayList<OriginRowData> list) {
super(context, resourceId, textViewResourceId, list);
this.m_context = context;
m_items = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.origin_include_list_row, null);
}
OriginRowData o = m_items.get(position);
if (o != null) {
TextView txtName = (TextView) v.findViewById(R.id.txt_origin_include_name);
TextView txtId = (TextView) v.findViewById(R.id.txt_origin_include_id);
CheckBox chkOrigin = (CheckBox) v.findViewById(R.id.chk_origin);
if (txtName != null) {
txtName.setText(o.getOrigin().getOrigin());
}
if (txtId != null) {
txtId.setText(Integer.toString(o.getOrigin().getId()));
}
if (chkOrigin != null) {
chkOrigin.setChecked(o.getInclude());
chkOrigin.setOnClickListener(new OriginIncludeOnClickListener(position));
}
}
return v;
}
}
You need to override ArrayAdapter's Add() method.
Since you are using your own private private ArrayList<OriginRowData> m_items;, default Add() method does not know that it has to add the data into this array list.
And in your getView you are using m_items array, So this needs to be updated. The default Add() method will add the items to the ArrayAdapter's inbuilt