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

4 回答 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

于 2012-11-22T11:01:29.967 回答
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 的复杂逻辑。

于 2012-11-22T13:21:37.803 回答
0

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

于 2012-11-22T11:54:46.013 回答
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();
        }
    };
}
于 2012-11-22T11:05:05.390 回答