在Android中搜索时显示ProgressDialog

时间:2011-02-28 21:03:27

标签: android search progressdialog

我阅读了有关stackoverflow的所有问题,这些问题可以给我一个提示,但我无法让它工作。

我有什么:

我有一个名为“wantlist”的活动,它启动了我的应用程序。在这个活动上,我有一个按钮,通过onSearchRequested();

开始搜索

我还有一个名为“discogssearch”的活动,它在互联网上调用XML Api,解析数据并显示搜索结果。

所有这一切都很好。

我想要实现的目标:

我希望显示一个ProgessDialog,同时发出耗时的api调用。

我尝试了什么:

我尝试在搜索开始之前以多种方式打开ProgessDialog并发现,我必须与主线程异步。所以我将耗时的代码放入AsyncTask并启动它。

会发生什么:

当我输入文本并点击输入nothings时(如前所述)直到结果到达。现在,“discogssearch”视角正在显示结果,并且ProgressDialog显示,但是这一点已经完成了所有工作。

我的代码:

wantlist.java

public class wantlist extends Activity implements OnClickListener {
/** Called when the activity is first created. */

ArrayList<Want> wants = new ArrayList<Want>();

@Override
public void onCreate(Bundle savedInstanceState) {        

    wants.add(new Want("Want1"));
    wants.add(new Want("Want2"));
    wants.add(new Want("Want3"));
    wants.add(new Want("Want4"));
    wants.add(new Want("Want5"));

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    ListView lv = (ListView) findViewById(R.id.WantList); 
    ImageButton b = (ImageButton) findViewById(R.id.searchbutton);
    b.setOnClickListener(this);

    lv.setAdapter(new WantAdapter(this,
            R.layout.lplistitem, wants));
    lv.setTextFilterEnabled(true);

}

public void onClick(View v) {
    onSearchRequested();

}

}

discogssearch.java

public class discogssearch extends Activity implements OnItemClickListener{
/** Called when the activity is first created. */

private static final int PROGRESS_DIALOG = 0;
private static final String LOGTAG = discogssearch.class.getName();

@Override
  public void onAttachedToWindow() {
    super.onAttachedToWindow();
    Window window = getWindow();
    // Eliminates color banding
    window.setFormat(PixelFormat.RGBA_8888);
  }


private ListView alv = null;
private ListView rlv = null;
private ListView llv = null;

ArrayList<Want> results = new ArrayList<Want>();
View.OnTouchListener gestureListener;
GestureDetector pageFlip;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.searchresults);

    Intent intent = getIntent();


      String query = intent.getStringExtra(SearchManager.QUERY);

      searchDiscogs(query);

}

public void searchDiscogs(String query)
{   
    query = URLEncoder.encode(query);
    alv = (ListView) findViewById(R.id.ArtistList);
    rlv = (ListView) findViewById(R.id.ReleaseList);
    llv = (ListView) findViewById(R.id.LabelList);

    rlv.setOnItemClickListener(this);

    rlv.setFastScrollEnabled(true);
    rlv.setVerticalFadingEdgeEnabled(true);

    results.clear();


    AsyncTask<String, Integer, DiscogsXMLHandler> at = new AsyncDiscogsSearch().execute(query);
    DiscogsXMLHandler discogsHandler = null;

    try {
        discogsHandler = at.get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Log.d("WICHTIG: ",discogsHandler.getReleaseResults().size() + "");

    alv.setAdapter(new WantAdapter(this,
            R.layout.lplistitem, discogsHandler.getArtistResults()));

    rlv.setAdapter(new WantAdapter(this,
            R.layout.lplistitem, discogsHandler.getReleaseResults()));

    llv.setAdapter(new WantAdapter(this,
            R.layout.lplistitem, discogsHandler.getLabelResults()));
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {

    if(arg0.equals(rlv))
    {
        String uri = ((Want)rlv.getItemAtPosition(arg2)).getDetailsUri();
        Log.d("Itemclick", uri);
        Intent viewUri = new Intent("android.intent.action.VIEW", Uri.parse(uri));
        viewUri.setClass(this, releasedetails.class);
        startActivity(viewUri);
    }


}

public Dialog onCreateDialog(int dial)
{

    switch(dial) {
    case PROGRESS_DIALOG:
        Log.d(LOGTAG,"Showing Progress Dialog");
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        return progressDialog;
    default:
        return null;
    }
}

private Animation inFromRightAnimation() {
      Animation inFromRight = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT, +1.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f);
      inFromRight.setDuration(100);
      inFromRight.setInterpolator(new AccelerateInterpolator());
      return inFromRight;
     }

     private Animation outToLeftAnimation() {
      Animation outtoLeft = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT, 0.0f,
        Animation.RELATIVE_TO_PARENT, -1.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f);
      outtoLeft.setDuration(100);
      outtoLeft.setInterpolator(new AccelerateInterpolator());
      return outtoLeft;
     }

     private Animation inFromLeftAnimation() {
      Animation inFromLeft = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT, -1.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f);
      inFromLeft.setDuration(100);
      inFromLeft.setInterpolator(new AccelerateInterpolator());
      return inFromLeft;
     }

     private Animation outToRightAnimation() {
      Animation outtoRight = new TranslateAnimation(
        Animation.RELATIVE_TO_PARENT, 0.0f,
        Animation.RELATIVE_TO_PARENT, +1.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f,
        Animation.RELATIVE_TO_PARENT, 0.0f);
      outtoRight.setDuration(100);
      outtoRight.setInterpolator(new AccelerateInterpolator());
      return outtoRight;
     }

     private class AsyncDiscogsSearch extends AsyncTask<String, Integer, DiscogsXMLHandler>{

            public static final String APIKEY = "xxxxxxxx";
            private final ProgressDialog pg = new ProgressDialog(discogssearch.this);

            @Override
            protected DiscogsXMLHandler doInBackground(String... params) {

                String urlString = "http://www.discogs.com/search?type=all&q="+params[0]+"&f=xml&api_key="+APIKEY ;

                //Retrieve XML-Data as InputStream
                InputStream instream = GZipStreamHelper.getStream(urlString);

                //Parse XML-Data
                DiscogsXMLHandler discogsHandler = new DiscogsXMLHandler();
                XMLParsingHelper.getInstance().parseAndHandle(instream, discogsHandler);

                return discogsHandler;
            }

            @Override
            protected void onPostExecute(DiscogsXMLHandler result) {
                // TODO Auto-generated method stub
                pg.dismiss();
            }

            @Override
            protected void onPreExecute() {
                pg.show();
            }




        }

}

感谢您的任何建议!

2 个答案:

答案 0 :(得分:1)

据我了解,您的行discogsHandler = at.get();会阻止您的UI线程。执行onPreExecute,但这只会将进度对话框放入主线程的消息循环中。但是,从searchDiscogs()

返回后,将执行实际打开并处理对话框的代码

解决方案是将您对查询结果的处理放入AsyncTask s onPostExecute,或从那里调用结果处理方法。

答案 1 :(得分:1)

我认为user634618是正确的。 AsyncTask#get()州的文档:

  

等待(如有必要)以完成计算,然后检索其结果。

(强调补充)。因此,UI线程只是在调用get时,您将无法执行AsyncTask。由于UI线程被阻止,因此不会执行显示进度对话框的请求。

正如user634618建议的那样,您可以在onPostExecute中处理搜索结果,这将释放UI线程并允许显示进度对话框。