【问题标题】:How do I convert my Arraylist to JSON and Post it to MySQL?如何将我的 Arraylist 转换为 JSON 并将其发布到 MySQL?
【发布时间】:2017-04-19 17:09:13
【问题描述】:

我一直在尝试将我手机中的所有电话号码转换为 JSON 并在一篇文章中将它们上传到 mysql 数据库,你能帮忙吗?我现在专注于 Android 方面 - php 将在以后。

所以,我创建了一个包含所有数字的数组列表 - 当您单击 buttonCheck 按钮时,您可以在 logcat 中看到它们,但毕竟我已经阅读了方法 sizelength 仍然无法识别通过我的alContacts 数组。我相信这是我应该采取的转换为 JSON (?) 的轨道。这是我的代码:

public class MainActivity extends AppCompatActivity {

    // this is the php file name where to select from the database, the user's phone number
    private static final String CHECKPHONENUMBER_URL = "http://www.example.com/myfile.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;

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

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

        //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) {
                System.out.println("Print the contacts array : ");
                System.out.println(alContacts);

                 CheckifUserisContact();
            }
        });

    }


// send the numbers in one POST to the mySql db with Volley

    private void CheckifUserisContact() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, CHECKPHONENUMBER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.equals("failure")) {
                            Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(MainActivity.this, "succeeded", Toast.LENGTH_LONG).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();

                    }

                }) {

            //********* HAVING TROUBLE HERE *******************

          //  JSONObject jsonObject=new JSONObject();
            JSONArray jsonArray = new JSONArray();
          //  jsonObject.put("alContacts",jsonArray);
            //for(int i=0;i<=alContacts.size;i++){}

            //*****************************************************

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_PHONENUMBER, jsonArray.toString());
                return params;

            }

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


    }
}

【问题讨论】:

    标签: android json arraylist


    【解决方案1】:

    试试这个:

    //********* HAVING TROUBLE HERE *******************
    
    try {
            JSONObject dataToSend = new JSONObject();
    
            // contacts
            JSONArray jsonArrayContacts = new JSONArray();
    
            for (int i = 0; i < alContacts.size(); i++)
            {
                // contact
                JSONObject jsonObjectContact = new JSONObject();
                jsonObjectContact.put("phone_number", alContacts.get(i));
    
                // Add contact jsonObject to contacts jsonArray
                jsonArrayContacts.put(jsonObjectContact);
            }
    
            // Add contacts jsonArray to jsonObject
            dataToSend.put("contacts", jsonArrayContacts);
    
            Log.d("JSON", "JSON: " + dataToSend.toString());
    
        } catch (final JSONException e) {
            Log.e("FAILED", "Json parsing error: " + e.getMessage());
        }
    
    //*****************************************************
    

    这是输出的 JSON 格式:

        {
            "contacts":[
            {
                "phone_number":"019114-123456"
            },
            {
                "phone_number":"016174-123456"
            },
            {
                "phone_number":"012104-123456"
            }]
        }
    

    希望对你有帮助~

    【讨论】:

    • 事实上我认为你的代码块应该在我的'public void onResponse'部分,而不是'Response.ErrorListener'。现在很好用,谢谢!
    • 我很高兴 :).... 最佳实践是在发出字符串/JSONObject 请求之前构建 JSON。在您的 onResponse 中,如果您的 conatct JSON 数据成功发送到服务器,您将从服务器获取响应 JSON,
    猜你喜欢
    • 2018-02-04
    • 2020-04-30
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    相关资源
    最近更新 更多