Мне нужна ваша любезная поддержка …. Я разрабатываю Android-приложение, которое хранит контакты пользователей на веб-сервере.
Когда я пытаюсь загрузить контакты со своего телефона на свой сервер через php; он загружает некоторые из моих контактов должным образом (почти 250 контактов), но после этого он дублирует остальные с одной контактной информацией (общее количество контактов в моем телефоне 1117)увидеть изображение.Это код Android, который я использовал:
public class AllContacts extends Activity {
// To get the logged in user id from sqlite databse
private SQLiteHandler db;
int i =0;Cursor phones, email;
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_list_item);TextView txt = (TextView) findViewById(R.id.text1);
//Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
final String[] projection = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, selection + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1", null, sortOrder);
txt.setText("Total: " + phones.getCount() + " contacts");
phones.moveToFirst();
// Iterate every contact in the phone}// submitContacts method is executed when a backup button is pressed
public void submitContacts(View arg0) {
/* Start an activity for result with request code 1
* LoginActivity is started to check whether the user is logged in or not
* if the user is logged in LoginActivity will send a result code to AllContacts activity
*/
if(isNetworkAvailable()){
Intent intent=new Intent(AllContacts.this,LoginActivity.class);
startActivityForResult(intent, 1);
}
else{
makeText(AllContacts.this, "You need internet access to run this application",
LENGTH_LONG).show();
Log.v("Home", "############################You are not online!!!!");
}}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 1
if(requestCode==1) {
if (resultCode == Activity.RESULT_OK) {
//String result = data.getStringExtra("result");
/**
* Checks if the device has Internet connection.
*
* @return <code>true</code> if the phone is connected to the Internet.
*/if(isNetworkAvailable()){
InsertData task1 = new InsertData();
task1.execute(new String[]{"http://172.22.68.58:80/norton2/insert.php"});
//Intent in = new Intent(this, AllContacts.class); // if not working use new Intent(this, MainActivity.class)
//startActivity(in);
}
else{
makeText(AllContacts.this, "You need internet access to run this application",
LENGTH_LONG).show();
Log.v("Home", "############################You are not online!!!!");
}}
}
}
private class InsertData extends AsyncTask<String, Integer, Boolean> {
ProgressDialog dialog = new ProgressDialog(AllContacts.this);
private ProgressBar progressBar;
private String result;
@Override
protected void onPreExecute() {
progressBar = (ProgressBar)findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
// dialog.setMessage("Backing up your Data...");
//dialog.show();
}
@Override
protected Boolean doInBackground(String... urls) {db = new SQLiteHandler(getApplicationContext());
if (phones != null && phones.moveToFirst()) {
int total = phones.getCount();
Log.e("Uploaded count", "" + phones.getCount());
for (String url1 : urls) {
for (; i < phones.getCount(); i++){
try {
HashMap<String, String> user = db.getUserDetails();
String user_id = user.get("uid");
pairs.add(new BasicNameValuePair("userId",user_id));
pairs.add(new BasicNameValuePair("txtName", phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))));
pairs.add(new BasicNameValuePair("txtTel", phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
pairs.add(new BasicNameValuePair("txtMajor", phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID))));
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url1);
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);} catch (ClientProtocolException e) {
makeText(AllContacts.this, e.toString(), LENGTH_LONG).show();
return false;
} catch (IOException e) {
makeText(AllContacts.this, e.toString(), LENGTH_LONG).show();
return false;
}
phones.moveToNext();
Log.e("Uploaded contact count", "" + i);
int progress = ((i+1) * 100) / total;
publishProgress(progress);
Log.v("Home", "************************Progress "+progress);
}
}
}
return true;
}
@Override
protected void onProgressUpdate(Integer... progress) {
TextView txt = (TextView) findViewById(R.id.text1);
txt.setText("Backup percentage: " + progress[0]+"%");
progressBar.setProgress(progress[0]);
}
protected void onPostExecute (Boolean result){
if (result == true) {
progressBar.setVisibility(View.GONE);
makeText(AllContacts.this, "Backup Successful!", LENGTH_LONG).show();
} else {
makeText(AllContacts.this, "Error", LENGTH_LONG).show();
}
dialog.dismiss();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
Я думаю, что вы должны взглянуть на Жизненный цикл деятельности так что вы можете понять, как вызывается метод onCreate ().
Других решений пока нет …