如何在新活动开始时添加进度条

3

我有两个活动AB。我使用意图从A跳转到B。现在在B中。

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

   LoadData();
}

现在在LoadData()中,我需要加载大量数据,所以当B开始时,我想显示一个进度条,在加载数据后,它跳回到我的B活动。我该怎么做?以下是我的加载函数:

public void LoadData(Context context)
    {

        String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
                + ("1") + "'";
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                + " COLLATE LOCALIZED ASC";

        ContentResolver cr = getContentResolver();
        // ContactsContract.Contacts.
        // Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
        // null, null, ContactsContract.Contacts.DISPLAY_NAME);
        // Find the ListView resource.

        Cursor cur;
        cur = context.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI,
                null,
                selection + " AND "
                        + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
                null, sortOrder);

        mainListView = (ListView) findViewById(R.id.mainListView);

        // When item is tapped, toggle checked properties of CheckBox and
        // Planet.
        mainListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener()
                {
                    public void onItemClick(AdapterView<?> parent, View item,
                            int position, long id)
                    {
                        ContactsList planet = listAdapter.getItem(position);
                        planet.toggleChecked();
                        PlanetViewHolder viewHolder = (PlanetViewHolder) item
                                .getTag();
                        viewHolder.getCheckBox().setChecked(planet.isChecked());
                    }
                });

        // Create and populate planets.
        planets = (ContactsList[]) getLastNonConfigurationInstance();
        // planets = new Planet[10];
        // planets.Add("asdf");
        ArrayList<ContactsList> planetList = new ArrayList<ContactsList>();
        String phoneNumber = null;
        String phoneType = null;

        count = cur.getCount();
        contacts = new ContactsList[count];

        if (planets == null)
        {
            if (cur.getCount() > 0)
            {
                planets = new ContactsList[cur.getCount()];
                int i = 0;
                //
                while (cur.moveToNext())
                {
                    String id = cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur
                            .getString(cur
                                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer
                            .parseInt(cur.getString(cur
                                    .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                    {
                        // Query phone here. Covered next
                        Cursor pCur = cr
                                .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                        null,
                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                                + " = ?", new String[]
                                        { id }, null);

                        // WHILE WE HAVE CURSOR GET THE PHONE NUMERS
                        while (pCur.moveToNext())
                        {
                            // Do something with phones
                            phoneNumber = pCur
                                    .getString(pCur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));

                            phoneType = pCur
                                    .getString(pCur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));

                            Log.i("Pratik", name + "'s PHONE :" + phoneNumber);
                            Log.i("Pratik", "PHONE TYPE :" + phoneType);
                        }
                        pCur.close();
                    }

                    if (phoneNumber != null
                            && !planetList.contains(new ContactsList(name,
                                    phoneNumber)))
                    {
                        planets = new ContactsList[]
                        { new ContactsList(name, phoneNumber) };

                        contacts[i] = planets[0];
                        planetList.addAll(Arrays.asList(planets));
                    }
                    phoneNumber = null;
                    i++;
                }
            }

            // for (int i = 0; i < count; i++)
            // {
            // Log.d("New Selected Names : ", contacts[i].getName());
            // }
        }

        // Set our custom array adapter as the ListView's adapter.
        listAdapter = new PlanetArrayAdapter(this, planetList);
        mainListView.setAdapter(listAdapter);

        Adapter adptr;
        adptr = mainListView.getAdapter();
    }
4个回答

1
请尝试这个 ////////////////////////////////////////////////////////////////// 编辑检查它

public class LoadData extends AsyncTask<Void, Void, Void> {
    ProgressDialog progressDialog;
    //declare other objects as per your need
    @Override
    protected void onPreExecute()
    {

        progressDialog= new ProgressDialog(YourActivity.this);
        progressDialog.setTitle("Please Wait..");
        progressDialog.setMessage("Loading");
        progressDialog.setCancelable(false);
        progressDialog.show();

        //do initialization of required objects objects here                
    };      
    @Override
    protected Void doInBackground(Void... params)
    {   
       LoadData();
         //do loading operation here  
        return null;
    }       
    @Override
    protected void onPostExecute(Void result)
    {
        super.onPostExecute(result);
        progressDialog.dismiss();
    };
 }

您可以使用以下方式进行调用

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

   LoadData task = new LoadData();
   task.execute();
}

如需更多帮助,请阅读Android文档 http://developer.android.com/reference/android/os/AsyncTask.html


标题问题与内容有很大不同。但是,如果用户想要从A到B,然后带着结果返回到A,他应该使用onResult方法。https://dev59.com/iXE95IYBdhLWcg3wApLl - deadfish
尝试使用 LoadData(YourActivity.this) 加载数据。 - Kanaiya Katarmal
那么除了LoadData(),我还应该使用什么? - Ahmad Abbasi

0

试试这个。

public class BActivtiy extends Activity implements Runnable{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.list_main);

        mainListView = (ListView) findViewById(R.id.mainListView);

        mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
                ContactsList planet = listAdapter.getItem(position);
                planet.toggleChecked();
                PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
                viewHolder.getCheckBox().setChecked(planet.isChecked());
            }
        });

        pd = ProgressDialog.show(BActivity.this, "Title", "Description", true);
        Thread t = new Thread(BActivity.this);
        t.start();
    }

    public void LoadData() {

        String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'";
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
        ContentResolver cr = getContentResolver();

        Cursor cur;
        cur = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, selection + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1", null, sortOrder);

        // Create and populate planets.
        planets = (ContactsList[]) getLastNonConfigurationInstance();
        // planets = new Planet[10];
        // planets.Add("asdf");
        ArrayList<ContactsList> planetList = new ArrayList<ContactsList>();
        String phoneNumber = null;
        String phoneType = null;
        count = cur.getCount();
        contacts = new ContactsList[count];
        if (planets == null) {
            if (cur.getCount() > 0) {
                planets = new ContactsList[cur.getCount()];
                int i = 0;
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        // Query phone here. Covered next
                        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);

                        // WHILE WE HAVE CURSOR GET THE PHONE NUMERS
                        while (pCur.moveToNext()) {
                            // Do something with phones
                            phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
                            phoneType = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                            Log.i("Pratik", name + "'s PHONE :" + phoneNumber);
                            Log.i("Pratik", "PHONE TYPE :" + phoneType);
                        }
                        pCur.close();
                    }

                    if (phoneNumber != null && !planetList.contains(new ContactsList(name, phoneNumber))) {
                        planets = new ContactsList[] { new ContactsList(name, phoneNumber) };
                        contacts[i] = planets[0];
                        planetList.addAll(Arrays.asList(planets));
                    }
                    phoneNumber = null;
                    i++;
                }
            }

            // for (int i = 0; i < count; i++)
            // {
            // Log.d("New Selected Names : ", contacts[i].getName());
            // }
        }
    }

    @Override
    public void run() {
        LoadData();
        mHandler.sendEmptyMessage(0);
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            pd.dismiss();
            listAdapter = new PlanetArrayAdapter(BActivtiy.this, planetList);
            mainListView.setAdapter(listAdapter);
            Adapter adptr;
            adptr = mainListView.getAdapter();
        }
    };
}

@AhmadAbbasi 请发布完整的错误日志记录,这样我们才能为您提供帮助。 - Dipak Keshariya
android.view.ViewRoot$CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能触摸其视图。 在 android.view.ViewRoot.checkThread(ViewRoot.java:2824) 在 android.view.ViewRoot.invalidateChild(ViewRoot.java:611) 在 android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:637) 在 android.view.ViewGroup.invalidateChild(ViewGroup.java:2513) 在 android.view.View.invalidate(View.java:5138) - Ahmad Abbasi
@AhmadAbbasi,你不能在线程中更新UI,请进行更改。如果你不明白,请在你的问题中发布loaddata()方法。 - Dipak Keshariya
@AhmadAbbasi 写下这几行代码 mainListView.setAdapter(listAdapter); Adapter adptr; adptr = mainListView.getAdapter(); 在 handler 中使用,它将解决你的问题。 - Dipak Keshariya
让我们在聊天室继续这个讨论:http://chat.stackoverflow.com/rooms/19937/discussion-between-ahmad-abbasi-and-igp - Ahmad Abbasi
显示剩余2条评论

0

你只需要在另一个线程中调用你的LoadData()方法。

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

        mDailog = ProgressDialog.show(ActivityA.this, "",
                        "Loading data....!!!", true);
                mDailog.show();

        new Thread() {
                            @Override
                            public void run() {
                                try {
                                      LoadData();
                                } catch (Exception e) {
                                    // TODO: handle exception
                                    e.printStackTrace();
                                }
                            }
                        }.start();

    }

在你的LoadData()方法中,在方法末尾使用处理程序发送消息以关闭进度条对话框。
希望这能帮助你避免使用AsyncTask的复杂逻辑。

0

我同意Kanaiya的答案,因为在API级别-10之前,在UI线程上调用长时间运行的任务是可以的。但从API-11开始,任何需要较长时间(近5秒以上)完成的任务必须在后台线程上完成。原因是任何在UI线程上花费5秒或更长时间的任务都会导致ANR(应用程序无响应),即强制关闭。为了做到这一点,我们必须创建一些后台线程或简单地使用AsyncTask。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接