Is it a correct way to set headerView to ListView in Fragment?
I have some fragment(see below code). In this fragment i populate ListView.
But I don't know where I can call addHeaderView.
Can anybody help me?
public class FeedsListForViewFragment extends ListFragment {
private Context mContext;
List<FeedItem> items;
private int layoutForList = R.layout.list_feeds_simple;
private ActiveRecordBase _db;
private Activity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = getActivity();
_db = ((JtjApplication)getActivity().getApplication()).getDatabase();
try {
_db.open();
} catch (ActiveRecordException e) {
e.printStackTrace();
}
}
public void setItemsToList(List<FeedItem> items, int curPosition) {
mContext = getActivity().getApplicationContext();
this.items = items;
ListView lv = getListView();
setListAdapter(new ListOfFeedsAdapter(mContext, layoutForList, items, mActivity));
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setCacheColorHint(Color.WHITE);
setPosition(curPosition);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (!(((FeedsActivity) getActivity()).getCurrentPosition() == position)) {
updateUnreadItemsInDb(position);
updateLinksList(position, items.get(position));
((FeedsActivity) getActivity()).setCurrentPosition(position);
}
}
#SuppressWarnings("unchecked")
private void updateUnreadItemsInDb(int position) {
FeedItem feed = items.get(position);
if (feed.isRead != true) {
List<FeedItem> feedsForUpdate = null;
List<FeedType> lft = null;
try {
feedsForUpdate = _db.find(FeedItem.class, false, "GUID=?", new String[] { String.valueOf(feed.guid) }, null, null, "PUBLICATIONDATE DESC", null);
lft = _db.findAll(FeedType.class);
} catch (ActiveRecordException e1) {
e1.printStackTrace();
}
for (FeedItem curFeed:feedsForUpdate) {
curFeed.isRead = true;
try {
curFeed.save();
FeedType ft = lft.get(Integer.parseInt(curFeed.channel_id) - 1);
ft.unread_count = ft.unread_count - 1;
ft.update();
} catch (ActiveRecordException e) {
e.printStackTrace();
}
}
items.get(position).isRead = true;
((ArrayAdapter<FeedItem>) getListView().getAdapter()).notifyDataSetChanged();
}
}
private void setPosition(int position) {
ListView lv = getListView();
lv.setSelection(position);
lv.setItemChecked(position, true);
try{
updateLinksList(position, items.get(position));
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
private void updateLinksList(int position, FeedItem feedItem) {
FeedsViewFragment viewFragment = (FeedsViewFragment) getFragmentManager().findFragmentById(R.id.feed_view_fragment);
viewFragment.setViewItem(feedItem);
}
}
You would call addHeaderView() between:
ListView lv = getListView();
and:
setListAdapter(new ListOfFeedsAdapter(mContext, layoutForList, items, mActivity));
Now, I have not tried a header View on a ListFragment, so while it should work, there is a chance that for some reason it does not.
Related
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've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.
My code is reachable but the adapter just doesnt work. The listview doesnt show and the fragment remains empty.
I re-populate my list at OnResume.
my code:
public class mylist extends ListFragment {
public void ToastLoadShout(String msg) {
Toast.makeText(getActivity(), msg.toString(), Toast.LENGTH_LONG).show();
}
private static View View;
HttpClient client;
HttpPost httppost;
HttpGet httpget;
JSONObject json;
List<List<String>> items;
List<item> markers = new ArrayList<item>();
MobileArrayAdapter adapter;
ListView list;
ProgressBar listload;
Button relist;
Preferences pref;
String datadata = "";
String savedlat="0.0";
String savedlon="0.0";
boolean isLoaded=false;
int index;
int top;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_list, container, false);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume(){
super.onResume();
// Recreate the adapter from the new feed
adapter = new MobileArrayAdapter(getActivity(), markers);
// Set the recreated adapter
list.setAdapter(adapter);
ToastLoadShout("reached here");
if (!(items==null))
ToastLoadShout("there are items");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!isLoaded){
try {
pref = new Preferences(getActivity());
list = (ListView) getView().findViewById(android.R.id.list);
listload = (ProgressBar) getView().findViewById(R.id.listload);
HashMap<String, String> loc = pref.getData();
ToastLoadShout(loc.get(Preferences.LAT) + ","
+ loc.get(Preferences.LON));
if (loc.get(Preferences.LAT) != null && !loc.get(Preferences.LAT).equals("0.0"))
{
if (loc.get(Preferences.LAT) != savedlat && loc.get(Preferences.LON)!=savedlon){
new Load().execute();
savedlat=loc.get(Preferences.LAT);
savedlon=loc.get(Preferences.LON);
}
}
else
ToastLoadShout("Get Location First.");
relist = (Button) getView().findViewById(R.id.relist);
relist.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listload.setVisibility(View.INVISIBLE);
HashMap<String, String> loc = pref.getData();
ToastLoadShout(loc.get(Preferences.LAT) + ","
+ loc.get(Preferences.LON));
if (loc.get(Preferences.LAT) != null && !loc.get(Preferences.LAT).equals("0.0")){
adapter.deleteList();
list.destroyDrawingCache();
new Load().execute();}
else
ToastLoadShout("Get Location First.");
}});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
list.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//Check if the last view is visible
index = list.getFirstVisiblePosition();
View v = list.getChildAt(0);
top = (v == null) ? 0 : v.getTop();
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// get selected items
//String selectedValue = (String) getListAdapter().getItem(position);
String selectedValue = markers.get(position).getTitle();
Toast.makeText(getActivity(), selectedValue, Toast.LENGTH_SHORT).show();
}
class Load extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
listload.setVisibility(View.VISIBLE);
isLoaded=true;
ToastLoadShout("preExecute");
}
#Override
protected Boolean doInBackground(String... params) {
try {
items = DownloadList();
if (items != null)
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
#Override
protected void onPostExecute(Boolean res) {
// TODO Auto-generated method stub
if (res) {
ArrangePutMarkers();
adapter=new MobileArrayAdapter(getActivity(), markers);
list.setAdapter(adapter);
} else {
ToastLoadShout("Error");
ToastLoadShout(datadata);
}
listload.setVisibility(View.INVISIBLE);
ToastLoadShout("PostExecute");
}
}
public void onBackPressed() {
}
}
Call notifydatasetchanged method of your adapter after you change its contents. Your OnResume method is assigning an empty data adapter to your listview.
Where are you populating your markers collection?
Also, you can call getListView and setListAdapter methods of the ListFragment class rather than finding the list with findViewById.
i have a listview builded from xml file by an lazyadapter (baseadpter)
for example: urlxml --> parser ---> baseadapter ---> listview
when i modified xml file on server i would like to refresh listview and see rows changed in it. By the way im using lib "pull to refresh".
When i pull to refresh i got new rows togheter old rows.
Do i have to delete listview content first and repeat this:
urlxml --> parser ---> baseadapter ---> listview
what is wrong?
EDIT woth some code
my adapter
public class LazyAdapter extends BaseAdapter {
private Activity activity;
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>> ();
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<ArrayList<String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.get(0).size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.elenco_articoli_items, null);
String Tt = data.get(0).get(position);
String URl = data.get(1).get(position);
TextView text=(TextView)vi.findViewById(R.id.title);;
ImageView image=(ImageView)vi.findViewById(R.id.image);
text.setText(Html.fromHtml(Tt));
imageLoader.DisplayImage(URl, image,1);
return vi;
}
}
my main activity
public class Lista_articoli_categoria extends Activity {
ArrayList<String> images = new ArrayList<String> ();
ArrayList<String> title = new ArrayList<String> ();
ArrayList<String> author = new ArrayList<String> ();
ArrayList<String> description = new ArrayList<String> ();
private LazyAdapter adapter;
private RefreshableListView mListView;
Parser task = new Parser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elenco_articoli);
try {
task.execute();
final RefreshableListView list = (RefreshableListView) findViewById(R.id.refreshablelistview);
adapter= new LazyAdapter(this, fill_data(task.get()));
mListView = list;
list.setAdapter(adapter);
list.setOnUpdateTask(new OnUpdateTask() {
public void updateBackground() {
refresh_data();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void updateUI() {
adapter.notifyDataSetChanged();
}
public void onUpdateStart() {
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
TODO
*/
}
});
}
#Override
public void onDestroy()
{
mListView.setAdapter(null);
super.onDestroy();
}
public ArrayList<ArrayList<String>> fill_data(ArrayList<Struttura_rss> Datidaxml){
ArrayList<ArrayList<String>> rec = new ArrayList<ArrayList<String>> ();
for(int i=0;i<Datidaxml.size();i++){
Struttura_rss p = Datidaxml.get(i);
title.add(p.getTitle());
images.add(p.getImage());
description.add(p.getArticolo());
author.add(p.getAuthor());
}
rec.add (title);
rec.add (images);
rec.add (description);
rec.add (author);
return rec;
}
public void refresh_data(){
try {
Parser task = new Parser();
task.execute();
adapter= new LazyAdapter(this, fill_data(task.get()));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
If you look at the example, you should understand easily...
Link: https://github.com/chrisbanes/Android-PullToRefresh/blob/master/sample/src/com/handmark/pulltorefresh/samples/PullToRefreshListActivity.java
On the refreshn you have to download only the new items (by exemple by sending a timestamp or an id to the webservice)
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
//Go to webservice
} catch (InterruptedException e) {
}
return mStrings;
}
And then, parse only the new items and add them here:
#Override
protected void onPostExecute(String[] result) {
mListItems.addFirst("Added after refresh...");
mAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
EDIT: if you cannot download only the needed items (RSS feed) download evrything and add the correct items in onPostExecute.
if(!isALreadyInTheList(currentItem))
mListItems.addFirst(currentItem);
else
doNothing();
nothing happens when I click on item of list view here is code
#SuppressLint("ParserError")
public class DinerList extends Activity implements Comparator<CanteenTagEntry>,
OnItemSelectedListener {
List<CanteenTagEntry> dinerlist;
int size;
int[] arr;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diner_list);
ListView listView1 = (ListView) findViewById(R.id.list);
Context con = getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(con);
ICanteenLogRepository repository = dbHelper.getCanteenLogRepository();
try {
dinerlist = repository.total();
Collections.sort(dinerlist, new DinerList());
Collections.sort(dinerlist, new sortbyuser());
Collections.sort(dinerlist, new sortbycompany());
size = dinerlist.size();
arr = new int[size];
for (int i = 0; i < size; i++) {
CanteenTagEntry tagentry = dinerlist.get(i);
int b = tagentry.getId();
System.out.print(b);
arr[i] = tagentry.getId();
System.out.print(arr[i]);
}
} catch (SQLException e) {
Log.d("DinerList", "Unable to retrieve diner list", e);
}
CanteenAdapter adapter = new CanteenAdapter(this,
R.layout.listview_item_row,
(ArrayList<CanteenTagEntry>) dinerlist);
listView1.setAdapter(adapter);
}
public class CanteenAdapter extends ArrayAdapter<CanteenTagEntry> {
Context context;
int layoutResourceId;
ArrayList<CanteenTagEntry> data = (ArrayList<CanteenTagEntry>) dinerlist;
public CanteenAdapter(Context context, int layoutResourceId,
ArrayList<CanteenTagEntry> data) {
super(context, layoutResourceId, dinerlist);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = (ArrayList<CanteenTagEntry>) dinerlist;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RouteHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RouteHolder();
holder.txtName1 = (TextView) row.findViewById(R.id.Title1);
holder.txtName2 = (TextView) row.findViewById(R.id.Title2);
holder.txtName3 = (TextView) row.findViewById(R.id.Title3);
row.setTag(holder);
} else {
holder = (RouteHolder) row.getTag();
}
CanteenTagEntry tagentry = data.get(position);
String idcolor = tagentry.getUser().getIdcolor().toString();
try {
holder.txtName1.setTextColor(Color.parseColor(idcolor));
holder.txtName2.setTextColor(Color.parseColor(idcolor));
holder.txtName3.setTextColor(Color.parseColor(idcolor));
} catch (Exception e) {
holder.txtName1.setTextColor(Color.GRAY);
holder.txtName2.setTextColor(Color.GRAY);
holder.txtName3.setTextColor(Color.GRAY);
}
holder.txtName1.setText(tagentry.getUser().getUserType().getName());
holder.txtName2.setText(tagentry.getUser().getCompany().getName());
holder.txtName3.setText(tagentry.getUser().getFirstName());
return row;
}
class RouteHolder {
TextView txtName1;
TextView txtName2;
TextView txtName3;
TextView txtName4;
}
}
#Override
public int compare(CanteenTagEntry o1, CanteenTagEntry o2) {
return o1.getUser().getFirstName()
.compareTo(o2.getUser().getFirstName());
}
public class sortbyuser implements Comparator<CanteenTagEntry> {
#Override
public int compare(CanteenTagEntry lhs, CanteenTagEntry rhs) {
return lhs.getUser().getUserType().getName()
.compareTo(rhs.getUser().getUserType().getName());
}
}
public class sortbycompany implements Comparator<CanteenTagEntry> {
#Override
public int compare(CanteenTagEntry lhs, CanteenTagEntry rhs) {
return lhs.getUser().getCompany().getName()
.compareTo(rhs.getUser().getCompany().getName());
}
}
#Override
public void onItemSelected(AdapterView<?> l, View v, int position,
long ide) {
super.onListItemClick(l, v, position, ide);
CanteenTagEntry tagentry = null;
int pos = position;
int id = arr[pos];
int userid = 0;
Context con = getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(con);
ICanteenLogRepository repository = dbHelper.getCanteenLogRepository();
try {
tagentry = repository.Retrieve(id);
userid = tagentry.getUser().getId();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StartFood food = new StartFood(id, userid);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
i thin you need to used
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
// do your work here
}
});
Try to set OnItemClickListener for your listView1 as per below and try to run.
listView1.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
CanteenTagEntry tagentry = null;
int pos = position;
int id = arr[pos];
int userid = 0;
Context con = getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(con);
ICanteenLogRepository repository = dbHelper.getCanteenLogRepository();
try
{
tagentry = repository.Retrieve(id);
userid = tagentry.getUser().getId();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
StartFood food = new StartFood(id, userid);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Before returning the row Set the listener to the row like this.
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// your code
}
});