为什么我的HashMap中的空值?

时间:2022-09-25 14:51:54

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 :

为什么我的HashMap中的phonenumber给我一个空值?我的想法是我遍历手机上的所有联系人。在我的try-catch语句中,工作正常,我在logcat中看到了所有联系人:

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

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

但是我的代码是System.out.println(“contact is:”+ phonenumber);后来在Hashmap中我得到了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 ?

我想将所有电话号码发布到MySql数据库,你能告诉我我做错了什么吗?

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);


    }

2 个解决方案

#1


1  

I get in logcat :

我进入logcat:

  contact is : null

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

因为它从未在onCreate和getParams()方法之间分配

String phonenumber;  // null until onResponse

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

根据代码的逻辑,它也将继续为null,而alContacts.isEmpty()

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

// VALUE,phonenumber,形式为“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

你似乎正在使用一个String phoneNo ...这是你想要的吗?然后不要创建辅助字符串变量,而是分配字段。但是,您只会发布联系人的最后一个字符串,而不是整个列表


Note, this is how to correctly iterate a Cursor

注意,这是如何正确迭代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?

并且,正如所指出的,您正在收集一个列表,但只在参数中加入一个元素。你想发布一个JSONArray吗?

#2


0  

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

感谢上面的cricket_007回答,我修改了我的代码:

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);


    }
}

#1


1  

I get in logcat :

我进入logcat:

  contact is : null

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

因为它从未在onCreate和getParams()方法之间分配

String phonenumber;  // null until onResponse

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

根据代码的逻辑,它也将继续为null,而alContacts.isEmpty()

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

// VALUE,phonenumber,形式为“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

你似乎正在使用一个String phoneNo ...这是你想要的吗?然后不要创建辅助字符串变量,而是分配字段。但是,您只会发布联系人的最后一个字符串,而不是整个列表


Note, this is how to correctly iterate a Cursor

注意,这是如何正确迭代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?

并且,正如所指出的,您正在收集一个列表,但只在参数中加入一个元素。你想发布一个JSONArray吗?

#2


0  

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

感谢上面的cricket_007回答,我修改了我的代码:

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);


    }
}