0

Actually, I want to send contacts of user phone to server in form of json. Somewhere i read that, it can be done through GSON library, but I am unable to get the exact code.Phone Number and contact name are in the form of string . I had tried it by making 2 classes.

One is the Main Class, in which I am fetching contacts

public class Access_contacts extends AppCompatActivity {


    ArrayList<Contact_Pojo> arrayList;
    private static final int PERMISSION_REQUEST_CONTACT =123 ;
    private static final int PICK_CONTACT =147 ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_access_contacts);
        arrayList= new ArrayList<Contact_Pojo>();

        askForContactPermission();

        Gson gson = new Gson();
        Type type = new TypeToken<List<Contact_Pojo>>() {}.getType();
        String json = gson.toJson(arrayList, type);

        ArrayList<Contact_Pojo> fromJson = gson.fromJson(json, type);

        for (Contact_Pojo task : fromJson) {
            System.out.println(task);
        }



    }

    private void gettingPhoneContacts() {
        ContentResolver cr = getApplicationContext().getContentResolver();
        // Read Contacts
        Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,     new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,       ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.RawContacts.ACCOUNT_TYPE },     ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' ",
                null, null);
        if (c.getCount() <= 0) {    Toast.makeText(getApplicationContext(), "No Phone Contact Found..!",
                Toast.LENGTH_SHORT).show();   }
                else {
            while (c.moveToNext()) {
                String Phone_number = c       .getString(c         .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));          //Phone number
            String name = c       .getString(c         .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


                    arrayList.add(new Contact_Pojo(name,Phone_number));


                Log.d("contactsss",Phone_number+ " "+name);
            //Name of contact
        }
        for(int i=0;i<arrayList.size();i++)
        {
        Log.d("jopo",""+arrayList.get(i));
        }

    }}

    private void askForContactPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(Access_contacts.this,Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {

                // Should we show an explanation?
                if (ActivityCompat.shouldShowRequestPermissionRationale(Access_contacts.this,
                        Manifest.permission.READ_CONTACTS)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Access_contacts.this);
                    builder.setTitle("Contacts access needed");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setMessage("please confirm Contacts access");//TODO put real question
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @TargetApi(Build.VERSION_CODES.M)
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            requestPermissions(
                                    new String[]
                                            {Manifest.permission.READ_CONTACTS}
                                    , PERMISSION_REQUEST_CONTACT);
                        }
                    });
                    builder.show();
                    // Show an expanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                } else {

                    // No explanation needed, we can request the permission.

                    ActivityCompat.requestPermissions(Access_contacts.this,
                            new String[]{Manifest.permission.READ_CONTACTS},
                            PERMISSION_REQUEST_CONTACT);

                    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                    // app-defined int constant. The callback method gets the
                    // result of the request.
                }
            }else{
                getContact();
            }
        }
        else{
            getContact();
        }
    }

    private void getContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, PICK_CONTACT);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CONTACT: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    gettingPhoneContacts();
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(this, "No Permission for Contacts", Toast.LENGTH_SHORT).show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
}

Other is POJO class, which is as follows :

public class Contact_Pojo {


    @Override
    public String toString() {
        return "Contact_Pojo [name=" + name + ", number=" + number + "  ]";
    }


    public Contact_Pojo(String name, String number) {
        this.name = name;
        this.number = number;

    }

    String name,number;;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }


}
1
  • 1 plenty of answers Commented May 23, 2018 at 7:05

2 Answers 2

1

Here is solution. You have to decide "What you need ?" JSONOject or JSONArray. Declare at top.

JSONObject mainObject = new JSONObject();
JSONArray jsonBody;

Now inside OnCreate

              jsonBody = new JSONArray();
                 try {
                    JSONObject object_1 = new JSONObject();
                    object_1.put("KEY_VALUE", KEY_PAIR);
                    object_1.put("KEY_VALUE", KEY_PAIR);
                    object_1.put("KEY_VALUE", KEY_PAIR);
                    object_1.put("KEY_VALUE", KEY_PAIR);
                    object_1.put("KEY_VALUE", KEY_PAIR_id);
                    jsonBody.put(0, object_1);
                    mainObject.put("data", jsonBody);
                  String data = mainObject.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }

Add your keys in place of KEY_VALUE and their values in KEY_PAIR.

If you need to send JSONArray pass jsonBody and if need JSONObject use mainObject.

Sign up to request clarification or add additional context in comments.

Comments

0

i think you should use JSONObject and JSONArray like:

JSONArray array = new JSONArray("Catalo");

        JSONObject contact = new JSONObject();
        contact.put("key", "value");
        contact.put("key", "value");
        ...
        array.put(contact);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.