0

I am getting all of my contacts details from contactconstract table, and Want to store all my contact data to String array then I would like to pass it to AsyncTask for doing some background task,Currently I am passing single contacts detail to AsyncTask,that would made my code crash because one by one asynctask is being called for each contact detail, I would like to store all my contact detail into array an then I pass this array to AsyncTASK so only one time AsyncTask would call so Please help me in this regard,

Given below is my part of the code:

ContentResolver cr = getContentResolver();
        SavingContacts savingcontacts=new SavingContacts();
        Cursor = getContentResolver().query(
                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                 null, null,
                 ContactsContract.Contacts.DISPLAY_NAME + " ASC");
        Log.d("database1" ,"17");
       if (Cursor.getCount() > 0)  {
             while (Cursor.moveToNext()) {

                  phone = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                 if (!TextUtils.isEmpty(phone)) {

                     Log.d("Your Location4", "ok4:");
                          name = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                          id = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                         // photouri=Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO));
                          email=Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                         System.out.println("contactId="+ id+ ", name=" + name + ", phoneNumber=" + phone+"Email="+email);

                 }
                 savingcontacts.savingcontact(id, name, phone, email);
             }


                }
       Cursor.close();

I am doing this work In oncreate function of activity //////////////////////////////////////////////////////////////////

Activity Class

   public class ContactsListActivity extends FragmentActivity  implements
ContactsListFragment.OnContactsInteractionListener {

    // Defines a tag for identifying log entries
    private static final String TAG = "ContactsListActivity";

    private  Cursor  Cursor;
    private ContactDetailFragment mContactDetailFragment;
   public  DBHandler db;
    // If true, this is a larger screen device which fits two panes
    private boolean isTwoPaneLayout;
    String id,name,phone, email;


    // True if this activity instance is a search result view (used on pre-HC devices that load
    // search results in a separate instance of the activity rather than loading results in-line
    // as the query is typed.
    private boolean isSearchResultView = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (BuildConfig.DEBUG) {
            Utils.enableStrictMode();
        }
        super.onCreate(savedInstanceState);
        Log.d("Hope","Hope 8");
        // Set main content view. On smaller screen devices this is a single pane view with one
        // fragment. One larger screen devices this is a two pane view with two fragments.
        setContentView(R.layout.activity_main);
      //  Getallcontacts();
        // Check if two pane bool is set based on resource directories
        isTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);

        // Check if this activity instance has been triggered as a result of a search query. This
        // will only happen on pre-HC OS versions as from HC onward search is carried out using
        // an ActionBar SearchView which carries out the search in-line without loading a new
        // Activity.

        if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {

            // Fetch query from intent and notify the fragment that it should display search
            // results instead of all contacts.
            String searchQuery = getIntent().getStringExtra(SearchManager.QUERY);
            ContactsListFragment mContactsListFragment = (ContactsListFragment)
                    getSupportFragmentManager().findFragmentById(R.id.contact_list);
            Log.d("Hope","Hope 47");

            // This flag notes that the Activity is doing a search, and so the result will be
            // search results rather than all contacts. This prevents the Activity and Fragment
            // from trying to a search on search results.
            isSearchResultView = true;
            mContactsListFragment.setSearchQuery(searchQuery);

            // Set special title for search results
            String title = getString(R.string.contacts_list_search_results_title, searchQuery);
            setTitle(title);

        }

        if (isTwoPaneLayout) {
            // If two pane layout, locate the contact detail fragment
            mContactDetailFragment = (ContactDetailFragment)
                    getSupportFragmentManager().findFragmentById(R.id.contact_detail);


        }
        ContentResolver cr = getContentResolver();
     //   SavingContacts savingcontacts=new SavingContacts();
        ArrayList<SavingContacts> contacts = new ArrayList<SavingContacts>();
        Cursor = getContentResolver().query(
                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                 null, null,
                 ContactsContract.Contacts.DISPLAY_NAME + " ASC");
        Log.d("database1" ,"17");
       if (Cursor.getCount() > 0)  {
             while (Cursor.moveToNext()) {
                 SavingContacts savingcontacts=new SavingContacts();

                  phone = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                 if (!TextUtils.isEmpty(phone)) {

                     Log.d("Your Location4", "ok4:");
                          name = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                          id = Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                         // photouri=Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO));
                          email=Cursor.getString(Cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                         System.out.println("contactId="+ id+ ", name=" + name + ", phoneNumber=" + phone+"Email="+email);
                         savingcontacts.savingcontact(id, name, phone, email);
                         contacts.add(savingcontacts);
                 }

             }


                }
       Cursor.close();
       new LoadSavingInDatabase.execute(contacts);



    }


    public static class LoadSavingInDatabase extends AsyncTask<ArrayList<SavingContacts>,String,String>{

        private static final String TAG_SUCCESS = "success";
        private static final String URL = "http://amiranzur.com/android_connect/create_product.php";

        JSONObject jsonObject= null;

        @Override
        protected String doInBackground(ArrayList<SavingContacts>... params) {



            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id", id));
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("phone", phone));
            params.add(new BasicNameValuePair("email" , email ));


            JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);

        if(jsonObject != null){
            try {
                int success = jsonObject.getInt(TAG_SUCCESS);

                if (success == 1) {

                   Log.d("create","lpc");

                  // bool = true;
                //   Log.d("insert","true" + bool); 
                } else {

                }
            } catch (JSONException e) {
                Log.d("exception","exc "+e);
                Log.d("create","lpc");
            }

        }
        else if(jsonObject == null){
            Log.d("null", "null1");
            //bool = false;
        }


            return null;
        }

        protected void onPostExecute(boolean bool){
            if(bool == false)
            Log.d("Insertion failed", "ID already inserted");


        }


    }





   /* public void Getallcontacts()
    {
        ContentResolver resolver;
    Cursor c = getContentResolver().query(
            Data.CONTENT_URI, 
            null, 
            Data.HAS_PHONE_NUMBER + "!=0 AND (" + Data.MIMETYPE + "=? OR " + Data.MIMETYPE + "=?)", 
            new String[]{Email.CONTENT_ITEM_TYPE, Phone.CONTENT_ITEM_TYPE},
            Data.CONTACT_ID);

    while (c.moveToNext()) {
        long id = c.getLong(c.getColumnIndex(Data.CONTACT_ID));
        String name = c.getString(c.getColumnIndex(Data.DISPLAY_NAME));
        String data1 = c.getString(c.getColumnIndex(Data.DATA1));

        System.out.println(id + ", name=" + name + ", data1=" + data1);
    }

    }*/



    /**
     * This interface callback lets the main contacts list fragment notify
     * this activity that a contact has been selected.
     *
     * @param contactUri The contact Uri to the selected contact.
     */

    public void onContactSelected(Uri contactUri) {
        if (isTwoPaneLayout && mContactDetailFragment != null) {
            // If two pane layout then update the detail fragment to show the selected contact
            mContactDetailFragment.setContact(contactUri);
        } else {
            // Otherwise single pane layout, start a new ContactDetailActivity with
            // the contact Uri
            Intent intent = new Intent(this, ContactDetailActivity.class);
            intent.setData(contactUri);
            startActivity(intent);
        }
    }

    /**
     * This interface callback lets the main contacts list fragment notify
     * this activity that a contact is no longer selected.
     */

    public void onSelectionCleared() {
        if (isTwoPaneLayout && mContactDetailFragment != null) {
            mContactDetailFragment.setContact(null);
        }
    }

    @Override
    public boolean onSearchRequested() {
        // Don't allow another search if this activity instance is already showing
        // search results. Only used pre-HC.
        return !isSearchResultView && super.onSearchRequested();
    }
7
  • see stackoverflow.com/questions/15894418/… Commented Feb 21, 2014 at 10:33
  • You mean to say I have to make 4 array list for id, name,phone,emial?I created just One array list like ArrayList<String> passing = new ArrayList<String>(); and then use passing.add(id),passing.add(name)....like that, isn't a right approach? Commented Feb 21, 2014 at 10:47
  • if you have 4 parameter then create one class, and send one list of that class to asyncTask class Commented Feb 21, 2014 at 10:48
  • can you please give me some idea or post a answer it would be highly appreciated thanks Commented Feb 21, 2014 at 10:50
  • did you have class for that? Commented Feb 21, 2014 at 10:51

5 Answers 5

1

you need create one class for your purpose like following:

public class Contact()
{
   private String _name , _phoneNum , _email , _id;

   public Contact(String id , String name , String phoneNum , String emailAdd)
   {
      _name = name;
      _phoneNum = phoneNum;
      _id = id;
      _email = emailAdd;
   }

   public void SetName(String name)
   {
        _name = name;
   }

   public String GetName()
   {
        return _name;
   }

 // other getter and setter
}

and for passing to your AsyncTask use:

    ArrayList<Contact> contacts = new ArrayList<Contact>()

   // add this two line and do this for all your obj

   Contact contact = new Contact(id , name , phoneNumber , emailAddress);
   contacts.add(contact);

  // after putting all data to contacts do following code

   TestAsyncTask task= new TestAsyncTask();
   task.execute(contacts);

and AsyncTask class:

class TestAsyncTask extends AsyncTask<ArrayList<Contact>, Void, Void>{

         @Override
         protected Void doInBackground(ArrayList<Contact>... params) {
                 // TODO Auto-generated method stub

                 ArrayList<Contact> contactArray = params[0];             

                 return null;
           }
        }
Sign up to request clarification or add additional context in comments.

8 Comments

Shayan sory to bother please explain me , I already have id,name email, phone attirubute so how do I connects these attribute to contacts class,i am so confused help me thanks
ok, i will change my code on Contact class and setting data, i comment that this line change, see that,
see my Edit, i add constructor in Contact class and add two line before sending to AsyncTask class
and for thanks people that answer to you just up vote them, and if one answer help you tick that as an answer
// add this two line and do this for all your obj, shayan what is that mean?
|
0

While declaring the AsyncTask in your class , declare it as follow :

  class TestAsyncTask extends AsyncTask<String[], Void, Void>{

                @Override
                protected Void doInBackground(String[]... params) {
                    // TODO Auto-generated method stub

                                 String[] strArray = params[0];             

                    return null;
                }

            }

The first parameter for the accepts the parameter you want to pass to the Asynctask created by you.

Also, call it as :

new TestAsyncTask().execute(myStringArray);

Comments

0

Create an array list like

 ArrayList<SavingContact> contactList = new ArrayList<SavingContact>();

and when you are adding into model object add that object tnto array list like

savingcontacts.savingcontact(id, name, phone, email);
contactList.add(savingcontacts);

and then pass this arraylist in constructor of your asyntask class.

Comments

0

Create a object "Contact" and fillt it with set and get method for ID, NAME, PHONE, and EMAIL.

public class Contact()
{
   private String _name;

   public void setName(String name)
   {
        _name = name;
   }

   public String getName()
   {
        return _name;
   }

   [...]
}

Store all your contacts in a List:

List<Contact> contacts = new ArrayList<Contact>()

Send your list to your AsyncTask

Comments

0

Best You Can use like this

class TestAsyncTask extends AsyncTask<ArrayList<String>, Void, Void>{

            @Override
            protected Void doInBackground(ArrayList<String>... params) {
                // TODO Auto-generated method stub

                             for(int i =0 ; i<params.size();i++)
                            {
                               String Str = params.get(i);
                            }        

                return null;
            }

        }

you can use like that,its easy way to store values to Array and also get values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.