-1

Why is phonenumber in my HashMap giving me a null value? The idea is that I loop through all contacts on my phone. In my try - catch statement, which is working fine, I see all my contacts in logcat with :

System.out.println("JSON: " + phonenumber);

But with my code System.out.println("contact is : " + phonenumber); later on in the Hashmap I get in logcat :

contact is : null

I want to post all the phone numbers to a MySql database, can you tell me what I am doing wrong ?

public class MainActivity extends AppCompatActivity {

    // this is the php file we are contacting with Volley
    private static final String CHECKPHONENUMBER_URL = "http://www.sitetocheckwithVolley.com/filetocheckwithVolley.php";

    //we are posting phoneNo, which in PHP is phonenumber
    public static final String KEY_PHONENUMBER = "phonenumber";

    //alContacts is a list of all the phone numbers
    public static final ArrayList<String> alContacts = new ArrayList<String>();

    Button buttonCheck;
    TextView textView;

    String phonenumber;

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

        buttonCheck = (Button) findViewById(R.id.buttonCheck);
        textView = (TextView) findViewById(R.id.textView);



        //get the names and phone numbers of all contacts in phone book
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {


                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));

                if (cur.getInt(cur.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));

                        alContacts.add(phoneNo);
                        // break;
                    }
                    pCur.close();

                }
            }
        }

        buttonCheck.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                CheckifUserisContact();
            }
        });

    }



    private void CheckifUserisContact() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, CHECKPHONENUMBER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONObject jsonObjectContact = new JSONObject();
                            //put all phone contacts into jsonObjectContact
                            for (int i = 0; i < alContacts.size(); i++)
                            {
                         // jsonObjectContact will be of the form {"phone_number":"123456789"}
                                jsonObjectContact.put("phone_number", alContacts.get(i));

                                //make a new string phonenumber for each JSON contact
                                phonenumber = jsonObjectContact.getString("phone_number");
                                textView.append(phonenumber + " \n");

                                System.out.println("JSON: " + phonenumber);
                            }

                        } catch (final JSONException e) {
                            Log.e("FAILED", "Json parsing error: " + e.getMessage());
                        } }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();

                    }

                }) {

         @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
             //The KEY, KEY_PHONENUMBER = "phonenumber" . In PHP we will have $_POST["phonenumber"]
             //The VALUE, phonenumber, will be of the form "12345678"
                params.put(KEY_PHONENUMBER,phonenumber);
                System.out.println("contact is : " + phonenumber);
                return params;


        }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }
CHarris
  • 2,693
  • 8
  • 45
  • 71
  • Hashmap.get returns null when the key is doesn't exist. Or you explicitly put null object – OneCricketeer Apr 22 '17 at 22:52
  • If you're trying to POST JSON, you wouldn't you StringRequest – OneCricketeer Apr 22 '17 at 22:53
  • The key is KEY_PHONENUMBER. – CHarris Apr 22 '17 at 22:58
  • That's great, but you're printing a null string. The same null string is in the Hashmap. You can even print before the StringRequest. The variable will be null there too – OneCricketeer Apr 22 '17 at 23:02
  • I'm honesty not sure why you're trying to POST a single string instead of the Arraylist – OneCricketeer Apr 22 '17 at 23:07
  • I'm trying to post all numbers as JSON objects - all the phone contacts - that is, as per the code in my 'try statement' . But starting by learning to do just a single string first. If you know an easy way how to modify my code so it does all the contacts I'd be delighted to hear it. – CHarris Apr 22 '17 at 23:11
  • In fact, I'm quite sure you can POST JSON using StringRequest :http://stackoverflow.com/questions/29442977/volley-jsonobjectrequest-post-parameters-no-longer-work – CHarris Apr 23 '17 at 00:23
  • Sure, you can, but it's a use case that JSONArrayRequest was made for. – OneCricketeer Apr 23 '17 at 04:09

2 Answers2

1

I get in logcat :

  contact is : null

Because it's never assigned between onCreate and the getParams() methods

String phonenumber;  // null until onResponse

It'll also continue to be null while alContacts.isEmpty() according to the logic of the code

//The VALUE, phonenumber, will be of the form "12345678"

Okay, then set it to that instead of not setting it at all

You seem to be using a String phoneNo... Is that what you want instead? Then don't make a secondary String variable and instead assign the field. However, then you only are posting the last string of the contacts, not the whole list


Note, this is how to correctly iterate a Cursor

   if (cur.moveToFirst()) {
        while (cur.moveToNext()) {

Or simply

for (cur.moveToFirst(); cur.moveToNext(); ) {

And, as pointed out, you're collecting a list, but only putting in one element into the parameters. Did you want to post a JSONArray?

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Thanks for the Cursor iteration tip. What's wrong with 'cur.getCount()>0' ? I'm guessing it's because if the user has no contacts it causes problems. – CHarris Apr 22 '17 at 23:14
  • I was under the impression that it advances the cursor so there's nothing to iterate – OneCricketeer Apr 23 '17 at 04:06
0

Thanks to cricket_007 answer above, I modified my code like so :

public class MainActivity extends AppCompatActivity {

    // this is the php file we are contacting with Volley
    private static final String CHECKPHONENUMBER_URL = "http://www.thesitetocheck.com/thefiletocheck.php";

    //we are posting phoneNo, which in PHP is phonenumber
    public static final String KEY_PHONENUMBER = "phonenumber";

    //alContacts is a list of all the phone numbers
    public static final ArrayList<String> alContacts = new ArrayList<String>();

    JSONObject jsonObjectContact = new JSONObject();

    Button buttonCheck;
    TextView textView;
    String phoneNo;

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

        buttonCheck = (Button) findViewById(R.id.buttonCheck);
        textView = (TextView) findViewById(R.id.textView);



        //get the names and phone numbers of all contacts in phone book
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

        if (cur.moveToFirst()) {
            while (cur.moveToNext()) {


                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));

                if (cur.getInt(cur.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        phoneNo = pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));

                        alContacts.add(phoneNo);
                        // break;
                    }
                    pCur.close();

                }
            }
        }

        buttonCheck.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                try {


                    //put all phone contacts into jsonObjectContact
                    for (int i = 0; i < alContacts.size(); i++)
                    {
                        // jsonObjectContact will be of the form {"phone_number":"123456789"}
                        jsonObjectContact.put("phone_number", alContacts.get(i));

                        textView.append(jsonObjectContact + " \n");

                        System.out.println("JSON: " + jsonObjectContact);
                    }

                } catch (final JSONException e) {
                    Log.e("FAILED", "Json parsing error: " + e.getMessage());
                }

                CheckifUserisContact();
            }
        });

    }



    private void CheckifUserisContact() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, CHECKPHONENUMBER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();

                    }

                }) {

         @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
             //The KEY, KEY_PHONENUMBER = "phonenumber" . In PHP we will have $_POST["phonenumber"]
             //The VALUE, phonenumber, will be of the form "12345678"
                params.put(KEY_PHONENUMBER,jsonObjectContact.toString());
                System.out.println("contact is : " + jsonObjectContact);
                return params;


        }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }
}
CHarris
  • 2,693
  • 8
  • 45
  • 71
  • You're still only putting one string, not "all" like your comment says since JSON can't have duplicate keys. Try posting a JSONArray instead – OneCricketeer Apr 23 '17 at 04:12
  • In my'for loop' for textView.append and System.out.println for jsonObjectContact I get all the entries in my phone in the format : {phone_number : 12345678} , {phone_number : 23456789}, etc.....all JSON Objects. Are you saying it is not possible to post these to MySQL db the way I am doing it ? – CHarris Apr 23 '17 at 07:18
  • I'm sure you could do that, but using a TextView (or any UI component) as a temporary "container" for your data usually is the wrong idea. Because you're still sending a comma delimited string to PHP, not a valid JSON object – OneCricketeer Apr 23 '17 at 11:49