Android Fragment BaseAdapter not working - android

This code works correctly in Activity,I change allContexts with getActivity()
but when copy it to Fragment after adapter=new ListViewAdapter(getActivity(), arraylist); gets error When mylist.setAdapter(adapter) is running, , my error for class ListViewAdapter
How to resolve this?
Fragment
public class Fragment1 extends Fragment {
DataBaseHelper myDbHelper;
ListView mylist;
ArrayList<String> iran,arr_intityid,arrshomare,primarykeyarrlist;
String[] fa,mysid,myshomare,primarykeyarr;
SQLiteDatabase db;
Cursor mCursor;
int translate;
EditText mysearch;
int [] favorit;
ArrayList<Integer> favor;
ListViewAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myview = inflater.inflate(R.layout.search_fragment, container, false);
mylist=(ListView) myview.findViewById(R.id.mylist);
return myview;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDbHelper = new DataBaseHelper(getActivity().getApplicationContext());
myDbHelper = new DataBaseHelper(getActivity());
iran=new ArrayList<String>();
arr_intityid=new ArrayList<String>();
arrshomare=new ArrayList<String>();
primarykeyarrlist=new ArrayList<String>();
favor=new ArrayList<Integer>();
try {
myDbHelper.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}
catch (SQLException sqle) {
sqle.printStackTrace();
}
ArrayList<myitems> arraylist = new ArrayList<myitems>();
db = myDbHelper.getReadableDatabase();
mCursor= db.rawQuery("SELECT field_translation_id_value,title,translate,my_id,favorites FROM khotbe"
+ " WHERE translate =1 ORDER BY field_translation_id_value ASC ;",null);
int i = 1;
mCursor.moveToFirst();
while (mCursor.isAfterLast() == false) {
iran.add(mCursor.getString(1));
arr_intityid.add(mCursor.getString(0));
primarykeyarrlist.add(mCursor.getString(3));
favor.add(mCursor.getInt(4));
arrshomare.add(""+i++);
mCursor.moveToNext();
}
fa= new String [iran.size()];
fa=iran.toArray(fa);
mysid= new String [arr_intityid.size()];
mysid=arr_intityid.toArray(mysid);
primarykeyarr= new String [primarykeyarrlist.size()];
primarykeyarr=primarykeyarrlist.toArray(primarykeyarr);
myshomare=new String[arrshomare.size()];
myshomare=arrshomare.toArray(myshomare);
favorit =new int[favor.size()];
for (int t= 0; t < favor.size(); t++) {
favorit[t]=favor.get(t).intValue();
}
mCursor.moveToPosition(0);
for (int j = 0; j < fa.length; j++) {
myitems qqq= new myitems(fa[j],mysid[j],myshomare[j],primarykeyarr[j],favorit[j]);
arraylist.add(qqq);
}
Log.i("sssssss",getActivity()+"");
adapter=new ListViewAdapter(getActivity(), arraylist);
Log.i("sssssss", "2222222222222");
mylist.setAdapter(adapter);
}
class ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
LayoutInflater inflater;
private List<myitems> worldpopulationlist = null;
private ArrayList<myitems> arraylist;
int myfavorit =0;
public ListViewAdapter(Context context, List<myitems> worldpopulationlist) {
// mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(getActivity());
this.arraylist = new ArrayList<myitems>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
Button btn;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public myitems getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.myitems_list, null);
holder.rank = (TextView) view.findViewById(R.id.txt25);
holder.btn=(Button) view.findViewById(R.id.btnfavor);
holder.country = (TextView) view.findViewById(R.id.txt26);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.rank.setText(worldpopulationlist.get(position).gettitle());
holder.country.setText(worldpopulationlist.get(position).getshomare()+"-");
if(myfavorit==0){
holder.btn.setBackgroundResource(R.drawable.ic_launcher);
}
else{
holder.btn.setBackgroundResource(R.drawable.star);
}
return view;
}
}

because the method onCreate triggered earlier than onCreateView
It must be so in the method onCreateView
mylist=(ListView) myview.findViewById(R.id.mylist);
adapter = new ListViewAdapter(getActivity(), arraylist);
mylist.setAdapter(adapter);
P.S. Please visit http://developer.android.com/guide/components/fragments.html
and
https://source.android.com/source/code-style.html

Related

android: listview load incorrectly

My listview load properly but when I go back to my MainActivity then again go to ViewAll activity then it load incorrectly like below.
Here is my ViewAll activity where I have load list view.
public class ViewAll extends Activity {
private ListView listView;
public ArrayList<Model> arrayList;
private Database_Handler database_handler;
private SQLiteDatabase db;
private MyAdapter adapter;
private SwipeRefreshLayout swipeContainer;
private long i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
listView = (ListView) findViewById(R.id.listView);
swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
addNewData();
database_handler = new Database_Handler(ViewAll.this);
db = database_handler.getReadableDatabase();
arrayList = database_handler.getAllContacts();
adapter = new MyAdapter(ViewAll.this, arrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
try {
database_handler = new Database_Handler(ViewAll.this);
db = database_handler.getReadableDatabase();
arrayList = database_handler.getAllContacts();
adapter = new MyAdapter(ViewAll.this, arrayList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void addNewData() {
try {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
String str1 = "List "+i+" ", str2 = "Handler testing";
database_handler = new Database_Handler(ViewAll.this);
db = database_handler.getWritableDatabase();
database_handler.addRegister(str1, str2, db);
database_handler.close();
handler.postDelayed(this, 60 * 10);
i++;
}
}, 60 * 10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here is my adapter.
public class MyAdapter extends BaseAdapter{
private Context context;
private ArrayList<Model> arrayList;
private static LayoutInflater inflater;
public MyAdapter(ViewAll viewAll, ArrayList<Model> arrayList) {
this.context = viewAll;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView tvFirstName,tvLastName;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = null;
try {
Holder holder;
myView = convertView;
if (myView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.adapter, null);
holder = new Holder();
holder.tvFirstName= (TextView) myView.findViewById(R.id.tvFirstName);
holder.tvLastName= (TextView) myView.findViewById(R.id.tvLastName);
myView.setTag(holder);
}
else {
holder = (Holder) myView.getTag();
}
holder.tvFirstName.setText(arrayList.get(position).getF_name());
holder.tvLastName.setText(arrayList.get(position).getL_name());
} catch (Exception e) {
e.printStackTrace();
}
return myView;
}
}
Actually I am inserting data into database using handler class and show all data into listview in my ViewAll activity and it work fine but when i go to my previous MainActivity and again go to ViewAll activity then listview load incorrectly which show in the image like after "List 24" data inserted incorrectly.
Please Clear your Arraylist and also clear your adapter when you are loading it from first item of listview.
You can clear this by lstVwList.setAdapter(null);

i cannot set select all checkbox to listview here is my code

Code for custome adapter
public class CustomAdapter extends BaseAdapter{
private Context context;
private ArrayList<String> name;
private ArrayList<String> id;
private ArrayList<String> group;
boolean checkBoxState;
public CustomAdapter( Context c,ArrayList<String> Cid, ArrayList<String> Cname,ArrayList<String> Cgroup) {
this.name = Cname;
this.id=Cid;
this.group = Cgroup;
MsgActivity msg=new MsgActivity();
this.context = c;
}
#Override
public int getCount() {
return id.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View Child, ViewGroup parent) {
Holder mholder;
LayoutInflater layoutInflater;
if(Child==null) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
Child = layoutInflater.inflate(R.layout.listview, null);
mholder = new Holder();
mholder.txt_name = (TextView) Child.findViewById(R.id.tvlist_name);
mholder.txt_Grp = (TextView) Child.findViewById(R.id.tvlist_group);
mholder.txt_id = (TextView) Child.findViewById(R.id.tvlist_id);
mholder.chk_box=(CheckBox) Child.findViewById(R.id.cbList_hook);
Child.setTag(mholder);
}
else
{
mholder=(Holder) Child.getTag();
}
mholder.txt_name.setText(name.get(position));
mholder.txt_Grp.setText(group.get(position));
mholder.txt_id.setText(id.get(position));
mholder.chk_box.setChecked(true);
return Child;
}
public class Holder {
TextView txt_id;
TextView txt_name;
TextView txt_Grp;
CheckBox chk_box;
}
}
code for display activity
public class MsgActivity extends AppCompatActivity implements OnItemSelectedListener {
EditText tx1;
TextView tv;
Button b1,b2,b3;
Spinner sp;
ListView lv;
String dat3;
SQLiteDatabase dh;
DbHelper mhelper;
public Integer m=null;
AddgrpActivity addgrp;
public CheckBox cb;
private ArrayList<String> userId = new ArrayList<>();
private ArrayList<String> user_name = new ArrayList<>();
private ArrayList<String> user_num = new ArrayList<>();
ArrayList<String> groups = new ArrayList<>();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dat3=sp.getSelectedItem().toString();
Toast.makeText(getApplicationContext(),dat3,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg);
tx1 = (EditText) findViewById(R.id.editText);
b1 = (Button) findViewById(R.id.button2_add_msg);
b2 = (Button) findViewById(R.id.button_snd);
sp = (Spinner) findViewById(R.id.spinner);
lv = (ListView) findViewById(R.id.listView);
sp.setOnItemSelectedListener(this);
mhelper = new DbHelper(this);
cb=(CheckBox)findViewById(R.id.checkBox_1);
tv=(TextView)findViewById(R.id.textView);
groups = addgrp.Addall();
groups.add("all");
ArrayAdapter<String> grps = new ArrayAdapter(this, android.R.layout.simple_spinner_item, groups);
grps.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(grps);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userId.clear();
user_name.clear();
user_num.clear();
dh = mhelper.getReadableDatabase();
Cursor mCursor;
if (dat3 == "all") {
mCursor = dh.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_NAME)));
user_num.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_GRP)));
} while (mCursor.moveToNext());
CustomAdapter cst = new CustomAdapter(MsgActivity.this, userId, user_name, user_num);
//ArrayAdapter cst = new ArrayAdapter(MsgActivity.this, android.R.layout.simple_list_item_multiple_choice, user_name);
lv.setAdapter(cst);
}
} else {
mCursor = dh.rawQuery("select * from " + DbHelper.TABLE_NAME + " where " + DbHelper.KEY_GRP + " = ?", new String[]{dat3});
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_NAME)));
user_num.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_GRP)));
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE_MODAL);
//user_sal.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_SAL)));
} while (mCursor.moveToNext());
}
}
final CustomAdapter cst = new CustomAdapter(MsgActivity.this, userId, user_name, user_num);
// ArrayAdapter cst=new ArrayAdapter(MsgActivity.this,android.R.layout.simple_list_item_multiple_choice,user_name);
//lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE_MODAL);
lv.setAdapter(cst);
mCursor.close();
}
});
}
public void onBackPressed() {
Intent in = new Intent(MsgActivity.this, MainActivity.class);
startActivity(in);
}
}

notifyDatasetChanged is not working for listview

My ListView has set of rows with Delete Button in each row.
On Click of the delete button must delete particular row from Sqlite Database and refresh the listview.
Problem
I am able to delete row from database. But I am not able to refresh the page after deleting the row.
For refreshing I tried using notifyDatasetChanged(), but no luck.
I could able to see the new list if i got back to previous activity and come back to same activity.
Please find the adapter and class codes below.
MainClass:
public class AddToCart extends AppCompatActivity {
ListView cart_list;
DatabaseHandler db = new DatabaseHandler(this);
Cursor todoCursor;
Context context;
String name, price, image, model;
ArrayList<String> bitmapArray = new ArrayList<String>();
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<String> list_price = new ArrayList<String>();
ArrayList<String> list_model = new ArrayList<String>();
Toolbar toolbar;
Button checkout;
static CustomAdapter_cart customAdapter_cart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addtocart);
context = this;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
cart_list = (ListView) findViewById(R.id.listview_cart);
checkout = (Button) findViewById(R.id.checkout);
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(AddToCart.this, Signup.class);
startActivity(in);
}
});
Intent i = getIntent();
// Get access to the underlying writeable database
// Query for items from the database and get a cursor back
// todoCursor = db1.rawQuery("SELECT id as _id, * from cart ", null);
// db1.execSQL("DELETE FROM cart");
// Reading all contacts
List<Cart> contacts = db.getAllContacts();
cart_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
for (Cart cn : contacts) {
name = cn.getName();
list_name.add(name);
price = cn.getPhoneNumber();
list_price.add(price);
image = cn.getImage_list();
bitmapArray.add(image);
model = cn.getModel();
list_model.add(model);
}
customAdapter_cart = new CustomAdapter_cart(this, list_name, list_price, bitmapArray, list_model);
cart_list.setAdapter(customAdapter_cart);
}
public static class MyLovelyOnClickListener implements View.OnClickListener
{
CustomAdapter_cart contextnew;
String myLovelyVariable;
Context context;
public MyLovelyOnClickListener(Context contextnew, CustomAdapter_cart context, String tv_model) {
this.contextnew = context;
this.context = contextnew;
this.myLovelyVariable = tv_model;
}
#Override
public void onClick(View v) {
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try {
db1.delete("cart", "model = ?", new String[]{myLovelyVariable});
customAdapter_cart.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
}
CustomAdapter.class
public class CustomAdapter_cart extends BaseAdapter {
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<String> list_price = new ArrayList<String>();
ArrayList<String> list_images = new ArrayList<String>();
ArrayList<String> list_model = new ArrayList<String>();
CustomAdapter_cart cart_refresh;
Bitmap b;
View rowView;
Context context;
AddToCart cart;
private static LayoutInflater inflater = null;
Cursor cu;
Context contextnew;
AddToCart.MyLovelyOnClickListener listener;
String model_item;
public CustomAdapter_cart(Context context, ArrayList<String> list_name, ArrayList<String> list_price, ArrayList<String> bitmapArray, ArrayList<String> list_model) {
this.context = context;
this.list_name = list_name;
this.list_price = list_price;
this.list_images = bitmapArray;
this.list_model = list_model;
this.cart_refresh = this;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list_name.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView tv_name, tv_price, tv_model;
ImageView image;
Button delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final Holder holder = new Holder();
rowView = inflater.inflate(R.layout.list_items_cart, null);
holder.tv_name = (TextView) rowView.findViewById(R.id.name_cart);
holder.tv_price = (TextView) rowView.findViewById(R.id.price_cart);
holder.image = (ImageView) rowView.findViewById(R.id.image_cart);
holder.tv_model = (TextView) rowView.findViewById(R.id.model_cart);
holder.delete = (Button) rowView.findViewById(R.id.delete);
holder.tv_name.setText(list_name.get(position));
holder.tv_price.setText(list_price.get(position));
holder.tv_model.setText(list_model.get(position));
String n = holder.tv_model.getText().toString();
holder.image.setImageBitmap(loadImageFromStorage(list_images.get(position)));
// holder.delete.setTag(holder.tv_model);
listener = new AddToCart.MyLovelyOnClickListener(context,CustomAdapter_cart.this,n);
holder.delete.setOnClickListener(listener);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name_item = ((TextView) rowView.findViewById(R.id.name_cart)).getText().toString();
String price_item = ((TextView) rowView.findViewById(R.id.price_cart)).getText().toString();
model_item = ((TextView) rowView.findViewById(R.id.model_cart)).getText().toString();
Intent in = new Intent(context, AddCart_FullImage.class);
in.putExtra("model", model_item);
in.putExtra("name", name_item);
in.putExtra("price", price_item);
context.startActivity(in);
}
});
return rowView;
}
private Bitmap loadImageFromStorage(String path) {
try {
File f = new File(path, "");
f.canRead();
b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
Any Help would be really helpfull.
Thanks.
you are just deleting a row from database. Your adapter is still having the same set of data. So first update the data set of the adapter and than call notifydatasetchanged()

CustomAdapter View override not setting text

I'm attempting to set the text color in a CustomAdapter class by overriding the View. The code seems to run but the phone screen displays nothing. Any suggestions?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(LogCat.this);
String logLevel = prefs.getString("dirLogCat", "");
setContentView(R.layout.log_cat);
ListView lv1 = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this, R.layout.text_list, log);
try {
Process process = Runtime.getRuntime().exec(new String[] {"logcat", "-d"});
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while ((line = bufferedReader.readLine()) != null){
if (line.contains(" " + logLevel + " ")){
//log.add(line);
log.add(line.substring(6, 14) + " " + line.substring(31, line.length()));
}
}
CustomAdapter adapter = new CustomAdapter(log, this, "V");
lv1.setAdapter(arrayAdapter);
adapter.notifyDataSetChanged();
}
catch (IOException e) {}
}
public class CustomAdapter extends BaseAdapter {
private Context ctx;
CustomAdapter (ArrayList<String> data, Context context, String log) {
this.ctx = context;
this.getView(0, new View(context), null);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflator = (LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.text_list, null);
TextView textView = (TextView) v.findViewById(R.id.logText);
textView.setTextColor(Color.CYAN);
return textView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
}
}
EDIT:
This did it:
public class CustomAdapter extends BaseAdapter {
private Context ctx;
private ArrayList<String> children;
CustomAdapter (ArrayList<String> data, Context context, String log) {
this.ctx = context;
System.out.println("Cyan1");
this.children = data;
this.getView(0, new View(context), null);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflator = (LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.text_list, null);
TextView textView = (TextView) v.findViewById(R.id.logText);
System.out.println("Cyan");
textView.setTextColor(Color.CYAN);
for(int i = 0; i < log.size(); i++){
textView.setText(children.get(i));
}
return textView;
}
You're setting the wrong adapter in the list?
CustomAdapter adapter = new CustomAdapter(log, this, "V");
lv1.setAdapter(arrayAdapter); //<---- arrayAdapter instead of adapter?
adapter.notifyDataSetChanged();

Append new elements from custom adapter to ListView

I've got a ListView with a 'show next results' button. The list is filled by a custom adapter extending BaseAdapter. Using it as shown below, only the new results are shown.
How can I append the new results to the list?
ListView listView = (ListView)findViewById(android.R.id.list);
// Show next results button
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = getIntent();
i.putExtra("firstIndex", mFirstIndex + NRES_PER_PAGE);
i.putExtra("itemCount", NRES_PER_PAGE);
startActivity(i);
}
});
mItems = json.getJSONArray("data");
setListAdapter(new ItemAdapter(ItemList.this, mType, mItems));
FIX
ListActivity
public class ItemList extends MenuListActivity{
ItemAdapter mItemAdapter;
Integer mFirstIndex = 0;
JSONArray mItems = new JSONArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
// Set data adapter
mItemAdapter = new ItemAdapter(ItemList.this, mType, mItems);
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
setListAdapter(mItemAdapter);
new GetItemInfoList().execute();
}
private class GetItemInfoList extends AsyncTask<Void, Void, JSONObject> {
protected JSONObject doInBackground(Void... params) {
// Set POST data to send to web service
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add(new BasicNameValuePair("firstindex", Integer.toString(mFirstIndex)));
postData.add(new BasicNameValuePair("itemscount", Integer.toString(ITEM_COUNT)));
JSONObject json = RestJsonClient.getJSONObject(URL_ITEMINFOLIST, postData);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
// Get data from json object and set to list adapter
JSONArray jsonArray = json.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++)
mItems.put(jsonArray.get(i));
mItemAdapter.notifyDataSetChanged();
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
} catch (JSONException e) {
}
}
}
}
Adapter
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private JSONArray mItems;
private ImageLoader mImageLoader;
private int mCategory;
public ItemAdapter(Context context, int category, JSONArray items) {
mContext = context;
mInflater = LayoutInflater.from(context);
mItems = items;
mCategory = category;
this.mImageLoader = new ImageLoader(context, true);
}
public int getCount() {
return mItems.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_row, null);
holder = new ViewHolder();
holder.listitem_pic = (ImageView) convertView.findViewById(R.id.listitem_pic);
holder.listitem_desc = (TextView) convertView.findViewById(R.id.listitem_desc);
holder.listitem_title = (TextView) convertView.findViewById(R.id.listitem_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
JSONObject item = mItems.getJSONObject(position);
String listitem_pic = item.getString("picture");
holder.listitem_pic.setTag(listitem_pic);
mImageLoader.DisplayImage(listitem_pic, (Activity)mContext, holder.listitem_pic);
holder.listitem_title.setText(item.getString("title"));
holder.listitem_desc.setText(item.getString("desc"));
}
catch (JSONException e) {
}
return convertView;
}
static class ViewHolder {
TextView listitem_title;
ImageView listitem_pic;
TextView listitem_desc;
}
}
It depends on your implementation of ItemAdapter, I'd recommend holding a reference to ItemAdapter, then updating the data set behind it and then calling notifyDataSetChanged() on it. something like:
ItemAdapter ia = new ItemAdapter(ItemList.this, mType, mItems);
setListAdapter(ia);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mItems.append(newItems);
ia.notifyDataSetChanged();
}
});
It is tricky without knowing what data you are using or whether you have the entire data set available at the start.

Categories

Resources