progress dialog keeps on displaying

↘锁芯ラ 提交于 2020-01-06 08:07:22

问题


I have written a long code in android and which displays a progress dialog when the restaurant list is loaded into the listview. Now the problem is that its working fine when restaurant list is loaded again on users filter changes but only at the first time. it just keeps on displaying even if the listview is populated and user has to manually dismiss it pressing the back button of deivce. I dont knw where to write pg.dismiss() in this case. Posting my code here . plz advise me..

 package com.Refinedymapps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Restaurantlist extends Activity implements OnClickListener, OnItemSelectedListener {
    ProgressDialog pg;
    private ImageButton imgbtn; 
    private ListView restaurant;
    private TextView city;
    String sendid,flagdopost="",linkurl;
    LocationManager locationManger;
    Geocoder gc;
    Bundle bundle;
    private int j=0;
    private Spinner cuisine,area;
    static ArrayList<HashMap<String,String>> customlist= new ArrayList<HashMap<String,String>>();
    private String asynctaskflag="",cuisineval,areaval;
    List<String> tempareanamelist,tempcuisinenamelist,areanamelist,cuisinelist,cuisineidlist,restaurantnames,areanames,restaurantidlist,originalcuisinelist,originalarealist;
    String str,coun,stat,cid,sid,cityid,cityname;



     @Override
    public void onCreate(Bundle savedInstanceState) 
     {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.restaurantlisting);
            linkurl=getResources().getString(R.string.linkurl);
            city=(TextView)findViewById(R.id.textviewcity);
            cuisine=(Spinner)findViewById(R.id.spncuisine);
            area=(Spinner)findViewById(R.id.spnarea);
            restaurant=(ListView)findViewById(R.id.lstrestaurant);
            imgbtn=(ImageButton)findViewById(R.id.imageButton1);            

            bundle = this.getIntent().getExtras();
            imgbtn.setImageResource(R.drawable.searchloc);
            asynctaskflag="init";
            new Thetask().execute(asynctaskflag,null,null);                 

            imgbtn.setOnClickListener(new OnClickListener(){
                public void onClick(View arg0) {
                    Intent newlocintent=new Intent(Restaurantlist.this,Restaurantlistdisplay.class);
                    startActivity(newlocintent);

                    }               
            });            
            restaurant.setOnItemClickListener(new OnItemClickListener(){                
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                        Toast.makeText(getBaseContext(), "resname"+restaurantnames.get(arg2)+"areaname"+areanames.get(arg2), 10).show();
                        String[] getid={"itemclick",restaurantnames.get(arg2),areanames.get(arg2)};
                        new Thetask().execute(getid);                                       
                }
            });
     } 

     public void populateReslist()
     {
        Log.i("inside populatereslist","value of j is:"+j);
        for(int i=0;i<restaurantnames.size();i++)
        {
            HashMap<String,String> temp = new HashMap<String,String>();
            temp.put("Restaurant Name",restaurantnames.get(i).toString());
            temp.put("Area Name", areanames.get(i).toString());
            customlist.add(temp);
        }   
     }

     public List<String> getAreanames(String cityid)
        {

            String list = null;
            areanamelist=new ArrayList<String>();

            final HttpClient client=new DefaultHttpClient();

            final HttpGet req=new HttpGet(linkurl+"/ymaws/resources/restaurant/"+cityid+"/areas/");
            HttpResponse httpResponse;
            try {
                    httpResponse=client.execute(req);
                    HttpEntity entity = httpResponse.getEntity();
                    Log.i("entity", entity.toString());
                    if (entity != null) 
                    {

                        InputStream instream = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                        StringBuilder sb = new StringBuilder();

                        String line = null;
                        try 
                        {
                            while ((line = reader.readLine()) != null) 
                            {
                                sb.append(line + "\n");
                            }
                        } 
                        catch (IOException e) 
                        {
                            e.printStackTrace();
                        } 
                        finally 
                        {
                            try 
                            {
                                instream.close();
                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }
                        }

                        // Closing the input stream will trigger connection release
                        list= sb.toString();
                        Log.i("areaname xml is", list.toString());
                    }
            }
            catch(Exception e)
            {

            }

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            try
            {
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document dom = builder.parse(new InputSource(new StringReader(list))); 
                Element root = dom.getDocumentElement();
                NodeList items = root.getElementsByTagName("Area");
                for (int i=0;i<items.getLength();i++)
                {
                    Node item = items.item(i);
                    NodeList properties = item.getChildNodes();
                    for (int j=0;j<properties.getLength();j++)
                    {
                        Node property = properties.item(j);
                        String name = property.getNodeName();
                        if (name.equalsIgnoreCase("areaName"))
                        {
                            areanamelist.add(property.getFirstChild().getNodeValue());
                        }                       
                        else
                        {

                        }                   
                    }
                }
                //Log.i("areaname list in getAreas method", areanamelist.toString());
                return areanamelist;         
           }
            catch (Exception e) 
            {
                throw new RuntimeException(e);
            } 
        }

     public List<String> getCuisines(String cityid)
     {

            String list = null;
            cuisinelist=new ArrayList<String>();
            cuisineidlist=new ArrayList<String>();
            final HttpClient client=new DefaultHttpClient();            
            final HttpGet req=new HttpGet(linkurl+"/ymaws/resources/restaurant/"+cityid+"/cuisines/");
            HttpResponse httpResponse;
            try {
                    httpResponse=client.execute(req);
                    HttpEntity entity = httpResponse.getEntity();
                    Log.i("entity", entity.toString());
                    if (entity != null) 
                    {

                        InputStream instream = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                        StringBuilder sb = new StringBuilder();

                        String line = null;
                        try 
                        {
                            while ((line = reader.readLine()) != null) 
                            {
                                sb.append(line + "\n");
                            }
                        } 
                        catch (IOException e) 
                        {
                            e.printStackTrace();
                        } 
                        finally 
                        {
                            try 
                            {
                                instream.close();
                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }
                        }

                        // Closing the input stream will trigger connection release
                        list= sb.toString();
                        Log.i("cuisinename xml is", list.toString());
                    }
            }
            catch(Exception e)
            {

            }

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            try
            {
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document dom = builder.parse(new InputSource(new StringReader(list))); 
                Element root = dom.getDocumentElement();
                NodeList items = root.getElementsByTagName("Cuisine");
                for (int i=0;i<items.getLength();i++)
                {
                    Node item = items.item(i);
                    NodeList properties = item.getChildNodes();
                    for (int j=0;j<properties.getLength();j++)
                    {
                        Node property = properties.item(j);
                        String name = property.getNodeName();
                        if (name.equalsIgnoreCase("cuisineName"))
                        {
                            cuisinelist.add(property.getFirstChild().getNodeValue());
                        }                       
                        else if(name.equalsIgnoreCase("cuisineId"))
                        {
                            cuisineidlist.add(property.getFirstChild().getNodeValue());
                        }                   
                    }
                }   
                Log.i("getcuisine cuisinelist",cuisinelist.toString());
                return cuisinelist;         
           }
            catch (Exception e) 
            {
                throw new RuntimeException(e);
            } 

     }

     public void firequery()
        {
            String url = null;
            if(cuisineval=="*" && areaval=="*")
            {
                 url=linkurl+"/ymaws/resources/restaurant/"+cityid+"/restaurants";                          
            }
            else if(cuisineval!="*" && areaval=="*")
            {

                for(int i=0;i<originalcuisinelist.size();i++)
                {   

                    Log.i("cuisinelist original item is",""+originalcuisinelist.get(i));
                    Log.i("cuisineidlist is",cuisineidlist.toString());

                    if((cuisine.getSelectedItem().toString()).equalsIgnoreCase(originalcuisinelist.get(i).toString()))
                    {                       
                        Log.i("cuisineid selected is",""+cuisineidlist.get(i));
                        url=linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&cuisineid="+cuisineidlist.get(i);
                    }
                }       
            }
            else if(cuisineval=="*" && areaval!="*")
            {

                            url = linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&areanm="+area.getSelectedItem().toString();


            }
            else
            {
                for(int i=0;i<originalcuisinelist.size();i++)
                {               
                    if((cuisine.getSelectedItem().toString()).equalsIgnoreCase(originalcuisinelist.get(i).toString()))
                    {               
                        url=linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&cuisineid="+cuisineidlist.get(i)+"&areanm="+area.getSelectedItem().toString();
                    }
                }                   
            }
            getResult(url);

        }

     public void getResult(String url)
     {
            String list = null;
            restaurantnames=new ArrayList<String> ();   
            areanames=new ArrayList<String>();
            restaurantidlist=new ArrayList<String>();
                        final HttpClient client=new DefaultHttpClient();
            Log.i("url is","url:"+url.toString());
            final HttpGet req=new HttpGet(url.replaceAll(" ", "%20"));
            HttpResponse httpResponse;
            try {
                    httpResponse=client.execute(req);
                    HttpEntity entity = httpResponse.getEntity();
                    Log.i("entity", entity.toString());
                    if (entity != null) 
                    {

                        InputStream instream = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        try 
                        {
                            while ((line = reader.readLine()) != null) 
                            {
                                sb.append(line + "\n");
                            }
                        } 
                        catch (IOException e) 
                        {
                            e.printStackTrace();
                        } 
                        finally 
                        {
                            try 
                            {
                                instream.close();
                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }
                        }                       
                        list= sb.toString();
                        Log.i("list xml is", list.toString());
                    }
            }
            catch(Exception e)
            {

            }
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            try
            {
              if(list!=null)
              {
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document dom = builder.parse(new InputSource(new StringReader(list))); 
                Element root = dom.getDocumentElement();
                NodeList items = root.getElementsByTagName("resLovData");
                for (int i=0;i<items.getLength();i++)
                {
                    Node item = items.item(i);
                    NodeList properties = item.getChildNodes();
                    for (int j=0;j<properties.getLength();j++)
                    {
                        Node property = properties.item(j);
                        String name = property.getNodeName();
                        if (name.equalsIgnoreCase("locName"))
                        {
                            restaurantnames.add(property.getFirstChild().getNodeValue());
                        }                       
                        else if(name.equalsIgnoreCase("areaName"))
                        {
                            areanames.add(property.getFirstChild().getNodeValue());
                        }
                        else if(name.equalsIgnoreCase("locId"))
                        {
                            restaurantidlist.add(property.getFirstChild().getNodeValue());
                        }

                    }
                }   
              }
              else
              {

              }
           }
            catch (Exception e) 
            {
                throw new RuntimeException(e);
            } 
     }

     public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }

     public class Thetask extends AsyncTask<String, Void, Void>  
     {     

         String x,y;         
         @Override 
         public void onPreExecute() 
         {   
            pg =new ProgressDialog(Restaurantlist.this);
            pg.setMessage("fetching info....");
            pg.setIndeterminate(true);
            pg.setCancelable(true);
            Log.i("inside preexecute","in pre execute");
            pg.show();          
         }   

         public Void doInBackground(String... params)
         {          
            if(params[0].equalsIgnoreCase("init"))
            {
                Log.i("inside doinbackground 1st",flagdopost);
                cid=bundle.getString("cid");
                sid=bundle.getString("sid");
                cityid=bundle.getString("cityid");              
                cityname=bundle.getString("cityname");
                originalcuisinelist=new ArrayList<String>();
                originalcuisinelist=getCuisines(cityid);

                tempcuisinenamelist = getCuisines(cityid);  
                tempcuisinenamelist.add(0,"All");

                originalarealist=new ArrayList<String>();
                originalarealist=getAreanames(cityid);
                tempareanamelist=getAreanames(cityid);
                tempareanamelist.add(0,"All");
                Log.i("area are",tempareanamelist.toString());

                flagdopost="init";  
                Log.i("inside doinbackground 1st",flagdopost);
            }           
            else if(params[0].equalsIgnoreCase(""))
            {
                flagdopost="";
                 j++;
                 if(j!=1)
                 {
                     firequery();           
                     flagdopost="itemselected";
                     Log.i("inside doinbackground 2nd",flagdopost);
                 }
            }           
            else if(params[0].equalsIgnoreCase("itemclick"))
            {
                x=params[1];
                y=params[2];
                for(int i=0;i<restaurantidlist.size();i++)
                {
                    if((params[1].toString()).equalsIgnoreCase(restaurantnames.get(i)))
                    {
                        sendid=restaurantidlist.get(i);

                    }
                }

                Log.i("in do in backgroung idforbundle is", sendid);
                flagdopost="itemclicked";
            }
            return null;                     
         } 

         public void onPostExecute(Void result)
         {       
             if(flagdopost.equalsIgnoreCase("init"))
             {
                 city.setText(cityname);                            
                 ArrayAdapter<String> adaptercuisine=new ArrayAdapter<String>(Restaurantlist.this,android.R.layout.simple_spinner_item,tempcuisinenamelist);
                 adaptercuisine.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                 ArrayAdapter<String> adapterarea=new ArrayAdapter<String>(Restaurantlist.this,android.R.layout.simple_spinner_item,tempareanamelist);
                 adapterarea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                 area.setAdapter(adapterarea); 
                 area.setSelection(0);

                 cuisine.setAdapter(adaptercuisine); 
                 cuisine.setSelection(0);

                 area.setOnItemSelectedListener(Restaurantlist.this);
                 cuisine.setOnItemSelectedListener(Restaurantlist.this);
             }
             else if(flagdopost.equalsIgnoreCase("itemselected"))
             {

                 customlist.clear();
                 populateReslist();
                 restaurant.invalidateViews();
                 restaurant.setAdapter(new SimpleAdapter(Restaurantlist.this,customlist,R.layout.customlistrow,new String[] {"Restaurant Name","Area Name"},
                 new int[] {R.id.tvresname,R.id.tvareaname})
                 {
                   @Override      
                   public View getView(int position, View convertView,ViewGroup parent)
                   {                                                   
                       View view =super.getView(position, convertView, parent); 
                       return view;                    
                   }  
                 });    

             }
             else if(flagdopost.equalsIgnoreCase("itemclicked"))
             {              
                Bundle bundle=new Bundle();
                bundle.putString("locid",sendid);

                Toast.makeText(getBaseContext(), "locId in dopost new one"+sendid, 10).show();
                Intent resdetail = new Intent(Restaurantlist.this,Restaurantdetail.class);
                resdetail.putExtras(bundle);
                startActivity(resdetail);               
             }              
             pg.dismiss();
         }

  }

    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) 
    {
        switch(arg0.getId())
        {
            case    R.id.spncuisine:

                                    asynctaskflag="";
                                    if(cuisine.getSelectedItem().toString()!="All")
                                    {
                                        cuisineval=cuisine.getSelectedItem().toString();
                                    }
                                    else
                                    {
                                        cuisineval="*";
                                    }

                                    new Thetask().execute(asynctaskflag,null,null);

                                    break;

             case   R.id.spnarea:                           
                                    asynctaskflag="";
                                    if(area.getSelectedItem().toString()!="All")
                                    {
                                        areaval=area.getSelectedItem().toString();
                                    }
                                    else
                                    {
                                        areaval="*";
                                    }
                                    new Thetask().execute(asynctaskflag,null,null);
                                    break;
        }


    }
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}   

回答1:


Try declaring your ProgressDialog inside the AsyncTask. Instead of as a Activity member variable.

public class Thetask extends AsyncTask<String, Void, Void>
{
     ProgressDialog pg = null;
     String x,y;         
     @Override 
     public void onPreExecute()
     ...


来源:https://stackoverflow.com/questions/9478325/progress-dialog-keeps-on-displaying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!