3

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 Successfully send single value and Multiple Values from Android to PHP script using JSON

i have Received single and Multiple Records from mysql database to android using JSON

Here is the Code for inserting and getting value from server

 class TeacherLogin1 extends AsyncTask<Void, Void, Void> {

         String name,pass;
         Context contextt;
         int idofteach = 0;
         int codee = 0;

         TeacherLogin1(String pass1,String name1,Context context)
         {
             name = name1;
             pass = pass1;
             contextt  = context;
         }

         @Override
         protected void onPreExecute() {
         super.onPreExecute();
         }


         @Override
         protected Void doInBackground(Void... arg0) {
              codee = Authenticate(name,pass);

         return null;
         }

         @Override
         protected void onPostExecute(Void result) {
         super.onPostExecute(result);
         if(codee!=0)
         {
             Intent teachers = new Intent(context,TeachersView.class);
             teachers.putExtra("TID", codee);
             teachers.putExtra("TNAME", TeachName);
             teachers.putExtra("sub1", subj1);
             teachers.putExtra("sub2", subj2);
             teachers.putExtra("sub3", subj3);
             teachers.putExtra("sub4", subj4);
            startActivity(teachers);
         }
         else
             Toast.makeText(context, "Wrong Details", Toast.LENGTH_SHORT).show();
         codee = 0;
         }
         } 
     public int Authenticate(String name,String Pass)
     {

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

              // put the values of id and name in that variable
            nameValuePairs.add(new BasicNameValuePair("name",name));
            nameValuePairs.add(new BasicNameValuePair("pass",Pass));



                try
                {
                HttpClient httpclient = new DefaultHttpClient();
                 ScriptsFilePath a = new ScriptsFilePath();
                HttpPost httppost = new HttpPost(a.TeacherAuthen);

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost); 
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    Log.e("pass 1", "connection success ");
            }
                catch(Exception e)
            {
                    Log.e("Fail 1", e.toString());
            }     

                try
                {
                    BufferedReader reader = new BufferedReader
                    (new InputStreamReader(is,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null)
                {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                Log.e("pass 2", "connection success ");
            }
                catch(Exception e)
            {
                    Log.e("Fail 2", e.toString());
            }     



                      try {

                       JSONObject jsonResponse = new JSONObject(result);
                       if(jsonResponse != null)
                       {
                       JSONArray jsonMainNode = jsonResponse.optJSONArray("GetTeacher");

                       for (int i = 0; i < jsonMainNode.length(); i++) {
                        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                        code = jsonChildNode.optInt("ID");
                        TeachName= jsonChildNode.optString("Name");
                        subj1= jsonChildNode.optString("subject1");
                        subj2= jsonChildNode.optString("subject2");
                        subj3= jsonChildNode.optString("subject3");
                        subj4= jsonChildNode.optString("subject4");
                       }

                       }

                      } catch (JSONException e) {
                //     Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                //       Toast.LENGTH_SHORT).show();
                      }
                    return code;


     }

and the TeacherAuthen.php script

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
    $host="localhost";
    $uname="root";
    $pwd='';
    $db="examsystem";

    $con = mysql_connect($host,$uname,$pwd) or die("connection failed");
    mysql_select_db($db,$con) or die("db selection failed");

     if(isset($_REQUEST)){
    $name=$_REQUEST['name'];
    $pass=$_REQUEST['pass'];}

    $flag['code']=0;
    $name1['code1'] = "sdf";

$sql = "SELECT * FROM teachers WHERE Username ='$name' and Pass='$pass'";
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['GetTeacher'][]=$row;
}
}
echo json_encode($json);
mysql_close($con);
?> 

where i am stuck

I dont no how to send ArrayList from android to PHP Script.

For Example I want to send these arraylists to php script =

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

and then in the PHP script i want to insert like this

"INSERT INTO `Question` (`ID` ,`Question` ,`A1` ,`A2` ,`A3` , `A4` ) VALUES (NULL, '$Question', '$A1', '$A2', '$A3' ,'$A4'); "

if i am able to send even a single arrayList then i think i can make a way to do the above

and Thanks for you Time

Jamil
  • 5,457
  • 4
  • 26
  • 29

3 Answers3

12

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

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

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<NameValuePair> postVars = new ArrayList<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(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 "<br>------" . $key . " => " . $value;
}

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

Komal12
  • 3,340
  • 4
  • 16
  • 25
Dawid Czerwinski
  • 670
  • 5
  • 11
  • foreach ($obj['ques'] as $key => $value){// do somthing} – Jamil Aug 30 '14 at 13:38
  • getting error invalid argument supplied for foreach.. and in java i am using – Jamil Aug 30 '14 at 13:39
  • try { JSONcontacts.put("ques", questions); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } – Jamil Aug 30 '14 at 13:39
  • when i use foreach ($obj as $value){} .. then it is right and is inserting in database. – Jamil Aug 30 '14 at 13:45
  • i think foreach ($obj['contact'] as $key => $value) will be right for when i pass EverythingJSON in nameValuePairs.. am i right ? – Jamil Aug 30 '14 at 13:47
  • Yes, you must pass EverythingJSON as nameValuePair using POST method. Sorry but in my AsynchTak I forgot to change `postVars.add(new BasicNameValuePair("JSON", String.valueOf(JSON)));` to `postVars.add(new BasicNameValuePair("JSON", String.valueOf(EverythingJSON)));` But if you put `JSONcontacts.put("ques", questions);` then in foreach loop you should do: 'foreach ($obj['ques'] as $key => $value)' – Dawid Czerwinski Aug 30 '14 at 13:54
  • ok last question.. i have send EverythingJSON and it contains two JSON object like "contact" and "apple" and i have received output [contact,contact1,contact2,contact3] by using foreach ($obj['contact'] as $key => $value)... can i get a single value for example only "contact2" from this array of contact – Jamil Aug 30 '14 at 14:06
  • or maybe there is a way to break the string just like it is done in java.. please suggest me. – Jamil Aug 30 '14 at 14:10
  • i used $pieces = explode(",", $value); and $pieces[0] but for the first and last value is like "[contact" and "contact4]" rest of the middle is fine – Jamil Aug 30 '14 at 14:13
  • I am looking at it, maybe try [this-click_me](http://www.phpro.org/examples/Convert-Object-To-Array-With-PHP.html), once you convert Object into Array you will be able to refer to the element in the array using index e.g. contac[2] or contact[0]. I hope this will work. – Dawid Czerwinski Aug 30 '14 at 14:14
  • this is how i remove the '[' and ']' – Jamil Aug 30 '14 at 14:17
  • $pieces1 = str_replace("[","",$value); $pieces2 = str_replace("]","",$value); $pieces = explode(",", $pieces1); $pieces[0] will give 'contact' only now :D – Jamil Aug 30 '14 at 14:18
  • foreach ($obj['contact'] as $key => $value) { $flag['code'] = 1; $pieces1 = str_replace("[","",$value); $pieces2 = str_replace("]","",$pieces1); $pieces = explode(",", $pieces2); foreach ($pieces as $value1) { mysql_query("insert into question(`ID` ,`question`) values(NULL,'$value1')",$con); } } – Jamil Aug 30 '14 at 14:23
  • I'm glad it worked, well done haha :D And no problem, glad I could help. – Dawid Czerwinski Aug 30 '14 at 14:39
  • Another solution would be to use foreach loop: `$str_everything = ""; foreach ($obj['contact'] as $key => $value) { str_everything = str_everything . $key . " # " . $value . "$"; }` and then you could explode the string by the $ to get KEY and VALUE or by # to get each element individually. or combine them both. Look the [PHP_Explode](http://php.net/manual/en/function.explode.php) this might work and be less coding. – Dawid Czerwinski Aug 30 '14 at 14:44
  • can you help ? http://stackoverflow.com/questions/34507749/send-arraylist-from-android-to-php-mysql – John Joe Dec 29 '15 at 10:20
  • **ArrayList** is depreciated in API 22. Please update the answer. – Ramz Jan 27 '16 at 11:47
5

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=  new ArrayList<String>();
 ArrayList<String> A1=  new ArrayList<String>();
 ArrayList<String> A2=  new ArrayList<String>();
 ArrayList<String> A3=  new ArrayList<String>();
 ArrayList<String> A4=  new ArrayList<String>();


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

 //add each json array to jArraySet
 // then send the data via 
   HttpClient httpclient = new DefaultHttpClient();
   ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();                   
    // put the values of id and name in that variable
   nameValuePairs.add(new BasicNameValuePair("all_arraylist",jArraySet.toString()));
   HttpPost httppost = new HttpPost(url);
   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
   HttpResponse response = httpclient.execute(httppost); 
   HttpEntity entity = 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.
?>
  • ok i will try this. can you please give me some hint about php code for this code... how can i retrieve these in php script? – Jamil Aug 30 '14 at 12:34
0

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.