Downloading images from a link displaying them in a listview - android

I have a list where for each item i need to display a image. I am downloading the image from a link and displaying it but with i am facing problems to display them as the list gets populated by text first and then downloads the images later.Also another problem is whenever i go up or down in the list image disappears and download again so the images are gone when i come to to the top the list items
EventTask
public RecieveEventsTask(EventListActivity c, String critiria) {
appContext = c;
session = new SessionManager(appContext);
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/geteventlist?user_id=" + id;
}
public RecieveEventsTask(MyEventList c, String critiria) {
my_appContext = c;
session = new SessionManager(my_appContext);
HashMap<String, String> user = session.getUserDetails();
// id
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/getmyeventlist?user_id=" + id;
}
protected void onPreExecute() {
dialog = new ProgressDialog(appContext == null ? my_appContext
: appContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Events...");
dialog.show();
super.onPreExecute();
}
String filterResponseString(String r) {
return r.replace("\r\n", "");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
responseString = filterResponseString(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
} catch (Exception e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (responseString != null) {
ArrayList<EventModel> eventsList = new ArrayList<EventModel>();
;
JSONArray jsonArr;
try {
// Log.v("json", responseString);
jsonArr = new JSONArray(responseString);
// jsonArr = events.getJSONArray("events");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
EventModel event = new EventModel();
event.setTitle(jsonObj.getString("event_info_title"));
event.setDescription(jsonObj.getString("event_info_desc"));
// Log.v("logo data "+i, jsonObj.getString("image_logo"));
event.setBanner(jsonObj.getString("image_banner"));
event.setLogo(jsonObj.getString("image_logo"));
// event.setDescription(jsonObj.getString("event_info_desc"));
event.setCategory(jsonObj.getString("event_cat_title"));
event.setStartDate(jsonObj
.getString("event_info_start_date"));
event.setEndDate(jsonObj.getString("event_info_end_date"));
event.setStartTime(jsonObj
.getString("event_info_start_time"));
event.setEndTime(jsonObj.getString("event_info_end_time"));
event.setEventId(jsonObj.getString("event_info_id"));
event.setPhone(jsonObj.getString("event_info_mobile"));
event.setEmail(jsonObj.getString("event_info_email"));
event.setWeblink(jsonObj.getString("event_info_web"));
//
// logoDownloader = new ImageDownloader(event.getLogoBitmap());
// logoDownloader.execute(event.getLogo());
//
// bannerDownloader = new ImageDownloader(event.getBannerBitmap());
// bannerDownloader.execute(event.getBanner());
//
eventsList.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appContext != null) {
appContext.showEventsDataLoaded(eventsList);
}
if (my_appContext != null) {
my_appContext.showEventsDataLoaded(eventsList);
}
// else
// {
// Log.v("check:","null");
//
// }
//
} else {
if(appContext!=null)
{
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
else {
Utility.showMessage(my_appContext, "Cannot Connect To Internet");
}
//
}
super.onPostExecute(result);
// Do anything with response..
}
i get the image link in my setlogo and setbanner method
Adapter class
private final Activity context;
private final ArrayList<EventModel> events;
ImageDownloader imgDownloader;
Bitmap bitmap;
ImageView icon;
public EventsListAdapter(Activity context, ArrayList<EventModel> events) {
super(context, com.bioscope.R.layout.event_listitem, events);
this.context = context;
this.events = events;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(com.bioscope.R.layout.event_listitem,
null, true);
TextView title = (TextView) rowView
.findViewById(com.bioscope.R.id.title);
title.setText(events.get(position).getTitle());
TextView description = (TextView) rowView
.findViewById(com.bioscope.R.id.description);
description.setText(events.get(position).getDescription());
TextView category = (TextView) rowView
.findViewById(com.bioscope.R.id.category);
category.setText(events.get(position).getCategory());
Log.v("logo", events.get(position).getLogo());
icon = (ImageView) rowView
.findViewById(com.bioscope.R.id.event_icon);
//imgDownloader = new ImageDownloader(icon);
new LoadImage().execute(events.get(position).getLogo());
//ImageLoader.displayImage(events.get(position).getLogo().toString(), icon);
return rowView;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
icon.setImageBitmap(image);
//pDialog.dismiss();
}else{
//pDialog.dismiss();
// Toast.makeText(EventListActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
// icon.set
}
}
}
}
i am setting the image in my icon of list items
Activity class
private ListView list;
private MenuItem myActionMenuItem;
private EditText myActionEditText;
private TextView myActionTextView;
private AutoCompleteTextView actv;
// private Spinner spinner;
private Button liveEvent;
private ArrayList<EventModel> eventsList;
private static final String[] paths = { "All", "Favourites" };
private ArrayList<String> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.bioscope.R.layout.eventlist);
RecieveEventsTask task = new RecieveEventsTask(this, "all");
task.execute();
}
public void showEventsDataLoaded(ArrayList<EventModel> eventsList) {
this.eventsList = eventsList;
// for(EventModel e:eventsList )
// {
// Log.v("title", e.getTitle());
// }
EventsListAdapter adapter = new EventsListAdapter(
EventListActivity.this, eventsList);
list = (ListView) findViewById(com.bioscope.R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(EventList.this, "You Clicked an item ",
// Toast.LENGTH_SHORT).show();
showEventInformaion(position);
}
});
// RecieveCategoriesTask task = new RecieveCategoriesTask(this, "all");
// task.execute();
liveEvent = (Button) findViewById(R.id.liveEvent);
liveEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EventListActivity.this,
LiveEventActivity.class);
startActivity(i);
}
});
}
public void showCategoryListDataLoaded(String response) {
Utility.showMessage(this, response);
}
Then in my activity i called the async reciver task to load all the data along with link and gave set them in my model class.

You haveto set ResponseCache in your Main class while downloading bitmap:
Like this:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html

Related

three categories item list get with diffrent category_id from json data in recyclerview android

I am developing an android app in which i store data from json.
everything is working fine but i am trying to implement multilayout Recyclerview where i show first and second category list items in a box with horizontal scroll and third list which we get from Category_id from json in vertical list
i get data from server in json where category list is open with unique category id just like
http://example.com/file_path&Category_id=3
and i get json data like
json data for category
[
{
"Category_ID":"3",
"Category_name":"Camera",
"Category_image":"upload\/images\/7089-2015-07-09.png"
},
{
"Category_ID":"9",
"Category_name":"Cars",
"Category_image":"upload\/images\/7789-2015-07-09.png"
},
]
json data for category list item
category list item json data. Every category list have unique id.
[
{
"Menu_ID":"19",
"Menu_name":"Sample 6",
"Price":"380",
"Menu_image":"upload\/images\/8611-2015-02-11.jpg"
},
{
"Menu_ID":"18",
"Menu_name":"Sample 5",
"Price":"500",
"Menu_image":"upload\/images\/8119-2015-02-11.jpg"
}
]
i am using recyclerview to show category and by clicking on category item category list is open
but i dont know how to call diffrent category list item from diffrent json category_id in a same recyclerview just like this image
Code is something like
MainActivity.java
public class ActivityProductList extends AppCompatActivity {
List<DataProductAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http: //example.com";
String Menu_Price_JSON = "Price";
String Menu_ID_JSON = "Menu_ID";
String Menu_Name_JSON = "Menu_name";
String Menu_Image_JSON = "Menu_image";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
public static ArrayList<Long> Menu_ID = new ArrayList<Long>();
public static ArrayList<String> Menu_name = new ArrayList<String>();
public static ArrayList<Double> Menu_price = new ArrayList<Double>();
public static ArrayList<String> Menu_image = new ArrayList<String>();
ProgressBar prgLoading;
SwipeRefreshLayout swipeRefreshLayout = null;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;
public static double Tax;
public static String Currency;
String MenuAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
private RecViewProductAdapter mla;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
ImageTitleNameArrayListForClick = new ArrayList<>();
mla = new RecViewProductAdapter(ActivityProductList.this);
// menu API url
MenuAPI = examplelink+"&category_id=";
// tax and currency API url
TaxCurrencyAPI = examplelink2;
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
Category_name = iGet.getStringExtra("category_name");
MenuAPI += Category_ID;
ListOfdataAdapter = new ArrayList<>();
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview_prod);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
recyclerViewadapter = new RecViewProductAdapter(ListOfdataAdapter, getApplicationContext());
recyclerView.setAdapter(recyclerViewadapter);
// JSON_HTTP_CALL();
new getTaxCurrency().execute();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
IOConnect = 0;
clearData();
new getDataTask().execute();
}
}, 3000);
}
});
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View arg1, int position)
{
// TODO: Implement this method
AdapterView<?> arg0;
long arg3;
Intent iDetail = new Intent(ActivityProductList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
})
);
}
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{
// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");
Tax = Double.parseDouble(tax.getString("Value"));
JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");
Currency = currency.getString("Value");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// clear arraylist variables before used
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if data available show data on list
// otherwise, show alert text
if(Menu_ID.size() > 0){
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(mla);
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
void clearData(){
Menu_ID.clear();
Menu_name.clear();
Menu_price.clear();
Menu_image.clear();
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu");
Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
Menu_name.add(menu.getString("Menu_name"));
Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
Menu_image.add(menu.getString("Menu_image"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
recyclerView.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
adapter class
public class RecViewProductAdapter extends RecyclerView.Adapter<RecViewProductAdapter.ViewHolder> {
Context context;
List<DataProductAdapter> dataAdapters;
ImageLoader imageLoader;
private ActivityProductList _mainActivity;
private Activity activity;
public RecViewProductAdapter(ActivityProductList activity){
this._mainActivity=activity;
}
public RecViewProductAdapter(Activity act) {
this.activity = act;
}
public RecViewProductAdapter(List<DataProductAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lsv_item_menu_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
View convertView = null;
holder.menuname.setText(ActivityProductList.Menu_name.get(position));
holder.menuprice.setText(ActivityProductList.Menu_price.get(position)+" "+ActivityProductList.Currency);
Picasso.with(activity).load(Config.ADMIN_PANEL_URL+"/"+ActivityProductList.Menu_image.get(position)).placeholder(R.drawable.loading).into(holder.imgThumb);
}
#Override
public int getItemCount() {
return ActivityProductList.Menu_ID.size();
// return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtText, txtSubText;
ImageView imgThumb;
public TextView menuname, menuprice, menunid;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
menuname = (TextView) itemView.findViewById(R.id.txtText);
menuprice = (TextView) itemView.findViewById(R.id.txtSubText);
imgThumb = (ImageView) itemView.findViewById(R.id.imgThumb);
}
}
}
any idea how can i achieve that layout with above code?
thankx

onResume Does Not Update ListView With New Data

I am trying to update a ListView on previous fragment after back button press. The onResume is called (verified with Toast) and the webservice runs (listView is displayed after it is cleared). The problem is that the ListView is still showing old values and not new value after accessWebService_getUsername is called. I verify the values from MySQL and even though the DB is updated, the ListView only returns old values.
#Override
public void onResume() {
Toast.makeText(getActivity(), "onResume", Toast.LENGTH_SHORT).show();
super.onResume();
adapter.clear();
getIMEI();
accessWebService_getUsername();
adapter.notifyDataSetChanged();
}
Update:
//ListView
ListView lv =(ListView)view.findViewById(R.id.listView);
adapter = new ContactsAdapter(getActivity(), arrRequest_Contact, arrRequest_NameSurname, arrRequest_MessageCount, arrRequest_Time, arrRequest_Image);
lv.setAdapter(adapter);
// Json
private class JsonGetUsername extends AsyncTask<String, Void, String> {
//Pending 01
private ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading Contacts, Please Wait");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
//Pending 02
if (dialog.isShowing()) {
dialog.dismiss();
}
adapter.notifyDataSetChanged();
try{
ListDrawer_getUsername(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getActivity(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService_getUsername() {
JsonGetUsername task = new JsonGetUsername();
// passes values for the urls string array
task.execute(new String[] { "http://mywebsite/php/get_username.php?pIMEI="+IMEI});
}
// build hash set for list view
public void ListDrawer_getUsername() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("username_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
request_username = jsonChildNode.optString("Username");
}
accessWebService_getContacts();
} catch (JSONException e) {
System.out.println("Json Error Rooms" +e.toString());
//Toast.makeText(getApplicationContext(), "No Rooms To Load", Toast.LENGTH_SHORT).show();
}
}
UPDATE 2:
//ContactsAdpater
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Request_Contact;
List<String> Request_NameSurname;
List<String> Request_MessageCount;
List<String> Request_Time;
List<String> Request_Image;
ContactsAdapter(Context c, List<String> Request_Contact, List<String> Request_NameSurname, List<String> Request_MessageCount, List<String> Request_Time, List<String> Request_Image)
{
super(c, R.layout.activity_contacts_single, R.id.textContact, Request_Contact);
this.context=c;
this.Request_Contact=Request_Contact;
this.Request_NameSurname=Request_NameSurname;
this.Request_MessageCount=Request_MessageCount;
this.Request_Time=Request_Time;
this.Request_Image=Request_Image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_contacts_single, parent, false);
}
TextView txtContact = (TextView) row.findViewById(R.id.textContact);
TextView txtNameSurname = (TextView) row.findViewById(R.id.textNameSurname);
TextView txtMessageCount = (TextView) row.findViewById(R.id.textMessageCount);
TextView txtTime = (TextView) row.findViewById(R.id.textTime);
ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
txtContact.setText(Request_Contact.get(position));
txtNameSurname.setText(Request_NameSurname.get(position));
txtMessageCount.setText(Request_MessageCount.get(position));
txtTime.setText(Request_Time.get(position));
Picasso.with(context).load(arrRequest_Image.get(position)).transform(new CircleTransform()).placeholder(R.drawable.ic_launcher).into(imageView);
return row;
}
}
You'll need to override the clear method in your ContactsAdapter to actually clear the lists you are storing your data in.
It looks like you'll need to clear all your lists, so if you add this to ContactsAdapter, your code should work as expected:
#Override
public void clear() {
super.clear();
Request_Contact.clear();
Request_NameSurname.clear();
Request_MessageCount.clear();
Request_Time.clear();
Request_Image.clear();
}

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>

android lazy list image loading array

so i have been at it for hours and its 4:07 AM now i have to sleep, so i hope someone can help me.
I have an ArrayList of ImageResults objects the class of which is defined as:
public class ImageResults {
String _title, _country, _thumbnailURL, _imageURL;
public ImageResults(String title, String country, String thumbnailURL, String imageURL)
{
_title = title;
_country = country;
_thumbnailURL = thumbnailURL;
_imageURL = imageURL;
}
public String getTitle()
{
return _title;
}
public String getCountry()
{
return _country;
}
public String getThumbnailURL()
{
return _thumbnailURL;
}
public String getImageURL()
{
return _imageURL;
}
}
Now in order to use https://github.com/thest1/LazyList i have to retrieve the thumbnail urls from my arraylist of type imageresults and place them in an array like im doing here
private void populateListBox()
{
String[] imgLst = new String[imagesList.size()];
for(int i = 0; i < imagesList.size();i++)
{
imgLst[i] = (imagesList.get(i)._thumbnailURL);
// Toast t = Toast.makeText(this,imgLst[0] , Toast.LENGTH_SHORT);
// t.show();
}
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
now the thing is the way it is above is not working but if i take the link individually as follows it works which is the default way the links are organized in the original project
private void populateListBox()
{
String[] imgLst={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300"};
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
this is how links are organized in the original project, and yest i am 100% sure that both methods are returning the same string just in different ways, one is fetching it from an object in an arraylist and the other im explicitly declaring it.
private String[] mStrings={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300",
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-CA1182456710.jpg&w=300",
"http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
"http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg",
"http://a1.twimg.com/profile_images/97470808/icon_normal.png",
"http://a3.twimg.com/profile_images/511790713/AG.png",
"http://a3.twimg.com/profile_images/956404323/androinica-avatar_normal.png",
"http://a1.twimg.com/profile_images/909231146/Android_Biz_Man_normal.png",
"http://a3.twimg.com/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
"http://a1.twimg.com/profile_images/349012784/android_logo_small_normal.jpg"};
main activity class
public class BngPaperActivity extends Activity {
ListView imageListView;
Spinner countrySpinner;
String selectedMonth;
String selectedYear;
LazyAdapter adapter;
ProgressDialog progress;
Dialog date;
getResult getRes;
String ResultsString;
ArrayList<String> monthList = new ArrayList<String>();
ArrayList<ImageResults> imagesList = new ArrayList<ImageResults>();
String dateText;
TextView selectedDateView;
static final int MONTHYEARDATESELECTOR_ID = 3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = new ProgressDialog(BngPaperActivity.this);
monthList.add("January"); monthList.add("February"); monthList.add("March"); monthList.add("April");
monthList.add("May"); monthList.add("June"); monthList.add("July"); monthList.add("August");
monthList.add("September"); monthList.add("October"); monthList.add("November"); monthList.add("December");
imageListView = (ListView) this.findViewById(R.id.imagesListView);
countrySpinner = (Spinner) this.findViewById(R.id.countrySpinner);
selectedDateView = (TextView) this.findViewById(R.id.selectedDateView);
Button monthYearButton = (Button) this.findViewById(R.id.monthyearBTN);
// set up a listener for when the button is pressed
monthYearButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// call the internal showDialog method using the predefined ID
showDialog(MONTHYEARDATESELECTOR_ID);
}
});
}
private DateSlider.OnDateSetListener mMonthYearSetListener =
new DateSlider.OnDateSetListener() {
public void onDateSet(DateSlider view, Calendar selectedDate) {
// update the dateText view with the corresponding date
dateText = (String.format("%tB %tY", selectedDate, selectedDate));
selectedDateView.setText(dateText);
try {
selectedMonth = monthList.indexOf(String.format("%tB", selectedDate)) + 1 +"";
selectedYear = String.format("%tY", selectedDate);
progress.setMessage("Fetching Images... \nPress Back Button To Cancel");
progress.setCancelable(true);
getRes = new getResult(progress,view);
getRes.execute();
try {
ResultsString = getRes.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parseResults(ResultsString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private void parseResults(String result)
{
Scanner scan = new Scanner(result);
String current = scan.nextLine();
String title = "";
String country = "";
String thumbURL = "";
String imageURL = "";
while(!current.equals("End of file"))
{
if(current.equals("Begin Thumb"))
{
current = scan.nextLine();
title = current.substring(current.indexOf(":")+1);
current = scan.nextLine();
country = current.substring(current.indexOf(":")+1);
current = scan.nextLine();
thumbURL = current.substring(current.indexOf(":")+1);
imageURL = thumbURL.replace("300", "900");
current = scan.nextLine();
}
if(current.equals("End Thumb"))
{
imagesList.add(new ImageResults(title,country,thumbURL,imageURL));
}
current = scan.nextLine();
}
populateListBox();
}
private void populateListBox()
{
//this is not working, i would like this one to work
String[] imgLst = new String[imagesList.size()];
for(int i = 0; i < imagesList.size();i++)
{
imgLst[i] = (imagesList.get(i)._thumbnailURL);
// Toast t = Toast.makeText(this,imgLst[0] , Toast.LENGTH_SHORT);
// t.show();
}
//-----------------------------------
/* This is working
String[] imgLst={
"http://www.istartedsomething.com/bingimages/resize.php?i=Velodrome_EN-AU1182456710.jpg&w=300"};
*/
adapter=new LazyAdapter(this, imgLst);
imageListView.setAdapter(adapter);
}
#Override
protected Dialog onCreateDialog(int id) {
// this method is called after invoking 'showDialog' for the first time
// here we initiate the corresponding DateSlideSelector and return the dialog to its caller
final Calendar c = Calendar.getInstance();
final Calendar minDate = Calendar.getInstance();
minDate.set(Calendar.YEAR, 2009);
minDate.set(Calendar.MONTH, Calendar.JUNE);
final Calendar maxDate = Calendar.getInstance();
maxDate.add(Calendar.DATE, 0);
switch (id) {
case MONTHYEARDATESELECTOR_ID:
return new MonthYearDateSlider(this,mMonthYearSetListener,c,minDate,maxDate);
}
return null;
}
private class getResult extends AsyncTask<String, String, String> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog progress;
DateSlider view;
public getResult(ProgressDialog progress, DateSlider view)
{
this.progress = progress;
this.view = view;
}
protected void onPreExecute() {
this.view.dismiss();
this.progress.show();
}
#Override
protected String doInBackground(String... urls) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet("http://devleb.com/BngPaper/BngPaperWebService.php?thumbnail=Yes&year="+selectedYear+"&month="+ selectedMonth));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
//Dialog.dismiss();
progress.dismiss();
return responseString;
}
protected void onPostExecute(Void unused) {
this.progress.dismiss();
if (Error != null) {
Toast.makeText(BngPaperActivity.this, Error, Toast.LENGTH_LONG).show();
}
}
}
}
The following doesn't work?
private void populateListBox()
{
adapter=new LazyAdapter(this, mStrings);
imageListView.setAdapter(adapter);
}
Like in the example given in the lazylist project.

Categories

Resources