【问题标题】:Progress dialog does not open on preExecute in Asynctask non-activity class在 Asynctask 非活动类中的 preExecute 上未打开进度对话框
【发布时间】:2014-05-02 09:17:05
【问题描述】:

我正在使用 ksoap 调用 Web 服务。 当应用程序启动或当我滚动到页面末尾时,应用程序正确地从 Web 服务获取数据并且它显示了我想要的数据,但是当我想在 AsyncTask 中显示进度对话框时它不能正常工作。它在 PostExecute 之后一闪而过地显示了进度对话框。那么,我的代码有什么问题?我不明白我的问题在哪里。 ;-)

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

这是一个使用 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 的类。

在主活动中,我在 onCreate 方法中调用了一个名为 LoadContent 的本地方法。 这是 MainActivity 类

 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");

    }   

}   

}

【问题讨论】:

    标签: java android android-asynctask progressdialog


    【解决方案1】:

    你有

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

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

     task.execute("getLatest");
    

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

    【讨论】:

    • 当我将此行 strJSON = task.execute("getLatest").get() 更改为 strJSON = task.execute("getLatest") 时,我将遇到类型不匹配错误。它会建议我将strJson 类型从String 更改为AsyncTask&lt;String, Void, String&gt;。那么,我该怎么办?
    • 不需要 strJSON = task.execute("getLatest") 只需 task.execute("getLatest") 。您可以使用接口作为对活动的回调
    • @user3594119 检查此stackoverflow.com/questions/16752073/… 仅使用task.execute("getLatest") 您可以使用界面返回活动
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多