Sending ArrayList from Android to PHP script using JSON

前端 未结 3 1315
轮回少年
轮回少年 2020-12-10 00:06

What is the Scenario

I want to send multiple ArrayList (usally 5) from android to the server and want to insert it into mysql database.

3条回答
  •  不知归路
    2020-12-10 00:52

    This is your Array: you can create more as required in your example.

    ArrayList contact = new ArrayList();
    

    Then, create a JSONcontacts variable of type JSONObject to store this array in this object

    JSONObject JSONcontacts = new JSONObject();
    

    Now, loop through all elements in that contact array and store it in the JSONcontacts

    //Loop through array of contacts and put them to a JSONcontact object
    for (int i = 0; i < contact.size(); i++) {
        try {
            JSONcontacts.put("Count:" + String.valueOf(i + 1), contact.get(i));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    

    Lets say you created many Arrays, which you probably have done, now you hvave to put them all into 1 JSON. So create a EverythingJSON variable of type JSONObject()

    JSONObject EverythingJSON = new JSONObject();
    

    and now put all your contact array and other arrays into it, right you loop through them as described above:

    EverythingJSON.put("contact", JSONcontacts);
    EverythingJSON.put("something", JSONsoemthing);
    EverythingJSON.put("else", JSONelse);
    

    now this is your AsynchTask to send them to your PHP server:

    new AsyncTask() {
        //String responseBody = "";
        @SuppressWarnings("unused")
        protected void onPostExecute(String msg) {
            //Not Needed
        }
    
        protected Object doInBackground(Object... params) {
            //Create Array of Post Variabels
            ArrayList postVars = new ArrayList();
    
            //Add a 1st Post Value called JSON with String value of JSON inside
            //This is first and last post value sent because server side will decode the JSON and get other vars from it.
            postVars.add(new BasicNameValuePair("JSON", EverythingJSON.toString());
    
            //Declare and Initialize Http Clients and Http Posts
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(Config.OnlineAPI);
    
            //Format it to be sent
            try {
                httppost.setEntity(new UrlEncodedFormEntity(postVars));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
    
            /* Send request and Get the Response Back */                    
            try {
                HttpResponse response = httpclient.execute(httppost);
                String responseBody = EntityUtils.toString(response.getEntity());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                Log.v("MAD", "Error sending... ");
            } catch (IOException e) {
                e.printStackTrace();
                Log.v("MAD", "Error sending... ");
            }
            return null;
        }
    }.execute(null, null, null);
    

    Now on the PHP server side, you can loop through this JSON as such: FIrst of all, get that JSON from POST and store it in a var:

    //Receive JSON
    $JSON_Received = $_POST["JSON"];
    

    Now decode it from JSON:

    //Decode Json
    $obj = json_decode($JSON_Received, true);
    

    And this is the loop to go through the array of contacts and get he Key and Value from it:

    foreach ($obj['contact'] as $key => $value) 
    {
        //echo "
    ------" . $key . " => " . $value; }

    you can repeat this loop for other Arrays you have sent :) Good Luck!

提交回复
热议问题