【问题标题】:How to show a progress spinner in android, when doInBackground() is being executed执行doInBackground()时如何在android中显示进度微调器
【发布时间】:2012-08-01 05:23:00
【问题描述】:

这是我的 Activity 类,我使用 AsyncTask 从服务器获取数据:

public class UserProfileActivity extends Activity {

    private ImageView userImage;
    private TextView userName;
    private TextView userLocation;
    private TextView editInfo;
    private TextView chnageImage;
    private TextView userScore;
    private ListView friendsList;
    public ArrayAdapter<String> adapter;
    public int score;
    public int level;
    public String image;
    public String fname;
    public String lname;
    public String city;
    public int id;
    public String email;
    protected Activity activity = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.user_profile);

        userImage = (ImageView) findViewById(R.id.profileImage);
        userName = (TextView) findViewById(R.id.userName_profile);
        userLocation = (TextView) findViewById(R.id.userLocation_profile);
        editInfo = (TextView) findViewById(R.id.edit_profile);
        chnageImage = (TextView) findViewById(R.id.changeImage_profile);
        userScore = (TextView) findViewById(R.id.userScore_profile);
        friendsList = (ListView) findViewById(R.id.friendsList);

        new LongOperation().execute("");

    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        private InputStream is;
        private StringBuilder sb;
        private String result;

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

            try {
                HttpPost httppost = new HttpPost(
                        "http://www.xxxxxxxxx.com/mobile/getProfileInfo");
                HttpResponse response = SignUpActivity.httpclient
                        .execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is, "iso-8859-1"), 8);
                    sb = new StringBuilder();
                    sb.append(reader.readLine() + "\n");
                    String line = "0";
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                } catch (Exception e) {
                }
                try {
                    JSONObject jObj = new JSONObject(result);
                    String status = jObj.getString("status");
                    score = jObj.getInt("credits");
                    level = jObj.getInt("level");
                    image = jObj.getString("image");
                    fname = jObj.getString("fname");
                    lname = jObj.getString("lname");
                    city = jObj.getString("city");
                    id = jObj.getInt("user_id");
                    email = jObj.getString("email");

                    JSONArray friendsJsonArray = jObj.getJSONArray("friends");
                    int size = friendsJsonArray.length();

                    ArrayList<String> friendsNames = new ArrayList<String>();
                    String[] friendsIds = new String[size];
                    for (int i = 0; i < size; i++) {

                        friendsNames.add(friendsJsonArray.getJSONObject(i)
                                .getString("name"));
                    }
                    adapter = new ArrayAdapter<String>(getApplicationContext(),
                            R.layout.simple_listview_item, friendsNames);

                } catch (Exception e) {
                }
            } catch (Exception e) {
            }

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

            friendsList.setAdapter(adapter);
            userScore.setText(score + " points" + "   level " + level);
            userName.setText(fname + "  " + lname);
            userLocation.setText(city);
            Bitmap bitmap = null;
            try {
                bitmap = BitmapFactory
                        .decodeStream((InputStream) new URL(image).getContent());
            } catch (MalformedURLException e1) {

                e1.printStackTrace();
            } catch (IOException e2) {

                e2.printStackTrace();
            }
            userImage.setImageBitmap(bitmap);

        }

        @Override
        protected void onPreExecute() {
        }

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

加载此活动时,它会显示所有默认值和图像,然后在后台代码执行完成时更改(例外),但这需要 2-3 秒,用户将看到默认值,这是我不想要的到。那么我怎样才能保持这样的微调器:

持续 2-3 秒,然后当微调器消失时,活动必须显示实际值。

谢谢

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    参考以下代码

    private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {
    
        private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
    
        /** progress dialog to show user that the backup is processing. */
        /** application context. */
        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Please wait");
            this.dialog.show();
        }
    
        @Override
        protected Boolean doInBackground(final String... args) {
            try {
    
                Utilities.arrayRSS = objRSSFeed
                        .FetchRSSFeeds(Constants.Feed_URL);
                return true;
            } catch (Exception e) {
                Log.e("tag", "error", e);
                return false;
            }
        }
    
        @Override
        protected void onPostExecute(final Boolean success) {
    
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
    
            // Setting data to list adapter
            setListData();
        }
    

    【讨论】:

    • 你能告诉我如何让这个progressDialog只出现在一个特定的视图上吗??......就像我有一个带有TextViews和一个ListView的活动。 TextViews 很容易填充,但 ListView 需要时间来获取数据。所以我希望这个 ProgressDialog 只出现在 ListView 上??
    • 您必须在后台从服务器获取数据时显示 ProgressDialog。不适合特定视图
    • 不是你的意思是我不能??...因为在某些应用程序中,它们会在同一活动中显示 3-4 个 ProgressDialogs。将尝试上传该应用程序的图片
    • 你可以这样做。为此,您必须调用另一个 Asynctask。一个完成后调用另一个
    • 是的,但是如何单独在列表视图上进行小进度对话框??....同一活动上的任何其他按钮或文本视图都将处于活动状态,而列表视图与此进度对话框重叠
    【解决方案2】:

    这样做:-

    1. 声明顶部的 ProgressDialog。

      ProgressDialog pd; 
      
    2. 启动它在异步任务的onPreExecute方法中。

      pd=ProgressDialog.show(ActivityName.this,"","Please Wait",false); 
      
    3. 停止它在 onPostExecute 方法中。

      pd.dismiss();
      

    【讨论】:

      【解决方案3】:

      在 onCreate 方法中调用如下所示

      mdialog=new Dialog(this);
       new LongOperation().execute("");
      

      然后覆盖 AyncTask 的 onPostExecute

      @Override
              protected void onPostExecute() {
              runOnUiThread(new Runnable() {
      
             @Override
             public void run() {
              // TODO Auto-generated method stub
              mdialog.dismiss();
             }
            });
              }
      

      【讨论】:

      • onPostExecute 按照设计在 UI 线程上运行。在这种情况下,添加 runOnUiThread 调用是多余的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多