Shazar
Shazar

Reputation: 103

Storing data into String array and pass it to AsyncTask

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

Upvotes: 0

Views: 2402

Answers (5)

Shayan Pourvatan
Shayan Pourvatan

Reputation: 11948

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

Upvotes: 1

saravanan
saravanan

Reputation: 388

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

Upvotes: 0

Alessandro Verona
Alessandro Verona

Reputation: 1257

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

Upvotes: 0

Sonali8890
Sonali8890

Reputation: 2005

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.

Upvotes: 0

Aparupa Ghoshal
Aparupa Ghoshal

Reputation: 309

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

Upvotes: 0

Related Questions