开发者

Showing a ProgressDialog while SEARCHING in Android

开发者 https://www.devze.com 2023-02-14 04:03 出处:网络
I read all Questions on stackoverflow that could give me a hint with this but i can\'t get this to work.

I read all Questions on stackoverflow that could give me a hint with this but i can't get this to work.

What i have:

I've got an activy called "wantlist" which starts witch my app. On this activity i have a button which starts a search via onSearchRequested();

I have another activity called "discogssearch" which makes a call to an XML Api on the internet, parses the data and displays the search results.

All of this is working fine.

What i want to achieve:

I want to display a ProgessDialog while the time consuming api call is beeing issued.

What i tried:

I tried opening a ProgessDialog on many ways before the search starts and found out, that i have to do this asynchronous to the main thread. So i put the time consuming code into an AsyncTask and started it.

What happens:

When i entered a text and hit enter nothings happening (as before) until the results arrive. Now the "discogssearch" perspective is beeing displayed with the results and the ProgressDialog shows up but a this point all the work is done already.

My Code:

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"));
    wan开发者_如何学Pythonts.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();
            }




        }

}

Thanks for any suggestions!


As I understand it, your line discogsHandler = at.get(); blocks your UI thread. onPreExecute is executed, but this only puts the progress dialog into the main thread's message loop. However, the code that actually opens and handles the dialog is executed after returning from searchDiscogs()

A solution would be to put your handling of the query's result into the AsyncTasks onPostExecute, or call result handling method from there.


I think user634618 is correct. The documentation for AsyncTask#get() states:

Waits if necessary for the computation to complete, and then retrieves its result.

(Emphasis added). So the UI thread just sits at the call to get and you lose the point of performing an AsyncTask. Since the UI thread is blocked, your request to display a progress dialog is not executed.

As user634618 suggests, you can handle the result of the search in onPostExecute, which will free up the UI thread and allow your progress dialog to display.

0

精彩评论

暂无评论...
验证码 换一张
取 消