Android的ProgressDialog进度条做的事情以正确的顺序(Android Progre

2019-10-21 00:46发布

我只是得到了这一点,但我对事物的秩序的一个小问题去了。 具体而言,在我的螺纹()我正在设置所使用的一个微调的阵列。 问题是微调的所有设置和我的线程之前基本上完成了()完成,因此将自身设置了一个空数组。

如何关联的纺纱ArrayAdapter与正在被另一个线程加载一个数组?

我剪的代码下降到什么,我认为是有必要了解的问题,只是让我知道,如果需要更多。 出现该问题是否refreshData()被调用。

按照同样的思路,有时我想从菜单中调用loadData()。 直接跟随loadData()如果我尝试火下一行这会导致forceclose,这是因为我是如何实现ProgressDialog也举杯。

谢谢光临

public class CMSHome extends Activity { 

private static List<String> pmList = new ArrayList<String>();

// Instantiate helpers
PMListHelper plh = new PMListHelper();
ProjectObjectHelper poc = new ProjectObjectHelper();

// These objects hold lists and methods for dealing with them
private Employees employees;
private Projects projects;

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

    // Loads data from filesystem, or webservice if necessary
    loadData();

    // Capture spinner and associate pmList with it through ArrayAdapter
    spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    this, android.R.layout.simple_spinner_item,
                    pmList);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    //---the button is wired to an event handler---
    Button btn1 = (Button)findViewById(R.id.btnGetProjects);
    btn1.setOnClickListener(btnListAllProjectsListener);
    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}


private void loadData()
{
    final ProgressDialog pd = ProgressDialog.show(this,
            "Please wait", "Loading Data...", true, false);

    new Thread(new Runnable(){
        public void run(){
            employees = plh.deserializeEmployeeData();
            projects = poc.deserializeProjectData();

            // Check to see if data actually loaded, if not then refresh
            if ((employees == null) || (projects == null)) {
                refreshData();
            }

            // Load up pmList for spinner control
            pmList = employees.getPMList();

            pd.dismiss();
        }
    }).start();
}

private void refreshData()
{
    // Refresh data for Projects
    projects = poc.refreshData();
    poc.saveProjectData(mCtx, projects);

    // Refresh data for PMList          
    employees = plh.refreshData();
    plh.savePMData(mCtx, employees);
}
}

<---- EDIT ----->我试图改变的onCreate()来吉姆的建议之后以下。 不知道是否我没这个权利,仍然不能正常工作:

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

    mCtx = this;

    // Loads data from filesystem, or webservice if necessary
    // Would like to extend this to update if files are over x days old
    final ProgressDialog pd = ProgressDialog.show(this,
            "Please wait", "Loading Data...", true, false);

    new Thread(new Runnable(){
        public void run(){
            employees = plh.deserializeEmployeeData();
            projects = poc.deserializeProjectData();

            // Check to see if data actually loaded, if not then refresh
            if ((employees == null) || (projects == null)) {
                refreshData();
            }

            pd.dismiss();

            runOnUiThread(new Runnable() {
                public void run(){
                    // Load up pmList for spinner control
                    pmList = employees.getPMList();
                }
            });

        }
    }).start();

    spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, pmList);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    //---the button is wired to an event handler---
    Button btn1 = (Button)findViewById(R.id.btnGetProjects);
    btn1.setOnClickListener(btnListAllProjectsListener);
    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}

哇,这花了永远为我找到一个解决方案,但是我喜出望外地终于得到了这个工作。

更新与后台线程的微调可通过利用处理器来实现。 线程的主要工作完成后的处理程序被调用。

  mProgressDlg = ProgressDialog.show(this, "App_Name", "Loading data...", 
                                    true, false);
  new Thread(new Runnable(){
            public void run() {
                    /*Load Data, set pmList in my case*/
                    mProgressDlg.dismiss();
                    hRefresh.sendEmptyMessage(REFRESH);
            }
    }).start();



Handler hRefresh = new Handler(){

@Override
public void handleMessage(Message msg) {
   switch(msg.what){
     case REFRESH:
                 spinner = (Spinner) findViewById(R.id.spinner);
                 final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                         mCtx, android.R.layout.simple_spinner_item, pmList);
                 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                 spinner.setAdapter(adapter);
                 spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
            break;
   }
}
};

感谢bhatt4982和他在回答这个线程

Answer 1:

不知道你是否曾解决过这个,但是这对我的作品:

public class Start extends Activity {
private static final String TAG = "PriceList";

ArrayAdapter<ProductCategory> category_adapter;
ArrayAdapter<ProductGroup> group_adapter;

ArrayList<ProductCategory> categories;
ArrayList<ProductGroup> groups;

ArrayList<Price> prices;

Spinner group_spinner;
Spinner category_spinner;
ProgressDialog progressDialog;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    group_spinner = (Spinner) findViewById(R.id.group_spinner);
    category_spinner = (Spinner) findViewById(R.id.category_spinner);

    // product category spinner
    categories = new ArrayList<ProductCategory>();

    category_adapter = new CustomArrayAdapter<ProductCategory>(categories);
    category_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // load category spinner from database
    loadCategory();     // adapter MUST be setup before this is called

    category_spinner.setAdapter(category_adapter);
    category_spinner.setOnItemSelectedListener(new OnItemSelectedListener () {


    ..... other stuff ...... 


private final Handler handler = new Handler() {
    @Override
    public void handleMessage(final Message msg) {
        Log.v(TAG, "worker thread done, setup adapter");

        switch (msg.what) {
        case Constants.CATEGORIES:
            category_adapter.notifyDataSetChanged();
            break;
        case Constants.GROUPS:
            group_adapter.notifyDataSetChanged();
            break;
        case Constants.PRICES:
            startActivity(new Intent(Start.this, ShowPrices.class));
            break;
        default:
        }
        // dismiss dialog
        progressDialog.dismiss();
    }
};

    // loadCategory() essentially the same....

private void loadGroup(final String cat) {
    Log.v(TAG, "loadGroup");

    progressDialog = new ProgressDialog(this);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setMessage("Retrieving Product Groups...");
    progressDialog.setMax(100);
    progressDialog.setProgress(0);
    progressDialog.show();

    new Thread() {

        @Override
        public void run() {

            int count = 100;
            int i = 0;

            SQLiteDatabase db = DbUtils.getStaticDb();

            Cursor c = db.rawQuery("select count(*) from productgroup where category = \'"
                            + cat + "\';", null);
            c.moveToFirst();
            if (!c.isAfterLast()) {
                count = c.getInt(0);
            }
            c.close();

            progressDialog.setMax(count);

            groups.clear();
            groups.add(new ProductGroup("-1", "--- Select ---"));

            StringBuilder sb = new StringBuilder("select _id,description from productgroup");
            sb.append(" where category = \'");
            sb.append(cat);
            sb.append("\' order by description;");
            Log.v(TAG, sb.toString());

            c = db.rawQuery(sb.toString(), null);
            c.moveToFirst();
            while (!c.isAfterLast()) {
                Log.v(TAG, c.getString(0));
                groups.add(new ProductGroup(c.getString(0), c.getString(1)));
                i++;
                if (i % 5 == 0) {
                    progressDialog.setProgress(i);
                }
                c.moveToNext();
            }
            c.close();

            // tell UI thread OK
            handler.sendEmptyMessage(Constants.GROUPS);
        }
    }.start();
}

    // custom ArrayAdapter allows us to have our own ArrayList<T>

class CustomArrayAdapter<T> extends ArrayAdapter<T> {

    CustomArrayAdapter(ArrayList<T> list) {
        super(Start.this, android.R.layout.simple_spinner_item, list);
    }

}


Answer 2:

所有loadData()中的onCreate()后的工作需要已经完成做后运行的工作()在线程中loadData()触发。 尝试pd.dismiss后内联loadData(),并添加此设置后工作提高到一个runOnUiThread()()。



Answer 3:

我也建议你使用https://github.com/commonsguy/cwac-task它有非常好的AsyncTaskEx IMPL,你可以用它来干重活不锁定用户界面。

实施例类;

protected class DoHeavyWorkAsync extends AsyncTaskEx<Void, Integer, String> {
        private static final String TAG = "DoHeavyWorkAsync";

        @Override
        protected String doInBackground(Void... arg0) {

            // do heavy work here. e.g. loadDataFromSomewhere();
            YourActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    // you can do ui work on the main activity from here
                }
            });

            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            Log.d(TAG, "onPreExecute()");
                    //e.g. display "loading..." 
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.d(TAG, "onPostExecute()");
        }
    }

从您的主要活动,你可以这样调用;

(new DoHeavyWorkAsync()).execute();


文章来源: Android ProgressDialog Progress Bar doing things in the right order