In one of my app, I need to use AsyncTask. I need to get an image URL from an HTTP site. I have done this in the doInBackground method. I am getting the URL of that image as a string.
publishProgress(thumb);//thumb is string
then in
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
sample = new ArrayList<String>();
System.out.println("this is on progress..."+values[0]);
sample.add(values[0]);
GridviewAdapter_old go=new GridviewAdapter_old(getActivity(), sample);
gv.setAdapter(go);
// gv.setAdapter(ga);
}
public class GridviewAdapter_old extends BaseAdapter
{
private ArrayList<String> listCountry;
private Activity activity;
public GridviewAdapter_old(Activity activity, ArrayList<String> listCountry) {
super();
// this.listCountry = listCountry;
this.listCountry = new ArrayList<String>();
this.listCountry = listCountry;
// this.listFlag = listFlag;
this.activity = activity;
System.out.println("this is contry name " + this.listCountry);
// System.out.println("this is img name " + this.listFlag);
// System.out.println();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
System.out.println("len " + listCountry.size());
// return listCountry.size();
return listCountry.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listCountry.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
public ImageView imgViewFlag;
// public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (convertView == null) {
view = new ViewHolder();
convertView = inflator.inflate(R.layout.test, null);
view.imgViewFlag = (ImageView) convertView
.findViewById(R.id.grid_item_image);
// view.imgViewFlag.setBackgroundResource(R.drawable.view_default);
convertView.setTag(view);
}
else {
view = (ViewHolder) convertView.getTag();
}
try {
URL myUrl = new URL(listCountry.get(0));
InputStream inputStream = (InputStream) myUrl.getContent();
Drawable drawable = Drawable.createFromStream(inputStream, null);
view.imgViewFlag.setImageDrawable(drawable);
} catch (Exception e) {
System.out.println(e.getMessage());
}
/*
* Bitmap imageBitmap = null; //System.gc(); try { URL imageURL = new
* URL(listCountry.get(0));
* System.out.println("this is in last portion..."
* +listCountry.get(position)); imageBitmap =
* BitmapFactory.decodeStream(imageURL.openStream());
* view.imgViewFlag.setImageBitmap(imageBitmap); //
* view.txtViewTitle.setText(listCountry.get(position)); //
* view.imgViewFlag.setImageResource(listFlag.get(position));
*
* } catch (Exception e) { System.out.println("this is error " +
* e.getMessage()); }
*/
return convertView;
}
}
The problem is:
I am not getting an image from the URL (that is getting from thumb (publishProgress(thumb);)
I am not getting the multiple images.
you are only getting one in your list because every time you call onProgressUpdate you create a new list.
You dont want to use onProgressUpdate to populate your list, that would be an insane amount of overhead. Instead you want to create your list inside your doInBackground then pass that list to your onPostExecute then put the new list to the adapter and call notifyDatasetChanged on the adapter to refresh the list.
in short, create the adapter (class wide variable), create an ArrayList (class wide variable) and everytime a change is made the the list all you have to do is call notifyDatasetCHanged on the adapter
ArrayList<String> list = new ArrayList<String();
ArrayAdapter adapter;
public class AsyncTask.....
#Override
protected Void doInBackground(Void... params){
...
list.add(stuff);
}
#Override
protected Void onPostExecute(Void params){
adapter.notifyDatasetChanged();
}
Related
public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
CustomList adapter = new CustomList(this, rowItems);
listView1.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
Id = _obj.getString("Id");
Designation = _obj.getString("Designation");
EmployeeName = _obj.getString("EmployeeName");
System.out.println(Id + "" + Designation + ""
+ EmployeeName);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
rowItems = new ArrayList<RowItem>();
}
}
}
This my code i am able to display the value after Jason parsing in this line System.out.println(Id + "" + Designation + ""
+ EmployeeName);
But i am unable to print data in Listview there is Error coming while i have created
Datamodel
public class RowItem {
public RowItem(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
private String title;
private String desc;
}
I have create adapter which i s extending from Base adapter that work fine can u please tell me how to bind value and display in list view after Json Parsing please suggest me i m trying to Implement .
Use Custom Adapter for binding your JSON data to your Listview like below :
public class ListViewAdapterForLead extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<SpinnerNavItem> data;
TextView txtText;
public ListViewAdapterForLead(Context context,ArrayList<SpinnerNavItem> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int index) {
return data.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_lead, null);
}
txtText = (TextView) convertView.findViewById(R.id.textLeadMenu);
txtText.setText(data.get(position).getTitle());
return convertView;
}
public View getDropDownView(int position,View convertView,ViewGroup parent){
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_lead, null);
}
txtText = (TextView) convertView.findViewById(R.id.textLeadMenu);
txtText.setText(data.get(position).getTitle());
return convertView;
}
}
bind your values in the getView() method of your custom adapter.
You should set the data after the background task gets completed.
* First try to set list adapter in onPostExecute() method.
* Make sure all the details in your model gets filled.
* Make use of getView() method in your Adapter class to parse the data.
For sample code for ListView with BaseAdapter, refer the below link
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
You forgot one thing,this is why the List is empty
Add the parsed data to your List
//initialize your list here
rowItems = new List<RowItems>();
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
RowItemsr = new RowItems();
Id = _obj.getString("Id");
Designation = _obj.getString("Designation");
EmployeeName = _obj.getString("EmployeeName");
System.out.println(Id + "" + Designation + ""
+ EmployeeName);
// you must create an object and add it to your list
r.setTitle(EmployeeName);
r.setDesc(Designation);
rowItems.add(r);
}
This is what you need
I am working on TCP socket, I receive some bunch of data for every sec and need to display it in ListView for that I am using a dynamic listView with custom array adapter.
My problem is, when I receive a new set of data from TCP socket, a new object is creating for listItem (findViewById), because of it when I scroll my listview, again it is moving to top when I am updating my listView.
When I consider only one set of data I did not find the above issue.
My code:
doAsynchronousTask = new TimerTask() {
#Override
public void run() {
finalizer = new Runnable() {
public void run() {
try {
new RetriveStock().execute(); // AsyncTask Executes for every 1 sec.
} catch (Exception e) {
// TODO: handle exception
}
}
}
};
handler.post(finalizer);
}
};
timer.schedule(doAsynchronousTask, 0, 1000); // execute in every 1000
// AsyncTask
public class RetriveStock extends AsyncTask<Void, Void, ArrayList<User>> {
#Override
protected ArrayList<User> doInBackground(Void... params) {
message += client.clientReceive(1); // Receive data from socket and put into message (string global variable).
printJson(); // Here I receive data from JSON and put into object
adb = new RSSListAdaptor(DefaultMarketWatch.this,
R.layout.rssitemview, list); // "list" is a global listAdapter.
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
protected void onPostExecute(ArrayList<User> result) {
lv.setAdapter(adb);
adb.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
// printJson()
public void printJson() {
String str = "";
/* SOME CODE HERE
FORMATING "message" (STRING VARIABLE) TO A PERFECT JSONARRAY FORMATE, AND PUT INTO VARIABLE "str" */
str = "[" + str + "]";
try {
JSONArray jsonArray = new JSONArray(str);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
User obj = new User();
// MY CODE, EITHER ADDING NEW OBJECT OR UPDATING THE EXISTING USER OBJECT.
list.add(obj);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
// My Custom ArrayAdapter.
public class RSSListAdaptor extends ArrayAdapter<User> {
private List<User> objects = null;
public RSSListAdaptor(Context context, int textviewid,
List<User> objects) {
super(context, textviewid, objects);
this.objects = objects;
}
#Override
public int getCount() {
return ((null != objects) ? objects.size() : 0);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater vi = (LayoutInflater) DefaultMarketWatch.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.rssitemview, null);
}
try {
User u = objects.get(position);
if (null != u) {
TextView title_list = (TextView) view.findViewById(R.id.symbol);
TextView ltp_list = (TextView) view.findViewById(R.id.ltp);
TextView high_list = (TextView) view.findViewById(R.id.high);
TextView low_list = (TextView) view.findViewById(R.id.low);
TextView persend_list = (TextView) view.findViewById(R.id.persent);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) title_list
.getLayoutParams();
params.setMargins(0, 0, 25, 0);
title_list.setText("TITLE");
ltp_list.setText("LTP");
high_list.setText("HIGH");
low_list.setText("LOW");
persend_list.setText("PERSENTAGE");
}
} catch (IllegalStateException is) {
is.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
}
Try this:
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// update listview with new data
// restore
mList.setSelectionFromTop(index, top);
Or
// Save ListView state
Parcelable state = listView.onSaveInstanceState();
// Set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
Do not recreate the adapter in doInBackground and do not reset it in onPostExecute
Rather create an empty adapter in your constructor or somewhere sensible, and when data comes in, append that data to your adapter then call notifyDataSetChanged
This question already has answers here:
BaseAdapter class wont setAdapter inside Asynctask - Android
(4 answers)
Closed 9 years ago.
I have an asynctask that gathers comments, usernames, and numbers by using a JSON method. Then I have a class that extends BaseAdapter that suppose to put the comments and usernames into a listView. The problem is how can I get the comments, usernames and numbers to the BaseAdapter class? Here is my current code
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
l1=(ListView)findViewById(R.id.list);
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
}
}
new loadComments().execute();
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(Context ctx_invitation, String[] comments, String[] Numbers, String[] usernames)
{
super();
this.ctx_invitation = ctx_invitation;
listComments = comments;
listNumbers = Numbers;
listUsernames = usernames;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
overwrite the values of the adapter you have implemented or add setters for them. Then set the values and make sure you call notifyDatasetChanged on the adapter.
You can either reference the adapter directly if it is a global variable or pass it in the constructor of your AsyncTask
In onPostExecute you can create a new BaseAdapter with the new data and then use setAdapter to set it as the adapter for your ListView. Or, as already said, you can use setters to update data in your current adapter and then notify the ListView that it should redraw itself.
By the very nature of AsyncTask you can update your UI wherever you want in onPreExecution, onProgressUpdate and onPostExecution.
Hi i am very new to this android..Actually i am trying to display 1 heading and description below it in a screen.I have done that using Galleryview.I don't know whether this is correct way to do this r not..
My actually idea is..In galleryview if i swipe the screen the next(heading and description should come) but i can't do this..SO i tried to keep next and previous option to do this..But this also i cant do ..I know that i am doing in wrong way.Please suggest me some goodway to do this.. I am ready to give more explanation if needed..The code below posted is what i done..
My Activity code:
public class NewsDescription extends Activity
{
// private String url = "http://m.indiatoday.in/xml/stories/"+(String)context.getInstance().getAppVariable("storyurl");
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newsdesgallery);
Gallery gl=(Gallery)findViewById(R.id.GalleryNewsDesc);
NewsDescriptionAdapter adapter =new NewsDescriptionAdapter(this);
gl.setAdapter(adapter);
}
}
My adapter class:
public class NewsDescriptionAdapter extends BaseAdapter
{
private static Context contxt;
String[] body= {};//new String[30];
String[] heading= {};//new String[30];
NewsDescriptionAdapter(Context conxt)
{
// System.out.println("inside cons");
this.contxt=conxt;
getelement();
}
public void getelement()
{
// System.out.println("Inside getElement");
String[] url=context.getInstance().getselectedUrl();
// System.out.println("After url");
// System.out.println("count="+(String)context.getInstance().getAppVariable("count"));
int count = Integer.parseInt((String)context.getInstance().getAppVariable("count"));
// System.out.println("count="+count);
// System.out.println("after count="+url[count]);
String URL = "http://xxxx.in/xml/stories/"+url[count];
// System.out.println("url="+URL);
TaplistingParser parser = new TaplistingParser();
// try {
// url=URLEncoder.encode(url, "UTF-8");
// } catch (UnsupportedEncodingException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
URL=URL.replace(" ","");
// System.out.println("url="+url);
String xml= parser.getXmlFromUrl(URL);
Document doc=parser.getDomElement(xml);
NodeList n1 = doc.getElementsByTagName("item");
body = new String[n1.getLength()];
heading = new String[n1.getLength()];
for( int i = 0 ; i < n1.getLength(); i++ )
{
// HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) n1.item(i);
body[i]=parser.getValue(e, "body");
heading[i]=parser.getValue(e, "headline");
// map.put("Body", parser.getValue(e,"body"));
// menuItems.add(map);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return body.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return body[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
// System.out.println("body="+body[position]);
if (convertView == null)
{
//this should only ever run if you do not get a view back
LayoutInflater inflater = (LayoutInflater) contxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newsdescriptionrow, null);
}
TextView next =(TextView)convertView.findViewById(R.id.nextnews);
// final Gallery gal=(Gallery)convertView.findViewById(R.id.GalleryNewsDesc);
next.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
System.out.println("Inside next");
int count = Integer.parseInt((String)context.getInstance().getAppVariable("count"));
count++;
context.getInstance().setAppVariable("count", Integer.toString(count));
}
});
TextView textViewhead = (TextView) convertView
.findViewById(R.id.name_DescHeading);
textViewhead.setText(heading[position]);
TextView textView = (TextView) convertView
.findViewById(R.id.name_Desclabel);
textView.setText(body[position]);
return convertView;
}
}
You should not use gallery widget any more as it is deprecated in newer version of android. Instead you can use a ViewPager from android support jar.
You can find an example in here :
https://github.com/nostra13/Android-Universal-Image-Loader
Lookout for ImagePagerActivity in the above code. You can create a custom cell with an imageview and textview for description (modify the item_pager_image xml). Let me know how it goes.
*
*
My Problem is that each Activity in my App gets data from Web Service and if
it remains idle for some OS dialog pops up showing Force Close and OK
option. when i clicks force close it stops but when i click Ok button it remains
in Activity, but when i move to other activity no data is shown as it does not hit web service
to get data for that activity
So, how to handle this situation
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coupon_layout);
context = this;
merchantName = (TextView) findViewById(R.id.CouponsMerchantName);
address = (TextView) findViewById(R.id.CouponsDetailAddress);
phone = (TextView) findViewById(R.id.CouponsDetailsPhone);
categoryImage = (ImageView) findViewById(R.id.CouponsCategoryImage01);
couponsListLayout = (ListView) findViewById(R.id.CouponsListLayout);
backButton = (Button) findViewById(R.id.CouponsBackButton);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
try {
entry = Data.storeMecrchantDetailMain.get(0);
merchantName.setText(entry.getMerchantName());
address.setText(entry.getAddress());
phone.setText(entry.getPhone());
ImageLoader imageLoader = new ImageLoader(CouponsActivity.this);
String categoryImg = Data.URL_BASE + entry.getCategoryImg();
categoryImage.setTag(categoryImg);
imageLoader.DisplayImage(categoryImg, CouponsActivity.this,
categoryImage);
adapter = new CustomAdapterCoupons(this, entry.getCouponsList());
couponsListLayout.setAdapter(adapter);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class CustomAdapterCoupons extends BaseAdapter {
/* Variable Declaration */
private Context context;
private List<CouponBean> list;
private CouponBean entry;
public com.a.util.ImageLoader imageLoader;
private LayoutInflater inflater;
public CustomAdapterCoupons(Context context, List<CouponBean> list) {
this.context = context;
this.list = list;
inflater = (LayoutInflater) CouponsActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new com.abc.util.ImageLoader(context);
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class ViewHolder {
public TextView couponName, couponCode, usageDescription,
expirationDate;
public ImageView couponImage;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
entry = list.get(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.coupons_list_layout,
null);
holder = new ViewHolder();
holder.couponName = (TextView) convertView
.findViewById(R.id.CouponListCouponName);
holder.couponCode = (TextView) convertView
.findViewById(R.id.CouponListCouponCode);
holder.expirationDate = (TextView) convertView
.findViewById(R.id.CouponListDetailDate);
holder.usageDescription = (TextView) convertView
.findViewById(R.id.CouponListUsageDescription);
holder.couponImage = (ImageView) convertView
.findViewById(R.id.CouponListLeftImage);
convertView.setTag(holder);
// Set the display text
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.couponName.setText(entry.getCouponName());
holder.expirationDate.setText(context
.getString(R.string.Coupon_Expiration_Date)
+ "\n"
+ entry.getExpirationDate());
holder.usageDescription.setText(entry.getUsageDescription());
holder.couponCode.setText(entry.getCouponCode());
holder.couponImage.setTag(Data.URL_BASE_2 + entry.getCouponImage());
imageLoader.DisplayImage(Data.URL_BASE_2 + entry.getCouponImage(),
(Activity) context, holder.couponImage);
Log.v(Data.LOG3, "image" + entry.getCouponImage());
final Button savedMyCoupons = (Button) convertView
.findViewById(R.id.CouponListAddtoMyCouponButton);
if (entry.getSavedMyCoupons().equalsIgnoreCase("N")) {
savedMyCoupons.setText(context
.getString(R.string.Add_to_myCoupons));
savedMyCoupons.setBackgroundResource(R.drawable.done_btn);
savedMyCoupons.setTag(entry.getCouponId().toString());
savedMyCoupons.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
createProgressDialog();
new Loader()
.execute(savedMyCoupons.getTag().toString());
}
});
} else if (entry.getSavedMyCoupons().equalsIgnoreCase("Y")) {
savedMyCoupons.setText(context
.getString(R.string.Already_Added_to_my_coupons));
savedMyCoupons.setBackgroundColor(Color.WHITE);
savedMyCoupons.setTextColor(Color.BLACK);
}
// display the view corresponding to data at specified position
return convertView;
}
}
private void createProgressDialog() {
progressDialog = new ProgressDialog(context);
// progressDialog.setIcon(R.drawable.icon);
progressDialog.setTitle(R.string.Please_Wait);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setIndeterminateDrawable(context.getResources()
.getDrawable(R.anim.simple_animation));
progressDialog.setMessage(context.getString(R.string.Please_Wait));
progressDialog.show();
}
#Override
public void onResume() {
Log.v(Data.LOG, "On Resume");
super.onResume();
}
class Loader extends AsyncTask<String, String, String> {
Boolean value;
protected String doInBackground(String... arg0) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Data.URL_POST_DATA);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("couponsubmit",
"submit"));
nameValuePairs.add(new BasicNameValuePair("sid",
Data.GET_SESSION_ID));
nameValuePairs.add(new BasicNameValuePair("api", "on"));
nameValuePairs.add(new BasicNameValuePair("couponid",
arg0[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// String result = responseBody;
Log.v(Data.LOG1, "Response : " + responseBody);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (Exception e) {
Log.e(Data.LOG, "" + e.getMessage());
e.printStackTrace();
}
LocateServices.getInstance().getStoreMerchantDetails(
entry.getMerchantID());
return null;
}
#Override
protected void onPostExecute(String result) {
// TODOAuto-generated method stub
super.onPostExecute(result);
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
entry = Data.storeMecrchantDetailMain.get(0);
adapter = new CustomAdapterCoupons(context,
entry.getCouponsList());
couponsListLayout.setAdapter(adapter);
progressDialog.dismiss();
}
};
}
}
Thanks for any help.
*
The dialog you are talking about is called ANR(Activity Not Responding) dialog, and there's no any method by which you can get the dialog to go away, and you should not try to remove it either.
You can however, call a new thread and run the methods to get data from web in that separate thread, instead of the UI thread.
Another method could be to start the fetching method after a second. The code example for this could be like this:
new Handler().postDelayed(new Runnable() {
public void run() {
//Your method to get data from web here
}
}, 1000); //delay in milliseconds
The above code will delay the fetching method by a second, so that the ANR dialog can be tricked away. However you should use a separate thread instead of this for better result.
Do your fetching in the background, your users will be happy. I use AsyncTask.
Try using Async Task function
Declare the function using
new AsynBackground().execute(u);
and implement the function as follows
private class AsynBackground extends AsyncTask<String, Void, Void>
{
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
fetchDistancesFromGoogle(params[0]);
return null;
}
}