Skip to content Skip to sidebar Skip to footer

Sending Arraylist From Android To Php Script Using Json

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. What I Have Done Successfully I have Succe

Solution 1:

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

ArrayList<String> contact = newArrayList<String>();

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

JSONObjectJSONcontacts = newJSONObject();

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 objectfor (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()

JSONObjectEverythingJSON = newJSONObject();

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:

newAsyncTask() {
    //String responseBody = "";@SuppressWarnings("unused")
    protectedvoidonPostExecute(String msg) {
        //Not Needed
    }

    protectedObjectdoInBackground(Object... params) {
        //Create Array of Post VariabelsArrayList<NameValuePair> postVars = newArrayList<NameValuePair>();

        //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(newBasicNameValuePair("JSON", EverythingJSON.toString());

        //Declare and Initialize Http Clients and Http PostsHttpClient httpclient = newDefaultHttpClient();
        HttpPost httppost = newHttpPost(Config.OnlineAPI);

        //Format it to be senttry {
            httppost.setEntity(newUrlEncodedFormEntity(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... ");
        }
        returnnull;
    }
}.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 "<br>------" . $key . " => " . $value;
}

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

Solution 2:

You cant send Arraylist to server,its an object. The best way to solve your problem is user JSON , you need to do something like that -

 ArrayList<String> Questions=  newArrayList<String>();
 ArrayList<String> A1=  newArrayList<String>();
 ArrayList<String> A2=  newArrayList<String>();
 ArrayList<String> A3=  newArrayList<String>();
 ArrayList<String> A4=  newArrayList<String>();


 JsonArray jArr1= newJsonArray();
 for(String data:A1)
 {
   jArr1.add(data);
 }
  JsonArray jArr2= newJsonArray();
 for(String data:A2)
 {
   jArr2.add(data);
 }
 //convert each array list to jsonarrayJsonArrayjArraySet=newJsonArray();
  jArraySet.add(jArr1);
  jArraySet.add(jArr2);

 //add each json array to jArraySet// then send the data via HttpClienthttpclient=newDefaultHttpClient();
   ArrayList<NameValuePair> nameValuePairs = newArrayList<NameValuePair>();                   
    // put the values of id and name in that variable
   nameValuePairs.add(newBasicNameValuePair("all_arraylist",jArraySet.toString()));
   HttpPosthttppost=newHttpPost(url);
   httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs));
   HttpResponseresponse= httpclient.execute(httppost); 
   HttpEntityentity= response.getEntity();

note: dont forget to do it in asynctask

in php section ,do the following

<?php$all_arraylist = $_POST['all_arraylist'];
$all_arraylist= json_decode($all_arraylist,TRUE); //this will give you an decoded array 

print_r($all_arraylist); // display the array// after seeing the array , i hope you will understand how to process it.?>

Solution 3:

Very simple. you should parse your JSON in php and get array of objects that you have sent. Here is solution

$JSON_Received = $_POST["json"];
 $obj = json_decode($JSON_Received, true);
  $array_1st_name = $obj[0];
  $array_2nd_name = $obj[1];

and so on you will get all array of object.

Post a Comment for "Sending Arraylist From Android To Php Script Using Json"