在Asynctask非活动类中的preExecute上不会打开“进度”对话框

时间:2014-05-02 09:17:05

标签: java android android-asynctask progressdialog

我正在使用kso​​ap来调用Web服务。 当应用程序启动或滚动到页面结束时应用程序正确地从Web服务获取数据并显示我想要的数据,但是当我想在AsyncTask中显示进度对话框时,它无法正常工作。它显示PostExecute之后的进度对话框。那么,我的代码有什么问题?我无法理解我的问题在哪里。 ;-)

我有一个名为ElvatraWebService的Web服务类:

这是一个使用Asynctasks获取最新帖子的方法

private  String GetLastPublicPosts(int counter){
    ...
    ...
    ...
    ...
    return resTxt; //Returns JSON String 
}



public String getLatestPost(int counter, Activity a){

    CallLatestPost task = new CallLatestPost(counter,a);
    try {
        strJSON = task.execute("getLatest").get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //Log.i("sss", "--" + strJSON);
    return strJSON;

}

private class CallLatestPost extends AsyncTask<String, Void, String> {
    private int Counter = 0;
    private ProgressDialog dialog;
    private Activity activity;
    private Context context;


    public CallLatestPost (int c,Activity actt) {
        super();
        this.Counter = c;
        activity = actt;
        context = actt;
        dialog = new ProgressDialog(this.context);

    }

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

        ElvatraWebService elws = new ElvatraWebService();
        String tmp = elws.GetLastPublicPosts(this.Counter);
        //Log.i("strJSON",strJSON);
        return tmp;
    }

    @Override
    protected void onPostExecute(String result) {
        //Set response 
        super.onPostExecute(result);

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

    }

    @Override
    protected void onPreExecute() {

        super.onPreExecute();



        dialog = new ProgressDialog(context);
        dialog.setMessage("Connecting...");
        //dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.show();

        Log.i("@@@Async", "=== " + "PreExec");
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }

}

我有一个名为post的类。它将从Elvatrawebservice调用getLatestPost。 然后它将使用PostAdapter类将JSON String转换为JsonArray。 PostAdapter是一个扩展BaseAdapter的类。

在Main Activity中我在onCreate方法中调用一个名为LoadContent的本地方法。 这是MainActivity Class

 public class MainActivity extends Activity {


String displayText="";
public TextView tv;
public ListView lv;
public ProgressBar pg;


int theCounter=20;
String[] strTAG = new String[] {"title","photo","date","desc","linkurl"};
//int[] intField = new int[] {R.id.title,R.id.imgPost, R.id.Date, R.id.desc, R.id.link};
ListAdapter sa;
List<HashMap<String,Object>> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recentposts);


    lv = (ListView) findViewById(R.id.list);    
    lv.setOnScrollListener(new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {

           final int lastItem = firstVisibleItem + visibleItemCount;
           if(lastItem == totalItemCount) {
               //load more data
            // Load content of listview
            LoadContent();


           }
        }
    });




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}



@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass

    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}



public void LoadContent(){

    lv = (ListView) findViewById(R.id.list);

    Post p = new Post(theCounter);
    theCounter+=20;
    if (p.GetLatestPosts(lv,MainActivity.this))
    {
        //tv.setText("true");

    }   

}   

}

1 个答案:

答案 0 :(得分:1)

你有

 task.execute("getLatest").get();

你不应该调用get(),因为这会阻塞等待结果的ui线程,使得asynctask不再异步。只需使用

 task.execute("getLatest");

您可以在doInBackground中返回结果,并在onPostExecute中更新ui。