Append Data Load More Listview - android

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).

Related

notifyDataSetChanged() makes the list refresh and scroll jumps back to the top of list

This is the main class. When I scroll down for more data and call the adapter, the list refreshes and scrolling jumps back to the top of list. I tried this for two days, but the issue remains.
I want the same position of list when scrolling down position.
public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
ArrayList<String> home_youmay_filepath = new ArrayList<String>();
ListView listViewyoumay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
listViewyoumay = (ListView) findViewById(R.id.lvItems);
// Attach the listener to the AdapterView onCreate
listViewyoumay.setOnScrollListener(new EndlessScrollListener() {
#Override
public boolean onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to your AdapterView
youmaylike(page);
// or customLoadMoreDataFromApi(totalItemsCount);
return true; // ONLY if more data is actually being loaded; false otherwise.
}
});
youmaylike(1);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
private void youmaylike(int a) {
showpDialog();
Log.d("Starta", "Start" + a);
String url = "http://v2.picsdream.com/api/v1/galleries/abstract?page=" + a;
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("cmsResponce", response.toString());
try {
JSONObject cards = response.getJSONObject("cards");
JSONArray data = cards.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject person = (JSONObject) data
.get(i);
String filepath = person.getString("filepath");
home_youmay_filepath.add(filepath);
}
PhotofargmentAdapteryoumay adapter3 = new PhotofargmentAdapteryoumay(MainActivity.this, home_youmay_filepath);
listViewyoumay.setAdapter(adapter3);
adapter3.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("LoginError", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
public class PhotofargmentAdapteryoumay extends BaseAdapter {
ArrayList<String> home_youmay_filepath = new ArrayList<String>();
private LayoutInflater layoutInflater;
Context context;
public PhotofargmentAdapteryoumay(Context Time_table, ArrayList<String> home_youmay_filepath) {
this.context = Time_table;
this.home_youmay_filepath = home_youmay_filepath;
layoutInflater = LayoutInflater.from(Time_table);
}
#Override
public int getCount() {
return home_youmay_filepath.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.photoadapter_layout, null);
holder = new ViewHolder();
// holder.month = (TextView) convertView.findViewById(R.id.tvtext);
holder.img = (ImageView) convertView.findViewById(R.id.img_nature);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// holder.month.setText(listData.get(position).getMonth());
String image = home_youmay_filepath.get(position);
Log.d("Image", image);
try {
Picasso.with(context)
.load(image).noFade()
.into(holder.img);
// ImageLoader imgLoader = new ImageLoader(HomeActivity.this);
//
// imgLoader.DisplayImage(image, holder.img);
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
class ViewHolder {
// TextView month;
ImageView img;
}
}
public abstract class EndlessScrollListener implements AbsListView.OnScrollListener {
// The minimum number of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 50;
// The current offset index of data you have loaded
private int currentPage = 1;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 50;
// 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 = 1;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
// this.startingPageIndex = startPage;
this.currentPage = startPage;
}
#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) {
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)) {
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 && (firstVisibleItem + visibleItemCount + visibleThreshold) >= totalItemCount) {
loading = onLoadMore(currentPage + 1, totalItemCount);
}
}
// Defines the process for actually loading more data based on page
// Returns true if more data is being loaded; returns false if there is no more data to load.
public abstract boolean onLoadMore(int page, int totalItemsCount);
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}
}
PhotofargmentAdapteryoumay adapter3 = new PhotofargmentAdapteryoumay(MainActivity.this, home_youmay_filepath);
listViewyoumay.setAdapter(adapter3);
Remove this lines

Restarting Asynctask in fragment after using replace transaction

I am using AsyncTask in my fragment for loading a list of data by Json. After clicking each list items this list fragment is replaced by details fragment containing details information. Then in new fragment (details fragment) user presses back button. Then again list fragment starts.
The problem is that Asynctask reloads again to fetch list items. I don't want this. I want to show previously loaded list. Here is the code:
public class MainList extends Fragment {
public MainList(){}
ArrayList<Country> countryList = new ArrayList<Country>();
Country country;
Button btnLoadMore;
ListView listView;
JSONParser jsonParser = new JSONParser();
public static String received_id;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
int current_page = 0;
int last_item;
int total_items = 32;
boolean continue_loading = true;
boolean loadingMore = false;
View footerView;
public ImageLoader_Json imageLoader;
int currentPosition = 0;
MyCustomAdapter dataAdapter = null;
private static String url_all_products_LoadMore = "http://www.hitel.ir/FarsiPlanet/Apps.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_RATE = "rate";
private static final String TAG_RATINGCOUNT = "ratingcount";
private static final String TAG_SHORT_DESCRIPTION = "short_description";
// products JSONArray
JSONArray products = null;
String Category;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.items_list, container, false);
Category = getArguments().getString("category");
footerView= ((LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_footer, null,false);
listView = (ListView) rootView.findViewById(R.id.listView1);
listView.addFooterView(footerView);
imageLoader = new ImageLoader_Json(getActivity().getApplicationContext());
displayListView();
return rootView;
}
private void displayListView() {
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.country_info, countryList);
listView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new loadMoreListView().execute();
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
Bundle data = new Bundle();
data.putString(TAG_PID, pid);
data.putString("TAG_Category", Category);
Fragment fragment = new Details_Restaurant();
FragmentManager fm = getFragmentManager();
fragment.setArguments(data);
fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02").commit();
}
});
listView.setAdapter(dataAdapter);
listView.setSelectionFromTop(currentPosition, 0);
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
RatingBar rate;
TextView ratingcount;
TextView short_description;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ratingcount = (TextView) convertView.findViewById(R.id.ratingCount);
holder.short_description = (TextView) convertView.findViewById(R.id.short_description);
holder.rate = (RatingBar) convertView.findViewById(R.id.ratingBar1);
holder.code = (TextView) convertView.findViewById(R.id.pid);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Country country = countryList.get(position);
holder.name.setText(country.getName());
holder.ratingcount.setText(country.getRatingCount());
holder.short_description.setText(country.getShort_description());
holder.rate.setRating(country.getRate());
holder.code.setText(country.getCode());
return convertView;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
class loadMoreListView extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("درحال دريافت اطلاعات...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show(); */
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
String firts_item = Integer.toString(current_page*10);
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", firts_item));
params.add(new BasicNameValuePair("category", Category));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_all_products_LoadMore, "GET", params);
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Float rate = (float) c.getInt(TAG_RATE);
String ratingcount = c.getString(TAG_RATINGCOUNT);
String short_description = c.getString(TAG_SHORT_DESCRIPTION);
country = new Country(id,name,rate,ratingcount,short_description,"","");
countryList.add(country);
}
}
else{
continue_loading = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
current_page += 1;
if (continue_loading) {
currentPosition = listView.getFirstVisiblePosition();
dataAdapter.notifyDataSetChanged();
displayListView();
loadingMore = false;
} else {
listView.removeFooterView(footerView);
}
}
}
}
Here you need to include #Override before calling onScrollStateChanged and onScroll
listView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new loadMoreListView().execute();
}
}
});
when you perform the replace() action on the fragment, you are removing the list fragment , thus when tapping back, you are replacing the details fragment with your listfragment which invokes onCreateView() as part of the fragments lifecycle.
I would try to either keep a static booelan set to true when the asynctask's onPostExecute() ends, so the next time the list fragment's onCreateView() will be invoked , you would check the value of the flag and if set to true will not execute the task, but just set the adapter with the old static data.

i am getting image url from json and they are loading successfully in grid view but after then scroll previous image replace by below images

one problem in there after the scroll gridview previous image replace by below images and again scroll up its again load i want its load one time and never be change on scroll.my app url is https://play.google.com/store/apps/details?id=com.vaibhavtech.mbmovies
public class NewMovie extends Activity {
private GridView lv;
private Vibrator vibrator;
private ArrayList<DataDemo> mDemoDataAl;
private ProgressDialog progressDialog;
private String mStringURL = "";
private ImageLoader mImageLoader = null;
protected static final int SHOW_PROGRESS_DIALOG = 0;
protected static final int STOP_PROGRESS_DIALOG = 1;
protected static final int NETWORK_FAILURE = 2;
protected static final int PROBLEM_IN_CONNECTING_SERVER = 3;
protected static final int SET_ADAPTER = 4;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.new_movie);
setProgressBarIndeterminateVisibility(true);
setProgressBarIndeterminateVisibility(false);
super.onCreate(savedInstanceState);
mDemoDataAl = new ArrayList<DataDemo>();
mImageLoader = ImageLoader.getInstance();
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
lv = (GridView) findViewById(R.id.grid_view);
mStringURL = "http://vaibhavtech.com/work/android/movie_list.php?category="
+ MainActivity.movie_Category + "&sub_category=new";
Log.d("The Url is ", " URL : " + mStringURL);
lv.setOnScrollListener(new EndlessScrollListener());
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// // TODO Auto-generated method stub
vibrator.vibrate(40);
MainActivity.movie_Id = ((TextView) arg1
.findViewById(R.id.tv_girdview_content_id)).getText()
.toString();
startActivity(new Intent(NewMovie.this, MovieDescription.class));
}
});
new GetDemoData().execute();
}
private class GetDemoData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
JSONObject json = JSONfunctions.getJSONfromURL(mStringURL,
NewMovie.this);
if (json != null) {
JSONArray MoviesArray = json.getJSONArray("Demo");
for (int i = 0; i < MoviesArray.length(); i++) {
DataDemo mDemoData = new DataDemo();
mDemoData.setmDemoId(MoviesArray.getJSONObject(i)
.getString("id"));
mDemoData.setmDemoTitle(MoviesArray.getJSONObject(i)
.getString("title"));
mDemoData.setmDemoYear(MoviesArray.getJSONObject(i)
.getString("year"));
mDemoData.setmDemoDuration(MoviesArray.getJSONObject(i)
.getString("duration"));
mDemoData.setmDemoPoster(MoviesArray.getJSONObject(i)
.getString("poster"));
mDemoDataAl.add(mDemoData);
}
} else {
mHandler.sendEmptyMessage(PROBLEM_IN_CONNECTING_SERVER);
}
} catch (Exception e) {
Log.d("Exceptions",
" The Xception messages are " + e.getMessage());
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);
mDemoDataAl.clear();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mHandler.sendEmptyMessage(SET_ADAPTER);
mHandler.sendEmptyMessage(STOP_PROGRESS_DIALOG);
}
}
public class NewMoviesAdapter extends BaseAdapter {
private LayoutInflater mInflater = null;
public NewMoviesAdapter() {
mInflater = LayoutInflater.from(NewMovie.this);
}
public int getCount() {
return mDemoDataAl.size();
}
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.grid_view_content,
null);
holder = new ViewHolder();
holder.txtMovieId = (TextView) convertView
.findViewById(R.id.tv_girdview_content_id);
holder.txtMovieDuration = (TextView) convertView
.findViewById(R.id.tv_girdview_content_listner);
holder.txtMovieName = (TextView) convertView
.findViewById(R.id.tv_girdview_content_name);
holder.txtMovieYear = (TextView) convertView
.findViewById(R.id.tv_girdview_content_like);
holder.imgMovie = (ImageView) convertView
.findViewById(R.id.iv_girdview_content_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.txtMovieId.setText(Utils
.asUpperCaseFirstChar(mDemoDataAl.get(position)
.getmDemoId()));
holder.txtMovieDuration.setText(mDemoDataAl.get(position)
.getmDemoDuration());
holder.txtMovieName.setText(Utils
.asUpperCaseFirstChar(mDemoDataAl.get(position)
.getmDemoTitle()));
holder.txtMovieYear.setText(mDemoDataAl.get(position)
.getmDemoYear());
mImageLoader.displayImage(
"http://vaibhavtech.com/work/android/admin/upload/"
+ mDemoDataAl.get(position).getmDemoPoster(),
holder.imgMovie);
} catch (Exception e) {
}
return convertView;
}
class ViewHolder {
public TextView txtMovieId;
public TextView txtMovieDuration;
public TextView txtMovieName;
public TextView txtMovieYear;
public ImageView imgMovie;
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 5;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
// new do.execute(currentPage + 1);
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SHOW_PROGRESS_DIALOG:
if (progressDialog == null) {
progressDialog = Utils.createProgressDialog(NewMovie.this);
progressDialog.setMessage("Loding...");
progressDialog.show();
} else {
progressDialog.show();
}
mHandler.removeMessages(SHOW_PROGRESS_DIALOG);
break;
case STOP_PROGRESS_DIALOG:
progressDialog.dismiss();
mHandler.removeMessages(STOP_PROGRESS_DIALOG);
break;
case NETWORK_FAILURE:
Utils.displayToast(NewMovie.this,
Constant.NO_NETWORK_CONNECTION);
mHandler.removeMessages(NETWORK_FAILURE);
break;
case PROBLEM_IN_CONNECTING_SERVER:
Utils.displayToast(NewMovie.this,
Constant.PROBLEM_IN_CONNECTING_SERVER);
mHandler.removeMessages(PROBLEM_IN_CONNECTING_SERVER);
break;
case SET_ADAPTER:
lv.setAdapter(new NewMoviesAdapter());
mHandler.removeMessages(SET_ADAPTER);
break;
default:
break;
}
};
};
}
newmovie.xml**************************
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp"
android:orientation="vertical" >
<GridView
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="377dp"
android:horizontalSpacing="10dp"
android:numColumns="2"
android:verticalSpacing="10dp" >
</GridView>
</LinearLayout>
mainactivity.java
public class MyApplication extends Application {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
It should help you: Universal Image Loader for Android. I was tried it and I can say that it's simple and practical.

ListView shows wrong placement of images taken from URL

My listview doesn't show exact placement of images on its individual custom adapters. I am trying to load the images using AsyncTask. Sometimes the images duplicates and I don't have any idea why. Here is my ArrayAdapter code:
public class NewsPromoAdapter extends ArrayAdapter<NewsPromosDTO> {
private final Context context;
List<NewsPromosDTO> npList;
LayoutInflater inflater;
Bitmap src;
public NewsPromoAdapter(Context context, List<NewsPromosDTO> npList) {
super(context, R.layout.news_and_promos, npList);
this.context = context;
this.npList = npList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
TextView nameText;
TextView date1Text;
ImageView imageView;
ProgressBar prg;
LoadImage loadImg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.news_and_promos, parent,
false);
holder = new ViewHolder();
holder.nameText = (TextView) convertView
.findViewById(R.id.newspromo_name);
holder.date1Text = (TextView) convertView
.findViewById(R.id.newspromo_date);
holder.imageView = (ImageView) convertView
.findViewById(R.id.newspromo_imageView);
holder.prg = (ProgressBar) convertView
.findViewById(R.id.progressBar1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.loadImg.cancel(true);
}
if (!(npList.get(position).getName().equals(""))) {
holder.nameText.setVisibility(View.VISIBLE);
holder.nameText.setText(npList.get(position).getName());
} else {
holder.nameText.setVisibility(View.GONE);
}
if (!(npList.get(position).getDate().equals(""))) {
holder.date1Text.setVisibility(View.VISIBLE);
holder.date1Text.setText(npList.get(position).getDate());
} else {
holder.date1Text.setVisibility(View.GONE);
}
if (!(npList.get(position).getImageURL().equals(""))) {
holder.imageView.setVisibility(View.VISIBLE);
holder.loadImg = new LoadImage(holder.imageView, npList.get(
position).getImageURL(), holder);
holder.loadImg.execute();
} else {
holder.imageView.setVisibility(View.GONE);
holder.prg.setVisibility(View.GONE);
}
return convertView;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap> {
ViewHolder viewH;
private ImageView imv;
private String url;
public LoadImage(ImageView imv, String imageURL, ViewHolder viewH) {
this.imv = imv;
this.url = imageURL;
this.viewH = viewH;
}
#Override
protected Bitmap doInBackground(Object... params) {
BitmapFromURL bmpURL = new BitmapFromURL();
src = bmpURL.getBitmapFromURL(url);
return src;
}
#Override
protected void onPostExecute(Bitmap result) {
// imv.setImageBitmap(result);
// viewH.prg.setVisibility(View.GONE);
viewH.prg.setVisibility(View.GONE);
imv.setImageBitmap(result);
}
}
}
Here is the Activity that handles the ADAPTER. I am implementing the Endless listview approach that some big sites uses. Like Facebook, Twitter, etc..New Items loaded into the listview when scrolling into the bottom. I am not sure if I did it well.
public class ListNewsPromoActivity extends Activity {
List<NewsPromosDTO> npList;
String url, user_email;
Bundle extras;
int user_points;
List<Integer> npIDs;
private ProgressDialog progressDialog;
BitmapFromURL bmpURL;
JSONArray users = null;
String TAG_ID = "id";
String TAG_NAME = "name";
String TAG_PHOTO = "photo";
String TAG_DATE = "date";
String TAG_DESC = "description";
ListView list;
NewsPromoAdapter newsAdapter;
boolean loadingMore = false;
private Runnable returnRes;
int itemsPerPage = 3;
int currentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.news_promo_listview);
list = (ListView) findViewById(R.id.mainView);
extras = getIntent().getExtras();
if (extras != null) {
user_points = extras.getInt("user_points");
user_email = extras.getString("user_email");
}
url = getString(R.string.app_url_news_promos);
npIDs = new ArrayList<Integer>();
npList = new ArrayList<NewsPromosDTO>();
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
list.setOnScrollListener(new OnScrollListener() {
// useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
// is the bottom item visible & not loading more already ? Load
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
Thread thread = new Thread(null, getRunnable());
thread.start();
}
}
});
// Runnable to load the items
// Since we cant update our UI from a thread this Runnable takes care of
// that!
returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
for (NewsPromosDTO np : npList) {
System.out.println(np.getName() + " andito ako!!");
newsAdapter.add(np);
}
newsAdapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
}
protected class loadNewsPromo extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
// Creating JSON Parser instance
loadingMore = true;
JSONParser jParser = new JSONParser();
JSONObject json;
if (jParser.checkServer(url)) {
try {
// Getting Array of UserNews
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All UserNews
for (int i = currentIndex; i < itemsPerPage; i++) {
if (itemsPerPage == i) {
// currentIndex--;
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
} finally {
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) { //
// progressDialog.dismiss();
loadingMore = false;
list();
}
}
public void list() {
// add the footer before adding the adapter, else the footer will not
// load!
View footerView = ((LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.footer, null, false);
newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);
list.addFooterView(footerView);
list.setAdapter(newsAdapter);
}
public Runnable getRunnable() {
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Get 15 new listitems
JSONParser jParser = new JSONParser();
JSONObject json;
npList = new ArrayList<NewsPromosDTO>();
if (jParser.checkServer(url)) {
try {
// Getting Array of Contacts
json = jParser.getJSONFromUrl(url);
users = json.getJSONArray(user_email);
// looping through All Contacts
// if (itemsPerPage > users.length() - currentIndex) {
// itemsPerPage = users.length();
// }
npList = new ArrayList<NewsPromosDTO>();
System.out.println(users.length() + " Laman ng users");
int counter = 0;
for (int i = currentIndex; i < users.length(); i++) {
if (itemsPerPage == counter) {
break;
} else {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
NewsPromosDTO npDTO = new NewsPromosDTO();
npDTO.setImageURL(c.getString(TAG_PHOTO));
npDTO.setId(c.getInt(TAG_ID));
npDTO.setName(c.getString(TAG_NAME));
npDTO.setDate(c.getString(TAG_DATE));
npDTO.setDescription(c.getString(TAG_DESC));
npList.add(npDTO);
currentIndex++;
}
counter++;
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
}
// Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
return loadMoreListItems;
}
}

ListView - ListView don't update

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)

Categories

Resources