为什么我的HashMap中的值为null?

时间:2017-04-22 22:47:42

标签: java hashmap android-volley

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

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

但是稍后在Hashmap中使用我的代码System.out.println("contact is : " + phonenumber);,我会进入logcat:

contact is : null

我想将所有电话号码发布到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 个答案:

答案 0 :(得分:1)

  

我进入了logcat:

O(4n)

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

A

根据代码逻辑

contact is : null 时它也将继续为空
  

// VALUE,phonenumber,形式为“12345678”

好的,然后将其设置为,而不是根本不设置

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

注意,这是如何正确迭代Cursor

alContacts.isEmpty()

或者只是

String phoneNo

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

答案 1 :(得分:0)

感谢上面的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);


    }
}