将数据存储到String数组中并将其传递给AsyncTask

时间:2014-02-21 10:29:08

标签: android android-asynctask arrays

我从contactconstract表中获取了所有联系人详细信息,并希望将所有联系人数据存储到字符串数组然后我想将其传递给AsyncTask以执行一些后台任务,目前我我将单个联系人详细信息传递给AsyncTask,这会导致我的代码崩溃,因为每个联系人详细信息都会调用一个asynctask,我想将所有联系人详细信息存储到数组中然后我将此数组传递给AsyncTASK所以只有一次AsyncTask会这么称呼,请在这方面帮助我,

以下是我的代码部分:

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

我正在做这项工作在活动的oncreate功能 ////////////////////////////////////////////////// ////////////////

活动类

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

5 个答案:

答案 0 :(得分:1)

你需要为你的目的创建一个类,如下所示:

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
}

并传递给AsyncTask使用:

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

和AsyncTask类:

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

答案 1 :(得分:0)

在您的类中声明AsyncTask时,请将其声明为:

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

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

                                 String[] strArray = params[0];             

                    return null;
                }

            }

接受您想要传递给您创建的Asynctask的参数的第一个参数。

另外,请将其命名为:

new TestAsyncTask()。execute(myStringArray);

答案 2 :(得分:0)

创建一个像

这样的数组列表
 ArrayList<SavingContact> contactList = new ArrayList<SavingContact>();

当你添加到模型对象中时,将该对象添加到数组列表中,如

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

然后在你的asyntask类的构造函数中传递这个arraylist。

答案 3 :(得分:0)

创建一个对象“Contact”并用ID,NAME,PHONE和EMAIL的set和get方法填充它。

public class Contact()
{
   private String _name;

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

   public String getName()
   {
        return _name;
   }

   [...]
}

将所有联系人存储在列表中:

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

将您的列表发送到AsyncTask

答案 4 :(得分:0)

最好你可以这样使用

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

        }

您可以这样使用,它可以轻松地将值存储到Array并获取值