ListView - ListView don't update - android

I'm trying to do Autogrowin/Endless ListView but I have a problem with ArrayAdapter = update after downloading the data.
public class ListShowActivity extends ListActivity {
private ShowsAdapter m_adapter;
private ArrayList<ShowsList> showList = new ArrayList<ShowsList>();
// Adapter
private class ShowsAdapter extends ArrayAdapter<ShowsList>
{
private ArrayList<ShowsList> items = new ArrayList<ShowsList>();
public ShowsAdapter(Context context, int textViewResourceId, ArrayList<ShowsList> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
public void appendList(ArrayList<ShowsList> results)
{
if((results != null) && (results.size() != 0))
{
m_adapter.add(results.get(0));
m_adapter.notifyDataSetChanged();
Log.i("test", "appendList: "+results.get(0).originalTitle);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
TextView tt = null;
TextView bt = null;
ImageView iv = null;
if (v == null){
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_show_item, null);
tt = (TextView) v.findViewById(R.id.showOriginalTitle);
bt = (TextView) v.findViewById(R.id.showTitle);
iv = (ImageView) v.findViewById(R.id.showPoster);
}
ShowsList item = this.items.get(position);
if (item != null) {
if(tt != null){
tt.setText(item.originalTitle);
}
if(bt != null){
bt.setText(item.title);
}
if(iv != null)
{
new DownloadImage().downloadImage(item.poster, iv);
}
}
return v;
}
}
// Implement new OnScrollListener
public class onScrollLoad implements OnScrollListener {
private int lastOffset = 10;
private int limit = 10;
private int mPrevTotalItemCount = 0;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (((firstVisibleItem + visibleItemCount) >= totalItemCount) && totalItemCount != mPrevTotalItemCount) {
lastOffset = totalItemCount;
mPrevTotalItemCount = lastOffset;
limit += 1;
ArrayList<ShowsList> results = new Api().getShows(lastOffset, limit);
m_adapter.appendList(results);
//new PagingRequest(m_adapter).execute(lastOffset, limit);
Toast.makeText(getApplicationContext(), lastOffset+" / "+limit, Toast.LENGTH_SHORT).show();
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
Log.i("test", "onScrollStateChange()");
}
}
// Implement AsyncTask for download items?
/*
private static class PagingRequest extends AsyncTask<Integer, Void, ArrayList<ShowsList>> {
private ShowsAdapter mAdapter;
public PagingRequest(ShowsAdapter adapter) {
this.mAdapter = adapter;
}
protected ArrayList<ShowsList> doInBackground(Integer... params) {
return new Api().getShows(params[0], params[1]);
}
protected void onPostExecute(ArrayList<ShowsList> result) {
this.mAdapter.appendList(result);
}
}
*/
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_shows);
TextView tv = (TextView) findViewById(R.id.headerbarText);
tv.setText("List Shows");
// Get Items
Api a = new Api();
// First 10 items
showList = a.getShows(0, 0);
if(showList.isEmpty() == false)
{
//showList = new Api().getShows(0,0);
m_adapter = new ShowsAdapter(this, R.layout.list_show_item, showList);
setListAdapter(m_adapter);
ListView lv = getListView();
lv.setOnScrollListener(new onScrollLoad());
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent = new Intent(ListShowActivity.this, ShowActivity.class);
//intent.putExtra("showID", getShowsList.get(position).ID);
startActivity(intent);
}
});
}else{
Toast.makeText(getApplicationContext(), "NoData", Toast.LENGTH_SHORT).show();
}
}
}
I pasted code without working Asynctask.
In "theory"^^ everything works (appendList Log return correct value), but i as say i have problem with update ShowsAdapter (Download new image + and insert content to ListView)

Related

Android:Receive Array of Objects and display in listView

Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});

listview hide on orientation change android

I am using custom list view inside fragment(From Api). on orientation change data is still in array list and also list view get notified but it hides when screen rotates.
here is the code:
public class FragNotice extends Fragment implements View.OnClickListener {
ListAdapter listAdapter;
ListView listView;
EditText editTextNotice;
private Button btnSearch;
private Button btnClear;
private int incre = 1;
private boolean boolScroll = true;
public FragNotice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
setRetainInstance(true);
search(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return init(inflater.inflate(R.layout.notice_activity, container, false));
}
private View init(View view) {
editTextNotice = (EditText) view.findViewById(R.id.editTextNotice);
btnSearch = (Button) view.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
btnClear = (Button) view.findViewById(R.id.btnClear);
btnClear.setOnClickListener(this);
listView = (ListView) view.findViewById(R.id.listViewNotice);
listView.setOnScrollListener(onScrollListener());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), new ArrayList<ListRowItem>());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
AsyncRequest.OnAsyncRequestComplete onAsyncRequestComplete = new AsyncRequest
.OnAsyncRequestComplete() {
#Override
public void asyncResponse(String response, int apiKey) {
switch (apiKey) {
case 1:
listView(response);
break;
}
}
};
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnClear) {
incre = 1;
boolScroll = true;
editTextNotice.setText(null);
if (listAdapter != null)
listAdapter.clear();
search(true);
} else if (v.getId() == R.id.btnSearch) {
String std = editTextNotice.getText().toString();
if (std.trim().length() > 1) {
incre = 1;
boolScroll = true;
if (listAdapter != null)
listAdapter.clear();
try {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(new View(getActivity()).getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
// TODO: handle exception
}
search(false);
} else
Toast.makeText(getActivity(),
"Please enter atleast two character.", Toast.LENGTH_LONG)
.show();
}
}
class ListAdapter extends ArrayAdapter<ListRowItem> {
private final Context context;
public ListAdapter(Context asyncTask, java.util.List<ListRowItem> items) {
super(asyncTask, R.layout.notice_listitem, items);
this.context = asyncTask;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final ListRowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.notice_listitem, parent, false);
holder = new ViewHolder();
holder.txtSno = (TextView) convertView.findViewById(R.id.txtSno);
holder.txtNoticePublishDate = (TextView) convertView.findViewById(R.id
.txtNoticePublishDate);
holder.btnView = (Button) convertView.findViewById(R.id.btnView);
holder.txtNoticeDescription = (TextView) convertView.findViewById(R.id
.txtNoticeDescription);
holder.txtNoticeName = (TextView) convertView.findViewById(R.id.txtNoticeName);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtSno.setText(String.valueOf(position + 1));
holder.txtNoticeDescription.setText(new AppUtility().TitleCase(rowItem.getDescription
()));
holder.txtNoticeName.setText(new AppUtility().TitleCase(rowItem.getFileTitle()));
try {
holder.txtNoticePublishDate.setText(String.valueOf((new SimpleDateFormat("dd MMM " +
"yyyy HH:mm:ss", Locale.US)).format((new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ss", Locale.US)).parse(rowItem.getUpdateDate()))));
} catch (ParseException e) {
holder.txtNoticePublishDate.setText(new AppUtility().TitleCase(rowItem
.getUpdateDate()));
}
holder.btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return convertView;
}
/*private view holder class*/
private class ViewHolder {
TextView txtSno;
TextView txtNoticeName;
TextView txtNoticeDescription;
TextView txtNoticePublishDate;
Button btnView;
}
}
class ListRowItem {
private final String FileTitle;
private final String Description;
private final String ContentType;
private final int DocumentUploadID;
private final String UpdateDate;
ListRowItem() {
this.FileTitle = "";
this.Description = "";
this.ContentType = "";
this.DocumentUploadID = 0;
this.UpdateDate = "";
}
ListRowItem(String fileTitle, String description, String contentType, int
documentUploadID, String updateDate) {
this.FileTitle = fileTitle;
this.Description = description;
this.ContentType = contentType;
this.DocumentUploadID = documentUploadID;
this.UpdateDate = updateDate;
}
public String getFileTitle() {
return FileTitle;
}
public int getDocumentUploadID() {
return DocumentUploadID;
}
public String getUpdateDate() {
return UpdateDate;
}
public String getDescription() {
return Description;
}
public String getContentType() {
return ContentType;
}
}
private void listView(String response) {
try {
ArrayList<ListRowItem> lstItem;
if(listAdapter==null){
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
listAdapter = new ListAdapter(getActivity(), lstItem);
} else {
Type listType = new TypeToken<ArrayList<ListRowItem>>() {
}.getType();
lstItem = new Gson().fromJson(response, listType);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
listAdapter.addAll(lstItem);
} else {
for (ListRowItem items : lstItem) {
listAdapter.add(items);
}
}
}
if (listAdapter != null)
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
private AbsListView.OnScrollListener onScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 5;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= count - threshold) {
if (boolScroll) {
if (editTextNotice.getText().toString().trim().length() > 0)
search(false);
else
search(true);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
private void search(boolean bool) {
String URL;
if (bool) {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/0/" + incre;
incre = incre + 1;
} else {
URL = new SqLite(getActivity()).returnDefaultURI() + "notice/" +
editTextNotice.getText().toString().trim() + "/" + incre;
incre = incre + 1;
}
AsyncRequest asyncRequest;
if (incre > 2)
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
null, 1);
else
asyncRequest = new AsyncRequest(onAsyncRequestComplete, getActivity(), "GET", null,
"Fetching data", 1);
asyncRequest.execute(URL);
}
}
You need to load the data into the ListView again. You are binding the ListView to an adapter, you need to do it in onConfigurationChanged() method.
When orientation changes the activity reloads again.So you have to override onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Your Code Here
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Your Code Here
}
}
create a directory layout-land in the resources copy the your .xml file there align and set the Edittext and Button according to landscape layout .may be it solved your problem if the listview doest not get enough space to show in landscape layout
In onViewCreated(View view, Bundle savedInstanceState) method above you are setting new empty arraylist every time. So the previous items which are loaded are removed from adapter even though it is retained by setRetainInstance(true)
So you should have a Field that holds the arraylist and pass that field to adapter
private ArrayList<ListRowItem> listItems = new ArrayList<>()
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (listAdapter==null) {
listAdapter=new ListAdapter(getActivity(), listItems);//pass the Arraylist here
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
Then in private void listView(String response) method, add items to that listview created above as
listItems = new Gson().fromJson(response, listType);
listAdapter.notifyDataSetChanged();

Append Data Load More Listview

I'm newbie Android Programming. I have Fragment which shows on Listview and now, i want Listview load more item when list ends. But data is not appending. I need help !
My code :
public class InfoTeacherFragment extends Fragment {
private String URL = "http://scv.udn.vn/dhdn/trdhsp/page/";
ProgressDialog pDialog;
Context mContext;
Vector<ArrayList<String>> data;
ArrayList<String> Name;
ArrayList<String> School;
ArrayList<String> Link;
ArrayList<String> Icon;
ListView lvItem;
DisplayImageOptions options;
ImageLoader imageloader;
View mFooterView;
InfoTeacher adapter;
ProgressBar loading;
int CurrentPage = 1;
int visibleThreshold = 3;
int startPage = 1;
boolean loadingMore = false;
public InfoTeacherFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_mission)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.teacherinfo_layout,
container, false);
mContext = container.getContext();
lvItem = (ListView) rootView.findViewById(R.id.lvTeacher);
lvItem.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
CurrentPage++;
customLoadMoreDataFromApi(CurrentPage);
Toast.makeText(mContext, "EndlessScrollListener",
Toast.LENGTH_SHORT).show();
}
});
imageloader = ImageLoader.getInstance();
imageloader.init(ImageLoaderConfiguration.createDefault(mContext));
if (Utils.isOnline(mContext) == true
&& Utils.KEY_CHECK_SUCCESS.equals("SUCCESS")) {
new LoadData().execute(URL + startPage);
lvItem.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
Intent intent = new Intent(mContext, NewsItemView.class);
if (Link != null) {
intent.putExtra("URL", Link.get(position));
startActivity(intent);
}
}
});
} else if (Utils.isOnline(mContext) == true
&& Utils.KEY_CHECK_SUCCESS.equals("FAIL")) {
Utils.MyToast(Utils.KEYWORK_ERROR[0], R.drawable.warning_icon,
mContext, false);
}
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(mContext, "", Utils.KEYWORK_ERROR[2]);
data = new Vector<ArrayList<String>>();
Name = new ArrayList<String>();
School = new ArrayList<String>();
Link = new ArrayList<String>();
Icon = new ArrayList<String>();
super.onPreExecute();
}
#Override
protected String doInBackground(String... URL) {
data = Utils.getInformationTeacher(URL[0]);
if (!(data.isEmpty())) {
return Utils.KEY_CHECK_SUCCESS;
} else {
return Utils.KEY_CHECK_FAIL;
}
}
#Override
protected void onPostExecute(String result) {
if (result.equals(Utils.KEY_CHECK_SUCCESS)) {
pDialog.dismiss();
Name = data.get(0);
School = data.get(1);
Icon = data.get(2);
Link = data.get(3);
adapter = new InfoTeacher(mContext, Name, School, Icon);
lvItem.setAdapter(adapter);
} else if (result.equals(Utils.KEY_CHECK_FAIL)) {
pDialog.dismiss();
Utils.MyToast(Utils.KEYWORK_ERROR[0], R.drawable.warning_icon,
mContext, false);
}
super.onPostExecute(result);
}
}
class InfoTeacher extends BaseAdapter {
private ArrayList<String> Icon = new ArrayList<String>();
private ArrayList<String> Name = new ArrayList<String>();
private ArrayList<String> School = new ArrayList<String>();
private LayoutInflater inflater;
ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
public InfoTeacher(Context context, ArrayList<String> Name,
ArrayList<String> School, ArrayList<String> Icon) {
this.Name = Name;
this.Icon = Icon;
this.School = School;
Collections.reverse(Name);
Collections.reverse(School);
Collections.reverse(Icon);
inflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return Name.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup arg2) {
View rowView = view;
ViewHolder holder;
if (rowView == null) {
holder = new ViewHolder();
rowView = inflater
.inflate(R.layout.teacher_layout, arg2, false);
holder.Name = (TextView) rowView
.findViewById(R.id.tv_NameTeacher);
holder.School = (TextView) rowView.findViewById(R.id.tv_School);
holder.ic_naviga = (ImageView) rowView
.findViewById(R.id.ivNaviga);
holder.icon = (ImageView) rowView
.findViewById(R.id.iv_IconTeacher);
rowView.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
final String mIcon = Icon.get(position);
holder.Name.setText(Name.get(position).toString());
holder.School.setText(School.get(position).toString());
ImageLoader.getInstance().displayImage(mIcon, holder.icon, options,
animateFirstListener);
return rowView;
}
}
static class ViewHolder {
ImageView icon;
TextView Name;
TextView School;
ImageView ic_naviga;
}
private static class AnimateFirstDisplayListener extends
SimpleImageLoadingListener {
static final List<String> displayedImages = Collections
.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
public void customLoadMoreDataFromApi(int page) {
new LoadData().execute(URL + page);
adapter.notifyDataSetChanged();
// This method probably sends out a network request and appends new data
// items to your adapter.
// Use the offset value and add it as a parameter to your API request to
// retrieve paginated data.
// Deserialize API response and then construct new objects to append to
// the adapter
}
class LoadMoreItemsList extends
AsyncTask<Void, Void, Vector<ArrayList<String>>> {
private LoadMoreItemsList() {
loadingMore = true;
mFooterView = LayoutInflater.from(mContext).inflate(
R.layout.loading_view, null);
}
#Override
protected void onPreExecute() {
lvItem.addFooterView(mFooterView);
lvItem.setAdapter(adapter);
super.onPreExecute();
}
#Override
protected Vector<ArrayList<String>> doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Vector<ArrayList<String>> result) {
super.onPostExecute(result);
}
}
}
Function Utils.Utils.getInformationTeacher(URL[0]) :
public static Vector<ArrayList<String>> getInformationTeacher(String url) {
Vector<ArrayList<String>> data = new Vector<ArrayList<String>>();
ArrayList<String> Name = new ArrayList<String>();
ArrayList<String> School = new ArrayList<String>();
ArrayList<String> Link = new ArrayList<String>();
ArrayList<String> Icon = new ArrayList<String>();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Document doc = Jsoup.connect(url).timeout(10 * 300).get();
Charset.forName("UTF-8");
doc.outputSettings().escapeMode(EscapeMode.xhtml);
Elements eles = doc.select("div#Thu tbody a.linkheader");
Elements elesIcon = doc.select("div#Thu img[src]");
int i = 0;
for (Element element : eles) {
i++;
String fillinfo = element.ownText();
String link = element.attr("href");
if (i % 2 == 0) {
School.add(fillinfo);
} else {
Name.add(fillinfo);
Link.add(link);
}
}
for (Element icon : elesIcon) {
String hrefIcon = icon.attr("src");
Icon.add(hrefIcon);
}
data.add(Name);
data.add(School);
data.add(Icon);
data.add(Link);
} catch (IOException e) {
return data;
}
}
return data;
}
And Finally : abstract EndlessScrollListener
package android.readnews.support;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
public abstract class EndlessScrollListener implements OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
this.startingPageIndex = startPage;
this.currentPage = startPage;
}
// This happens many times a second during a scroll, so be wary of the code
// you place here.
// We are given a few useful parameters to help us work out if we need to
// load some more data,
// but first we check if we are waiting for the previous load to finish.
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
Log.i("abc", "ABC + totalItemCount < previousTotalItemCount");
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) {
this.loading = true;
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the
// current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
Log.i("abc", "ABC + totalItemCount > previousTotalItemCount");
loading = false;
previousTotalItemCount = totalItemCount;
currentPage++;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to
// fetch the data.
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
Log.i("abc", "ABC + !loading");
onLoadMore(currentPage + 1, totalItemCount);
loading = true;
}
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount);
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}
I want load more 7 pages
In your LoadData AsyncTask, in onPostExecute, you always re-create the adapter with new data received, so it does not append the existing data.
What you need to do is add a method to InfoTeacher adapter to append new items to your existing data, and then call that method from onPostExecute if the adapter already exists (adapter != null).

EmptyView in ListView in ActionBarActivity appears on page even though the list is not empty

EmptyView in ListView appears on page even though the list is not empty.
(I'm not using ListActivity)
Even when I remove the setEmptyView(...) it makes no change!
What am I supposed to do?
Here is the code to my List Fragment:
public class SearchResultListFragment extends Fragment{
Pagination pagination;
boolean loadingMore = false;
ListView list;
TextView text1;
TextView text2;
TextView text3;
TextView text4;
TextView text5;
Button Btngetdata;
private static String url = "https://www.....com/api/property/search";
private static int currentFirstVisibleItem;
public SearchResultArrayListAdaptor adapter ;
LinearLayout linlaHeaderProgress;
JSONArray jsonArray = null;
JSONParse fetchclass = null;
public SearchResultListFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linlaHeaderProgress = (LinearLayout) getActivity().findViewById(R.id.linlaHeaderProgress);
ArrayAdapter<PropertyObject> aa =(ArrayAdapter<PropertyObject>) list.getAdapter();
if (aa!= null){
aa.clear();
aa.notifyDataSetChanged();
}
list.setOnItemClickListener((OnItemClickListener) getActivity());
adapter = new SearchResultArrayListAdaptor(getActivity(), R.layout.list_view_items, new ArrayList<PropertyObject>());
list.setAdapter(adapter);
pagination = new Pagination(0,15);
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search_result_list, container, false);
list=(ListView)rootView.findViewById(R.id.listViewSearchResult);
list.setOnScrollListener(
new OnScrollListener(){
private int currentVisibleItemCount;
private int currentTotalItemCount;
private int currentScrollState;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
if(fetchclass!=null) {
pagination = new Pagination(this.currentTotalItemCount,15);
if(!(fetchclass.getStatus()== AsyncTask.Status.RUNNING)) {
fetchclass= new JSONParse(getActivity());
fetchclass.execute(url);
}
}
else {
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
});
return rootView;
}
//*********************************** inner class
public class JSONParse extends AsyncTask<String, String, JSONObject> {
Context mContext;
int checkBoxRooms;
public JSONParse(Context context){
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject json = null;
PropertyFilter searchFilter = SearchFilterManager.initializePropertyFilter(new PropertyFilter(), getArguments());
getActivity().setProgressBarIndeterminateVisibility(true);
JSONParserForSearch jParser = new JSONParserForSearch();
json = jParser.getJSONFromUrl(url, searchFilter, pagination);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// SHOW THE SPINNER WHILE LOADING FEEDS
getActivity().setProgressBarIndeterminateVisibility(false);
PropertyObject propertyObject;
try {
jsonArray = json.getJSONArray("PropertyListings");
if (jsonArray == null || jsonArray.length()<1){
// list.setEmptyView(getActivity().findViewById(R.id.txtNoResult));
}
else {
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
adapter.add(propertyObject);
adapter.notifyDataSetChanged();
}
}
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.khoonat.khoonat2.SearchResultListActivity$SearchResultListFragment">
<ListView
android:id="#+id/listViewSearchResult"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
>
</ListView>
<LinearLayout
android:id="#+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone"
>
My Adapter is ArrayAdapter.
I have implemented isEmpty and getCount too.
Here is my Adapter:
public class SearchResultArrayListAdaptor extends ArrayAdapter<PropertyObject>{
Context context;
int layoutResourceId; // This is the layout you created for the list items
ArrayList<PropertyObject> items;
public SearchResultArrayListAdaptor(Context context, int layoutResourceId, ArrayList<PropertyObject> items) {
super(context, layoutResourceId, items);
this.items = items;
this.layoutResourceId = layoutResourceId;
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
TextView txtLarge1 =
(TextView)row.findViewById(R.id.listViewSearchResultTxtLarge1);
TextView txtLarge2 =
(TextView)row.findViewById(R.id.listViewSearchResultTxtLarge2);
#Override
public int getCount() {
if (items == null)
return 0;
else
return items.size();
}
#Override
public boolean isEmpty(){
if (items == null || items.size()==0)
return true;
return false;
}
My Activity For List:
public class SearchResultListActivity extends ActionBarActivity implements OnItemClickListener{
static PropertyObject selectedPropertyObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle=new Bundle();
bundle.putInt("intentionOfOwner", intent.getIntExtra("intentionOfOwner",0));
SearchResultListFragment fragobj=new SearchResultListFragment();
fragobj.setArguments(bundle);
///back button
setContentView(R.layout.activity_search_result_list);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, fragobj).commit();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View textView, int rowNumber, long arg3) {
Intent intent = new Intent(this, PropertyDetailActivity.class);
PropertyObject po = (PropertyObject) arg0.getAdapter().getItem((int)arg3);
intent.putExtra("listingID",po.getID());
startActivity(intent);
}
any guess?
thanks a lot in advance.
I think the problem is around here, not applicable if you are doing lazy list loading
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
adapter.add(propertyObject);
adapter.notifyDataSetChanged();
}
try like
ArrayList<PropertyObject> items = new ArrayList<PropertyObject>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
items.add(propertyObject);
}
adapter.items = items;
adapter.notifyDataSetChanged();

setOnScrollListener of ListView interrupts setOnItemClickListener

It took me two(!) days to figure out my problem.
I have ListView with both onItemClickListener and onScrollListner. If I implement the onScrollListner then no ItemClick actions are fired.
I saw this problem here: setOnScrollListener with setOnItemClickListener and here:Android: cannot set both: setOnItemClickListener setOnScrollListener? with no real solution.
I have also noticed (in the emulator) that when one of the rows (in the ListView) is selected then ItemClick does fire (I assume that it works in not touch mode).
Very frustrating, can anyone think of a solution?
Some code:
Custom ListView
public class CustomHomeListView extends ListView implements android.widget.AdapterView.OnItemClickListener, OnScrollListener, IReceiver {
public static final String TAG = CustomHomeListView.class.getSimpleName();
private static Context mContext;
List<DiscussionModel> mDiscussionsArray = new ArrayList<DiscussionModel>();
private DiscussionsCustomAdapter mAdapter;
private boolean mIsLoading;
private int mCurrentMinDiscussionRowIndex;
private View mFooterView;
private int mFirstVisiblePosition;
private int mSelectedItemPosition;
private int mDividerHeight;
private int mSavedPositionInsideListView;
public MyResultReceiver mReceiver;
public void onCreate() {
// for computing scroll position to an item after data fetch
mDividerHeight = getDividerHeight();
mSavedPositionInsideListView = 0;
// prepare ResultReceiver for informing that puller service is done
mReceiver = new MyResultReceiver(new Handler());
mReceiver.setReceiver(this);
mCurrentMinDiscussionRowIndex = -1; // default value for retrieving most
// recent
// posts from web
mAdapter = new DiscussionsCustomAdapter(mContext);
CrowdietApplication cda = (CrowdietApplication) mContext.getApplicationContext();
mAdapter.setCurrentUserUid(cda.getUserId());
setAdapter(mAdapter);
setOnScrollListener(this);
setOnItemClickListener(this);
mFooterView = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.home_list_view_footer, null);
//setCustomHomeListViewOnScrollListener();
pullDiscussions();
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DiscussionModel discussion = mDiscussionsArray.get(position);
Intent intent = new Intent(mContext, DiscussionActivity.class);
intent.putExtra(CONSTS_DISCUSSIONS.DISCUSSION_ID_FROM_CALLING_ACTIVITY, discussion.getDiscussionId());
mContext.startActivity(intent);
}
public void refresh() {
mCurrentMinDiscussionRowIndex = -1;
pullDiscussions();
}
private void pullDiscussions() {
mIsLoading = true;
// preparing puller service
Intent intent = new Intent(mContext, PullDiscussionsListIntentService.class);
intent.putExtra(CONSTS_APP_SIGNALS.MIN_DISCUSSION_ROW_INDEX_TO_FETCH, mCurrentMinDiscussionRowIndex);
intent.putExtra(CONSTS_APP_SIGNALS.RECEIVER_TAG, mReceiver);
mContext.startService(intent);
}
private void refreshListFromDatabase() {
DbDiscussions dbDiscussions = new DbDiscussions(mContext);
Cursor discussionsCursor;
discussionsCursor = dbDiscussions.getDiscussions();
if (discussionsCursor != null && discussionsCursor.getCount() > 0) {
prepareDiscussionsArray(discussionsCursor);
mCurrentMinDiscussionRowIndex = dbDiscussions.getMinDiscussionRowIndex();
mAdapter.setData(mDiscussionsArray);
mAdapter.notifyDataSetChanged();
mIsLoading = false;
}
discussionsCursor.close();
dbDiscussions.destroy();
}
private void prepareDiscussionsArray(Cursor discussionsCursor) {
mDiscussionsArray.clear();
int noOfReturnedDiscussions = discussionsCursor.getCount();
discussionsCursor.moveToFirst();
for (int i = 0; i < noOfReturnedDiscussions; i++) {
DiscussionModel discussion = new DiscussionModel();
discussion.setDiscussionId(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_DISCUSSION_ID)));
discussion.setDiscussionTitle(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_DISCUSSION_TITLE)));
discussion.setUsername(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_USERNAME)));
mDiscussionsArray.add(discussion);
discussionsCursor.moveToNext();
}
}
private int calcItemPosition() {
int posInListView = 0;
for (int i = 0; i < mSelectedItemPosition - mFirstVisiblePosition - 1; i++) {
View child = getChildAt(i);
if (child == null) {
break;
}
posInListView += child.getHeight() + mDividerHeight;
}
// Log.d(TAG, "measured height :" + posInListView);
return posInListView;
}
public CustomHomeListView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
private void prepareForMySetSelection() {
if (mSelectedItemPosition > -1) {
mSavedPositionInsideListView = calcItemPosition();
}
}
private void mySetSelection() {
if (mSelectedItemPosition > -1) {
setSelectionFromTop(mSelectedItemPosition, mSavedPositionInsideListView);
} else {
setSelection(mFirstVisiblePosition);
}
}
public void onReceiveResult(int resultCode, Bundle resultData) {
prepareForMySetSelection(); // should be before
// RefreshListFromDatabase() so that
// actual position inside adapter is
// saved
refreshListFromDatabase();
setAdapter(mAdapter);
mySetSelection();
// }
removeFooterView(mFooterView);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mFirstVisiblePosition = getFirstVisiblePosition();
mSelectedItemPosition = getSelectedItemPosition();
if (mAdapter != null && mAdapter.getCount() > 0) {
int l = visibleItemCount + firstVisibleItem;
if (l >= totalItemCount && !mIsLoading) {
addFooterView(mFooterView);
pullDiscussions();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
}

Categories

Resources