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,
我从contactconstract表获取所有联系人详细信息,并希望将我的所有联系人数据存储到String数组然后我想将它传递给AsyncTask以执行一些后台任务,目前我将单个联系人详细信息传递给AsyncTask,使我的代码崩溃,因为每个联系人详细信息都会调用一个asynctask,我想将所有联系人详细信息存储到数组中然后我将此数组传递给AsyncTASK所以只有一次AsyncTask会调用所以请在这方面帮助我,
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();
}
5 个解决方案
#1
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:
并传递给您的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);
and AsyncTask class:
和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;
}
}
#2
0
While declaring the AsyncTask in your class , declare it as follow :
在您的类中声明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;
}
}
The first parameter for the accepts the parameter you want to pass to the Asynctask created by you.
接受要传递给您创建的Asynctask的参数的第一个参数。
Also, call it as :
另外,将其命名为:
new TestAsyncTask().execute(myStringArray);
new TestAsyncTask()。execute(myStringArray);
#3
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
当你添加到模型对象时添加该对象tnto数组列表就像
savingcontacts.savingcontact(id, name, phone, email);
contactList.add(savingcontacts);
and then pass this arraylist in constructor of your asyntask class.
然后在你的asyntask类的构造函数中传递这个arraylist。
#4
0
Create a object "Contact" and fillt it with set and get method for ID, NAME, PHONE, and EMAIL.
创建一个对象“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;
}
[...]
}
Store all your contacts in a List:
将所有联系人存储在列表中:
List<Contact> contacts = new ArrayList<Contact>()
Send your list to your AsyncTask
将列表发送到AsyncTask
#5
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
您可以这样使用,它可以轻松地将值存储到Array并获取值
#1
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:
并传递给您的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);
and AsyncTask class:
和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;
}
}
#2
0
While declaring the AsyncTask in your class , declare it as follow :
在您的类中声明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;
}
}
The first parameter for the accepts the parameter you want to pass to the Asynctask created by you.
接受要传递给您创建的Asynctask的参数的第一个参数。
Also, call it as :
另外,将其命名为:
new TestAsyncTask().execute(myStringArray);
new TestAsyncTask()。execute(myStringArray);
#3
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
当你添加到模型对象时添加该对象tnto数组列表就像
savingcontacts.savingcontact(id, name, phone, email);
contactList.add(savingcontacts);
and then pass this arraylist in constructor of your asyntask class.
然后在你的asyntask类的构造函数中传递这个arraylist。
#4
0
Create a object "Contact" and fillt it with set and get method for ID, NAME, PHONE, and EMAIL.
创建一个对象“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;
}
[...]
}
Store all your contacts in a List:
将所有联系人存储在列表中:
List<Contact> contacts = new ArrayList<Contact>()
Send your list to your AsyncTask
将列表发送到AsyncTask
#5
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
您可以这样使用,它可以轻松地将值存储到Array并获取值