ListView load more on scroll bottom - android

In MainActivity I create the DownloadTask which populate model class then listview via CustomListAdapter class but I created the function to recognize end of scroll and I want to load more items to the listview. I was reading and looking at code on internet but I can't figure it out to solve this because its a kind different.
The MainActivity class
public void updateList() {
adap = new CustomListAdapter(this, feedList, null);
feedListView.setAdapter(adap);
feedListView.setOnScrollListener(new OnScrollListener() {
public void onScrollStateChanged(AbsListView view,
int scrollState) { // TODO Auto-generated method stub
int threshold = 1;
int count = feedListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (feedListView.getLastVisiblePosition() >= count
- threshold) {
mHandler = new Handler();
mIsLoading = true;
Toast.makeText(getApplicationContext(), "END", Toast.LENGTH_LONG).show();
}
}
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
}
public class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
if (null != feedList) {
updateList();
}
if (progressbar.isShown()) {
progressbar.setVisibility(View.INVISIBLE);
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
/////.....
feedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomListAdapter
public class CustomListAdapter extends BaseAdapter
{
private int mCount = 25;
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
private ArrayList<String> data;
protected ListView feedListView;
public CustomListAdapter( Context context, ArrayList<FeedItem> listData)
{
this.listData = listData;
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
}
public void addMoreItems(int count) {
mCount += count;
notifyDataSetChanged();
}
#Override
public int getCount()
{
return mCount;
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position)
{
return position;
}
public View getView( int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
View row=convertView;
if ((row == null) || (row.getTag()==null)) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
////
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
final FeedItem newsItem = (FeedItem) listData.get(position);
/////
return convertView;
}
static class ViewHolder
{
////
}
}
When I reach the bottom the toast is created.

Instead of using OnScrollListener, you can compare position to list data size and load more items accordingly within your adapter class.
public View getView( int position, View convertView, ViewGroup parent){
if(position == getCount()-1){
// load new items here. you can do a for loop here, if you'd like to add multiple items.
addMoreItems(newItem);
}
// rest of the getView implementation
}
And you also need to update the following methods:
public void addMoreItems(FeedItem newItem) {
listData.add(newItem); // since you want to add this item at the end of the list
notifyDataSetChanged();
}
#Override
public int getCount(){
return listData.size();
}
#Override
public Object getItem(int position){
return listData.get(position);
}
And don't create a new adapter when you want to update your listView, like you did in your update method. If you do that, it'll get rid of the previous content. Instead, just call addMoreItems method of your adapter, it'll do the trick for you.

#Override
public void onScrollStateChanged(int scrollState) {
// TODO Auto-generated method stub
if(scrollState==RecyclerView.SCROLL_STATE_IDLE){
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleThreshold) <= (firstVisibleItem + visibleItemCount)) {
Log.v("scroll","Last Item Wow !");
if(footerView.getVisibility()!=View.VISIBLE){
footerView.setVisibility(View.VISIBLE);
}
refreshExpListViewData();
}
}
}

A very simple way to implement "endless scrolling" is to use the EndlessAdapter library by commonsguy.
https://github.com/commonsguy/cwac-endless

Related

Fragment, Volley and RecyclerView

I hope someone out there can help me solve my problem. I have android app that have 3 tabs, i use fragment, first tab is recyclerView list, second tabs is map. the problem is in tabs 1, i need to fetch data with volley to recyclerView on tabs 1, if run fine but i cannot see the data on first app start, but when i change tab and back to tab 1 again it will refresh the data and show the data on recyclerView.
Adapter.java
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Warkop> mWarkop;
private LayoutInflater inflater;
public CustomListAdapterWarkop(Context context, List<Warkop> mWarkop) {
this.context=context;
inflater= LayoutInflater.from(context);
this.mWarkop = mWarkop;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_warkop_row, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder viewHolder = (ItemViewHolder) holder;
Warkop current = mWarkop.get(position);
viewHolder.tvNamaWarkop.setText(current.getNamaWarkop());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.noimage)
.showImageOnFail(R.drawable.noimage)
.showImageOnLoading(R.drawable.noimage).build();
imageLoader.displayImage(current.getFotoWarkop(), viewHolder.ivFotoWarkop, options);
}
#Override
public int getItemCount() {
return mWarkop.size();
}
}
ItemHolder.java
package com.andylah.warkopedia;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by andylah on 11/3/2017.
*/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public ImageView ivFotoWarkop;
public TextView tvNamaWarkop;
public ItemViewHolder(View itemView) {
super(itemView);
tvNamaWarkop = itemView.findViewById(R.id.nama_warkop);
ivFotoWarkop = itemView.findViewById(R.id.image_warkop);
}
}
Tab 1.java
public class tabSatu extends Fragment {
private static final String TAG = tabDua.class.getSimpleName();
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private boolean isFragmentLoaded = false;
View vTabSatu;
private RecyclerView recyclerView;
public static List<Warkop> warkopList = new ArrayList<Warkop>();
private CustomListAdapterWarkop warkopAdapter;
public tabSatu(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new AsyncFetch().execute();
vTabSatu = inflater.inflate(R.layout.tabsatu_view, container, false);
recyclerView = vTabSatu.findViewById(R.id.warkop_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
Log.d("LOG : ", "onCreatedView Run");
// Inflate the layout for this fragment
return vTabSatu;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
Log.d("LOG : ", "onViewCreated Run");
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isFragmentLoaded ) {
// Load your data here or do network operations here
isFragmentLoaded = true;
//new AsyncFetch().execute();
}else{
isFragmentLoaded = false;
Log.d("LOG : ", "isFragmentLoaded = false");
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pDialog = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading list warkop ...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL(AppConfig.LOAD_WARKOP);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try{
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if(!error){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
warkop.setNamaWarkop(jsonObject.getString("nama_warkop"));
warkop.setAlamatWrkop(jsonObject.getString("alamat_warkop"));
warkop.setKotaWarkop(jsonObject.getString("kota_warkop"));
warkop.setLatWarkop(Double.parseDouble(jsonObject.getString("lat_warkop")));
warkop.setLangWarkop(Double.parseDouble(jsonObject.getString("long_warkop")));
warkop.setIsWifi(Integer.parseInt(jsonObject.getString("is_wifi")));
warkop.setIsToilet(Integer.parseInt(jsonObject.getString("is_toilet")));
warkop.setIsTv(Integer.parseInt(jsonObject.getString("is_tv")));
warkop.setIsColokan(Integer.parseInt(jsonObject.getString("is_colokan")));
warkop.setIsParkir(Integer.parseInt(jsonObject.getString("is_parkir")));
warkop.setFotoWarkop(jsonObject.getString("foto_warkop"));
warkopList.add(warkop);
}
}else{
String errorMsg = object.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Problem: Even you call notifyDataSetChanged() but there are no data in Adapter.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
warkopAdapter = new CustomListAdapterWarkop(getActivity(), warkopList);
warkopAdapter.notifyDataSetChanged();
recyclerView.setAdapter(warkopAdapter);
}
So you need to set and notify warkopList to Adapter after API call. It will help you.
tabSatu:
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
try {
JSONObject object = new JSONObject(result);
String getObject = object.getString("warkop");
JSONArray jsonArray = new JSONArray(getObject);
boolean error = object.getBoolean("error");
if (!error) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Warkop warkop = new Warkop();
...
warkopList.add(warkop);
adapter.setItems(warkopList);
}
}
...
}
CustomListAdapterWarkop: add setItem() method to Adapter
public class CustomListAdapterWarkop extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
...
public void setItems(List<WarkopList> warkopList) {
mWarkop = warkopList;
notifyDataSetChanged();
}
...
}

I want to populate ListView with two TextViews and data from a remote server

I want to populate ListView with two TextViews and data from a remote server. here is my async class:
class Dataload extends AsyncTask<String,Void,ArrayAdapter> {
String returnString, s = "";
String name;
int quantity,price;
ArrayList<String> list = new ArrayList<String>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayAdapter adapter) {
ls.setAdapter(adapter);
}
#Override
protected ArrayAdapter doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("h", s));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://grclive.16mb.com/select_rum.php", postParameters);
String result = response.toString();
try {
returnString = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
name = json_data.getString("r_name");
quantity=json_data.getInt("r_quantity");
price=json_data.getInt("r_price");
list1.add(name + " " + quantity + " L" + " " + price + " ₹");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getApplicationContext(),R.layout.textfield, list1);
return adapter;
}
}
I wrote a custom adapter class for the ListView:
public class MyAdapter extends BaseAdapter {
Activity context;
ArrayList<String> list1;
TextView t1,t2;
MyAdapter(Activity context,ArrayList list1)
{
this.context=context;
this.list1=list1;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.list_text, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.t1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.t2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(list1.get(position));
// holder.txtViewDescription.setText(description[position]);
return convertView;
}
}
Now I want to send the ListView value to the adapter class to show in TextViews.
Please help me complete this.
You need to change this lines:
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
With this:
#Override
public int getCount() {
return list1.size();
}
#Override
public Object getItem(int position) {
return list1.get(position);
}

Call BaseAdapter In Fragment Close Application

Call BaseAdapter In Fragment Close Application
Comment in line spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
Work
Error Log
Class FragmentNews
public class FragmentNews extends Fragment {
ArrayList<Category> categorylist = new ArrayList<Category>();
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
return rootView;
}
class fechPosts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
ringProgressDialog = new ProgressDialog(getActivity());
ringProgressDialog.setMessage("در حال ارسال پیام");
ringProgressDialog.setCancelable(true);
ringProgressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = fetch(params[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Activity myActivity = getActivity();
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
ringProgressDialog.dismiss();
}
}
public String fetch(String titel) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = null;
httppost = new HttpGet(
"http://mynikan.ir/paliz/mobile/GetAllProduct.php");
String r = "ok";
String result = null;
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONArray array = null;
try {
array = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject json_data;
try {
json_data = array.getJSONObject(i);
Category obj = new Category();
obj.Image = json_data.getString("Product_Image");
obj.Title = json_data.getString("Price");
categorylist.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return r;
}
Class Adapter
public class Category_Adapter extends BaseAdapter {
public String[] items;
public LayoutInflater myinflater;
Context context;
static class ViewHolder
{
TextView text;
TextView price;
ImageView im;
}
public int[] picmenu;
ArrayList<Category> categorylist = new ArrayList<Category>();
public Category_Adapter(Context c, ArrayList<Category> pthemop) {
myinflater = LayoutInflater.from(c);
context = c;
categorylist = pthemop;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return categorylist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
// /////
if (convertView == null) {
convertView = myinflater.inflate(R.layout.snipper_single, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.im = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(categorylist.get(position).Title);
Picasso.with(context).load(categorylist.get(position).Image)
.into(holder.im);
return convertView;
}}
Class Category
public class Category {
String Title;
String Image;
}
Here:
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
line causing issue because spinner object of Spinner is null.
In onCreateView method creating new object instead of initializing object which is using in spinner.
Change onCreateView method as:
spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");

How to remove particular row from listview on button click(Android)

I have Custom Adapter class, in which on button click we make Asynchronous call to server. So in the onPostExecute() method i want to delete particular Row on which button is clicked. Here is My Adapter class
public class CartAdapter extends BaseAdapter {
private List<Products> cartList;
private LayoutInflater inflater;
Context context;
public static final String URLL ="http://192.168.1.3/wordpress/upmeapi/class-woocommerce.php?function=remove_cart_api";
RequestObject requestObject;
public CartAdapter(Context ctx,List<Products> list){
this.context = ctx;
this.cartList = list;
}
#Override
public int getCount() {
return cartList.size();
}
#Override
public Object getItem(int position) {
return cartList.get(position);
}
#Override
public long getItemId(int position) {
Products c = cartList.get(position);
long id = c.getProductId();
return id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
CartHolder holder = null;
if (row == null){
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.cartview_helper,parent,false);
holder = new CartHolder(row);
row.setTag(holder);
}
else {
holder =(CartHolder)row.getTag();
}
Products c = cartList.get(position);
Picasso.Builder builder = new Picasso.Builder(context);
Picasso picasso = builder.build();
picasso.with(context).cancelRequest(holder.myImage);
picasso.load(c.getProductImage())
.placeholder(R.drawable.ic_plusone_tall_off_client)
.resize(100,100)
.into(holder.myImage);
/* Picasso.with(context)
.load(c.getProductImage())
.placeholder(R.drawable.ic_plusone_tall_off_client)
.resize(100, 75)
.into(holder.myImage);*/
holder.title.setText(c.getTitle());
String stringdouble= Double.toString(c.getPrice());
holder.price.setText(stringdouble);
holder.quantity.setText(String.valueOf(c.getProductQuantity()));
holder.totalPrice.setText(c.getTotalPrice());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long productId = getItemId(position);
//holder.button.setTag(position);
try {
ProductHelper productHelper = new ProductHelper();
productHelper.setProductId(productId);
ObjectMapper objectMapper = new ObjectMapper();
String req = objectMapper.writeValueAsString(productHelper);
requestObject = ExceptionRequest.generateRequest(req);
requestObject.setUrl(URLL);
new RemovefromList().execute(requestObject);
}catch (Exception e) {
e.printStackTrace();
}
}
});
return row;
}
static class CartHolder {
ImageView myImage;
TextView title;
//TextView descriptions;
TextView price;
TextView quantity;
TextView totalPrice;
Button button;
public CartHolder(View v){
myImage =(ImageView)v.findViewById(R.id.imageView2);
title =(TextView)v.findViewById(R.id.carttitle);
// descriptions =(TextView)v.findViewById(R.id.product_description);
price =(TextView)v.findViewById(R.id.cart_price);
quantity =(TextView)v.findViewById(R.id.item_quantity);
totalPrice =(TextView)v.findViewById(R.id.sub_total);
button =(Button)v.findViewById(R.id.remove_cart);
}
}
private class RemovefromList extends AsyncTask<RequestObject, Void,JSONObject> {
#Override
protected JSONObject doInBackground(RequestObject... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// RequestObject requestObject = new RequestObject();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(arg0[0], ServiceHandler.POST);
JSONObject products = new JSONObject();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
products = jsonObj.getJSONObject("rsBody");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return products;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result!=null){
String status = result.getString("status");
// cartList.remove();
// notifyDataSetChanged();
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return;
}
}
}
inside onPostExecute() if i get status success this means on server side that particular product has been removed.but At our side we still see that products.
so i want to remove that row and also want to update count of cartitem.
Any help would be Appreciated in advanced.
please check this
send position in Async task constructor when button is clicked
private List<Products> cartList;
private LayoutInflater inflater;
Context context;
public static final String URLL ="http://192.168.1.3/wordpress/upmeapi/class-woocommerce.php?function=remove_cart_api";
RequestObject requestObject;
public CartAdapter(Context ctx,List<Products> list){
this.context = ctx;
this.cartList = list;
}
#Override
public int getCount() {
return cartList.size();
}
#Override
public Object getItem(int position) {
return cartList.get(position);
}
#Override
public long getItemId(int position) {
Products c = cartList.get(position);
long id = c.getProductId();
return id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
CartHolder holder = null;
if (row == null){
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.cartview_helper,parent,false);
holder = new CartHolder(row);
row.setTag(holder);
}
else {
holder =(CartHolder)row.getTag();
}
Products c = cartList.get(position);
Picasso.Builder builder = new Picasso.Builder(context);
Picasso picasso = builder.build();
picasso.with(context).cancelRequest(holder.myImage);
picasso.load(c.getProductImage())
.placeholder(R.drawable.ic_plusone_tall_off_client)
.resize(100,100)
.into(holder.myImage);
/* Picasso.with(context)
.load(c.getProductImage())
.placeholder(R.drawable.ic_plusone_tall_off_client)
.resize(100, 75)
.into(holder.myImage);*/
holder.title.setText(c.getTitle());
String stringdouble= Double.toString(c.getPrice());
holder.price.setText(stringdouble);
holder.quantity.setText(String.valueOf(c.getProductQuantity()));
holder.totalPrice.setText(c.getTotalPrice());
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long productId = getItemId(position);
//holder.button.setTag(position);
try {
ProductHelper productHelper = new ProductHelper();
productHelper.setProductId(productId);
ObjectMapper objectMapper = new ObjectMapper();
String req = objectMapper.writeValueAsString(productHelper);
requestObject = ExceptionRequest.generateRequest(req);
requestObject.setUrl(URLL);
new RemovefromList(position).execute(requestObject);
}catch (Exception e) {
e.printStackTrace();
}
}
});
return row;
}
static class CartHolder {
ImageView myImage;
TextView title;
//TextView descriptions;
TextView price;
TextView quantity;
TextView totalPrice;
Button button;
public CartHolder(View v){
myImage =(ImageView)v.findViewById(R.id.imageView2);
title =(TextView)v.findViewById(R.id.carttitle);
// descriptions =(TextView)v.findViewById(R.id.product_description);
price =(TextView)v.findViewById(R.id.cart_price);
quantity =(TextView)v.findViewById(R.id.item_quantity);
totalPrice =(TextView)v.findViewById(R.id.sub_total);
button =(Button)v.findViewById(R.id.remove_cart);
}
}
private class RemovefromList extends AsyncTask<RequestObject, Void,JSONObject> {
int selectedPos;
public RemovefromList(int pos){
selectedPos = pos;
}
#Override
protected JSONObject doInBackground(RequestObject... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// RequestObject requestObject = new RequestObject();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(arg0[0], ServiceHandler.POST);
JSONObject products = new JSONObject();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
products = jsonObj.getJSONObject("rsBody");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return products;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result!=null){
String status = result.getString("status");
cartList.remove(selectedPos);
notifyDataSetChanged();
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return;
}
}
}
You send the position also in asynctask parameter
new RemovefromList().execute(requestObject,position);
private class RemovefromList extends AsyncTask<String, Void,JSONObject> {
public RemovefromList(RequestObject obj, int pos) {
super();
RequestObject robj = obj;
int position= pos;
}
#Override
protected JSONObject doInBackground(String... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// RequestObject requestObject = new RequestObject();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(robj, ServiceHandler.POST);
JSONObject products = new JSONObject();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
products = jsonObj.getJSONObject("rsBody");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return products;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result!=null){
String status = result.getString("status");
cartList.remove(position);
notifyDataSetChanged();
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return;
}
}
Remove that particular item from ur List list and then call adapter.notifyDataSetChanged();
// For Delete from list
new AsynceTaskDeleteData().execute(position);
listData.remove(position);
// In your AsyncTask
private class AsynceTaskDeleteData extends AsyncTask<Integer, String, String> {
int position;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Integer... arg0) {
// Creating service handler class instance
position = arg0[0];
// Now pass position for delete
}
#Override
protected void onPostExecute(String result) {
notifyDataSetChanged();
}
}

listview is jerking on scrolling

i hv an application in which i am getting data from api,when data get loads and i tried to scroll the listview it get starts jerking,i tried to find the solution but get nothing.please help me to sort it out.
InboxActivity.java
list=(ListView)rootView.findViewById(R.id.list);
catagery = new ArrayList<ProfileInbox>();
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), fontPath);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//arg0.getp.setBackgroundColor(Color.WHITE);
//parent.getChildAt(position).setBackgroundColor(Color.BLUE);
IsRead=true;
catagery.get(position).setRead(IsRead);
new Task().execute(url);
adapter.notifyDataSetChanged();
msg=catagery.get(position).getMessage();
dateFrom=catagery.get(position).getSentDate();
sub=catagery.get(position).getSubject();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
});
return rootView;
}
private void loadNextPageOfReviews()
{
page_no_count += 1;
new JSONAsyncTask().execute(loadMoreUrl);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please Wait, Loading...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// ------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("inbox");
String unread_msg= jsono.getString("unread_msg");
Log.i("unreadMsg", unread_msg);
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
ProfileInbox category = new ProfileInbox();
String id = c.getString("msg_id");
String sub = c.getString("subject");
String name = c.getString("message");
String imageSetter=c.getString("sent_on");
//Log.i("id", id);
//Log.i("name", name);
//Log.i("imageSetter", imageSetter);
category.setMsgId(((JSONObject) c).getString("msg_id"));
if(unread_msg.contains(id)){
category.setRead(false);
}
else{
category.setRead(true);
}
category.setSubject(((JSONObject) c).getString("subject"));
category.setMessage(((JSONObject) c).getString("message"));
category.setSentDate(((JSONObject) c).getString("sent_on"));
//Log.i("category", category.toString());
catagery.add(category);
//Log.i("category", category.toString());
}
return true;
}
// ------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if (result == false){
Toast.makeText(getActivity(),
"Unable to fetch data from server", Toast.LENGTH_LONG)
.show();
}
else if(Blank.notice.equals("true")){
msg=catagery.get(0).getMessage();
dateFrom=catagery.get(0).getSentDate();
sub=catagery.get(0).getSubject();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
else if(Blank.notice.equals("false"))
{
//adapter.notifyDataSetChanged();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
InboxAdapter
public class InboxAdaptor extends BaseAdapter {
private List<ProfileInbox> originalData;
private List<ProfileInbox> filteredData;
private Context context;
public static String url;
public static String bussinessId;
public InboxAdaptor(Context context, ArrayList<ProfileInbox> Data) {
this.context = context;
this.originalData = Data;
//Log.i("originalData", Data.toString());
filteredData = new ArrayList<ProfileInbox>();
filteredData.addAll(this.originalData);
//Log.i("filterData", filteredData.toString());
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.inboxlist, null,false);
holder.coloredlay=(RelativeLayout)convertView.findViewById(R.id.coloredlay);
holder.txtWelcom = (TextView) convertView.findViewById(R.id.txtWelcom);
holder.dateTime = (TextView) convertView.findViewById(R.id.dateTime);
holder.txtdetails = (TextView) convertView.findViewById(R.id.txtdetails);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
if(filteredData.get(position).getRead()==true)
{
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}else{
holder.coloredlay.setBackgroundColor(Color.parseColor("#E5E4E2"));
}
// holder.img.setTag(position);
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(convertView.getContext().getAssets(), fontPath);
holder.txtWelcom.setText(filteredData.get(position).getSubject());
holder.txtWelcom.setTypeface(tf);
holder.dateTime.setText(filteredData.get(position).getSentDate());
holder.dateTime.setTypeface(tf);
holder.txtdetails.setText(filteredData.get(position).getMessage());
holder.txtdetails.setTypeface(tf);
/* if(Blank.notice.equals("true")){
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}
*/
notifyDataSetChanged();
return convertView;
}
public static class ViewHolder {
public RelativeLayout coloredlay;
public TextView txtdetails;
public TextView dateTime;
public TextView txtWelcom;
}
Remove notifyDataSetChanged() from getView() , notifyDataSetChanged() will update adapter when the data which you provided for your adapter has been changed , but you are using that wrong when a View of your list has been changed.
Remove notifyDataSetChanged() from getView().
You dot need that here. Rather have Remove notifyDataSetChanged() in onPostExecute() call back of JSONAsyncTask
Use cachecolorHint for come out of your solution:
<ListView
android:id="#+id/listNewsMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent" >
</ListView>

Categories

Resources