如何将联系人姓名和号码发送到MySQL数据库?

时间:2017-02-14 11:43:40

标签: android mysql android-intent android-volley

我想存储联系人姓名&通过PHP编号到MySQL。问题是使用空值插入的数据。代码是否正确? 主要Activity.java

public class Activity extends NavigationActivity {

    TextInputEditText name1,mobile1;

    private static final String TAG = Activity.class.getSimpleName();
    private static final int REQUEST_CODE_PICK_CONTACTS = 1;
    private Uri uriContact;
    private String contactID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offers);

        name1 = (TextInputEditText) findViewById(R.id.reference_new_connection_name_1);
        mobile1 = (TextInputEditText) findViewById(R.id.reference_new_connection_mobile_1);

        name1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                {
                    name1.setText("");
                    mobile1.setText("");
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent,PICK_CONTACT);
                }
            }
        });

        //This is a Button
    public void sendReference(View view) {

        sendContacts(retrieveContactName(),retrieveContactNumber());
        sendReference();

    }

    public void sendContacts(final String name, final String mobile)
    {
        final ProgressDialog progressDialog = new MyCustomProgressDialog(Activity.this);
        progressDialog.setCancelable(false);
        progressDialog.show();

        if (ConnectivityReceiver.isConnected()) {
            deleteCache(Activity.this);

            StringRequest login_request = new StringRequest(Request.Method.POST, Config.SEND_REFERENCE_URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.e("Response", response);
                    progressDialog.dismiss();
                }
            },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            progressDialog.dismiss();
                            if (error instanceof NoConnectionError) {
                                noConnection();
                            } else {
                                Log.e("Error",error.toString());
                            }
                        }
                    }){
                @Override
                protected Map<String,String> getParams(){
                    Map<String,String> params = new HashMap<>();
                    params.put("user_id",id);
                    params.put("Name",name);
                    params.put("Mobile",mobile);
                    return params;
                }

            };

            RequestQueue login = Volley.newRequestQueue(Activity.this);
            login.add(login_request);
        }
        else
        {
            noConnection();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
            Log.d(TAG, "Response: " + data.toString());
            uriContact = data.getData();

            retrieveContactName();
            retrieveContactNumber();

            name1.setText(retrieveContactName());
            mobile1.setText(retrieveContactNumber());

            name1.setEnabled(false);
            mobile1.setEnabled(false);
        }
    }

    private String retrieveContactNumber() {

        String contactNumber = null;

        // getting contacts ID
        Cursor cursorID = getContentResolver().query(uriContact,
                new String[]{ContactsContract.Contacts._ID},
                null, null, null);

        if (cursorID.moveToFirst()) {

            contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
        }

        cursorID.close();
        Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                        ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

                new String[]{contactID},
                null);

        if (cursorPhone.moveToFirst()) {
            contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
        cursorPhone.close();
        return contactNumber;
    }

    private String  retrieveContactName() {

        String contactName = null;

        Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);

        if (cursor.moveToFirst()) {

            contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }

        cursor.close();
        return contactName;
    }


    public void sendReference()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Reference Sent..")
                .setMessage("Thank You..")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent intent = new Intent(Activity.this,SecondActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        finish();
                        startActivity(intent);
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

}

3 个答案:

答案 0 :(得分:1)

此方法有一个大问题…… 对于每个上传到服务器的联系人,都会在此处生成请求。

这可能会对服务器造成不必要的流量

相反,我们可以使用json数组:

代码:

private fun getContacts(): JsonArray {

    val resolver: ContentResolver = contentResolver
    val cursor = resolver.query(
        ContactsContract.Contacts.CONTENT_URI, null, null, null,
        null
    )
    val mainJsonArray: JsonArray = JsonArray()
    if (cursor!!.count > 0) {
        while (cursor.moveToNext()) {
            val personJsonObj: JsonObject = JsonObject()
            val id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
            val name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
            //val phoneNumber = (cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER) )).toInt()
            personJsonObj.addProperty("NAME", name.replace("\\", "\\\\").replace("'", "\\'").replace("\"", "\\\""))

            val orgCursor = getContentResolver().query(
                ContactsContract.Data.CONTENT_URI, null,
                ContactsContract.Data.CONTACT_ID + "=?", arrayOf(id), null
            )

            val phoneJsonArray = JsonArray()
            val emailJsonArray = JsonArray()

            if (orgCursor!!.count > 0) {
                while (orgCursor.moveToNext()) {
                    if (orgCursor!!.getString(orgCursor.getColumnIndex(ContactsContract.Data.MIMETYPE)).equals(
                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE
                        )
                    ) {
                        val companyName = orgCursor.getString(orgCursor.getColumnIndex(ContactsContract.Data.DATA1))
                        val designation = orgCursor.getString(orgCursor.getColumnIndex(ContactsContract.Data.DATA4))
                        personJsonObj.addProperty(
                            "ORGANIZATION",
                            companyName.replace("\\", "\\\\").replace("'", "\\'").replace("\"", "\\\"")
                        )
                        personJsonObj.addProperty(
                            "DESIGNATION",
                            designation.replace("\\", "\\\\").replace("'", "\\'").replace("\"", "\\\"")
                        )

                    } else if (orgCursor!!.getString(orgCursor.getColumnIndex(ContactsContract.Data.MIMETYPE)).equals(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
                        )
                    ) {
                        val phoneNum = orgCursor.getString(orgCursor.getColumnIndex(ContactsContract.Data.DATA1))
                        phoneJsonArray.add(phoneNum.replace(" ", "").replace("-", ""))
                    } else if (orgCursor!!.getString(orgCursor.getColumnIndex(ContactsContract.Data.MIMETYPE)).equals(
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
                        )
                    ) {
                        val emailAddr = orgCursor.getString(orgCursor.getColumnIndex(ContactsContract.Data.DATA1))
                        emailJsonArray.add(emailAddr.replace(" ", ""))
                    }
                }
            }
            orgCursor.close()
            personJsonObj.add("EMAIL_LIST", emailJsonArray)
            personJsonObj.add("PHONE_NUMBERS", phoneJsonArray)
            mainJsonArray.add(personJsonObj)
        }

    }
    cursor.close()
    return mainJsonArray
}

生成json数组:

[{
        "NAME": "Test User Test User Last Name",
        "ORGANIZATION": "Some Company",
        "DESIGNATION": "Associate",
        "EMAIL_LIST": ["testuser@organiztion.com", "testuser1@org.com"],
        "PHONE_NUMBERS": ["123456789", "9808776"]
    }, {
        "NAME": "User One",
        "ORGANIZATION": "Test Company",
        "DESIGNATION": "Owner",
        "EMAIL_LIST": ["abc1@test.com", "abc2@test.com", "abc3@test.com", "abc4@test.com"],
        "PHONE_NUMBERS": ["7777", "8888", "9999"]
    }]

答案 1 :(得分:0)

我非常抱歉伙计们......我浪费了你的黄金时间..最后我得到了答案,...... Php开发者犯了一个错误..他改变了我发送的params值... Harvey Fletcher是正确的,...谢谢你的回答... ..

答案 2 :(得分:0)

列类型可以设置为int,这意味着0将从头开始删除。