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>
Related
I want to parse data and images via url of json.
I have used following code to do same. But i am not getting why the images disappear when i scroll down.
Can Anyone please tell me how can i stop to disappear images when i scroll down ?
Images are loading randomly how can i fix it?
Please find below link of source code :-
http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://milagro.in/wip/apps/n/THDC2.json");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).gettata_project_name(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
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("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.settata_project_name(object.getString("tata_project_name"));
actor.setproject_Typology(object.getString("project_Typology"));
actor.setproject_logo_url(object.getString("project_logo_url"));
actor.setprice(object.getString("price"));
actorsList.add(actor);
}
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();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.Projectname = (TextView) v.findViewById(R.id.Projectname);
holder.typology = (TextView) v.findViewById(R.id.typology);
holder.price = (TextView) v.findViewById(R.id.price);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.imageview.setImageResource(R.drawable.ic_launcher);
//new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.Projectname.setText(actorList.get(position).gettata_project_name());
holder.typology.setText(actorList.get(position).getproject_Typology());
holder.price.setText("Price: " + actorList.get(position).getprice());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView Projectname;
public TextView typology;
public TextView price;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public class Actors {
private String tata_project_name;
private String project_Typology;
private String project_logo_url;
private String price;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String tata_project_name, String project_Typology,String project_logo_url, String price ) {
super();
this.tata_project_name = tata_project_name;
this.project_Typology = project_Typology;
this.project_logo_url = project_logo_url;
this.price = price;
}
public String gettata_project_name() {
return tata_project_name;
}
public void settata_project_name(String tata_project_name) {
this.tata_project_name = tata_project_name;
}
public String getproject_Typology() {
return project_Typology;
}
public void setproject_Typology(String project_Typology) {
this.project_Typology = project_Typology;
}
public String getproject_logo_url() {
return project_logo_url;
}
public void setproject_logo_url(String project_logo_url) {
this.project_logo_url = project_logo_url;
}
public String getprice() {
return price;
}
public void setprice(String price) {
this.price = price;
}
}
try this library Picaso this is the best image loading library from url.
After using Volley library The problem is solved.
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("");
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();
}
}
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
I am creating an application which works offline. My app is working fine in online mode and getting json from url. How can I make it work offline? How do I insert json from a url into SQLite? I want to get all data from a url first, then insert it in SQLite and then use database.
This is my complete code:
public class MainActivity extends Activity {
CategoryListAdapter3 cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String URL, URL2;
String SelectMenuAPI;
String _response;
String status;
GridView gridview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
cla = new CategoryListAdapter3(MainActivity.this);
new TheTask().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(MainActivity.this,
Subcategory.class);
iMenuList.putExtra("Category_ID",
Category_ID.get(position));
iMenuList.putExtra("Category_name",
Category_name.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
SelectMenuAPI = "http://www.syddddds.pk/beta7/_webservices
/mobile_api.php?response=getmaincategories";
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("Status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
//
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add(Long.parseLong(object .getString("category_id")));
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image_path"));
}
}
else {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gridview.setAdapter(cla);
cla.notifyDataSetChanged();
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return MainActivity.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(MainActivity.Category_name.get(position));
androidAQuery.id(holder.imgThumb).image(MainActivity.Category_image.get(position),
true, true);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}