简体   繁体   中英

how to put progress bar in starting of a new activity

i Have two activities A and B . i used intent to jump from A to B . now in B .

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

   LoadData();
}

now in LoadData() , i have to load a lot of data, wo i want that when it B starts, it show a Progress bar and after loading the data, it jumps back to my activity B. how can I do this??? here is my load function

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();
    }

Please try this ////////////////////////////////////////////////////////////////// Edit Check It

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();
    };
 }

You can call this using

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

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

for more help read android document http://developer.android.com/reference/android/os/AsyncTask.html

Try this.

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();
        }
    };
}

I am agree with Kanaiya's answer because upto the API level-10 it is fine to call long running tasks on UI thread. But from API-11, any task that takes longer time (nearly more than 5 sec) to complete must be done on background thread. The reason behind this is any task that takes 5 seconds or more on UI thread then ANR(Application Not Responding) ie force close happens. To do that we have create some background thread or simply make use of AsyncTask.

You just need to call your LoadData() method in another thread.

    @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();

    }

Inside your LoadData(), at the end of the method use a handler to send a message to dismiss the progress bar dialog.

Hope this will help you to avoid the complex logic using AsyncTask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM