【问题标题】:Sending ArrayList from Android to PHP script using JSON使用 JSON 将 ArrayList 从 Android 发送到 PHP 脚本
【发布时间】:2014-08-30 12:08:22
【问题描述】:

场景是什么

我想将多个 ArrayList(通常为 5 个)从 android 发送到服务器,并希望将其插入 mysql 数据库。

我的成功之处

我已经使用 JSON 成功地将单个值和多个值从 Android 发送到 PHP 脚本

我已经使用 JSON 从 mysql 数据库到 android 接收到单个和多个记录

这是从服务器插入和获取值的代码

 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;


     }

和 TeacherAuthen.php 脚本

<?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);
?> 

我被困在哪里

我不知道如何将 ArrayList 从 android 发送到 PHP 脚本。

例如,我想将这些数组列表发送到 php 脚本 =

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

然后在我想像这样插入的 PHP 脚本中

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

如果我什至能够发送一个数组列表,那么我想我可以找到一种方法来完成上述操作

感谢您的时间

【问题讨论】:

  • 为什么不是里面有 5 个 json 数组的 Json 对象?
  • 你的意思是 nameValuePairs.add(new BasicNameValuePair("ques",Questions)) ?
  • JsonObject json = new JsonObject() Json.putJsonArray 等。您可能还想考虑 Json 解析

标签: android mysql json arraylist


【解决方案1】:

这是您的数组:您可以根据示例中的需要创建更多。

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

然后,创建一个 JSONObject 类型的 JSONcontacts 变量来将此数组存储在此对象中

JSONObject JSONcontacts = new JSONObject();

现在,遍历该联系人数组中的所有元素并将其存储在 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();
    }
}

假设您创建了许多数组,您可能已经完成了,现在您必须将它们全部放入 1 个 JSON 中。所以创建一个 JSONObject() 类型的 EverythingJSON 变量

JSONObject EverythingJSON = new JSONObject();

现在将你所有的联系人数组和其他数组放入其中,就像上面描述的那样循环遍历它们:

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

现在这是你的 AsynchTask 将它们发送到你的 PHP 服务器:

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);

现在在 PHP 服务器端,您可以像这样循环遍历这个 JSON: 首先,从 POST 获取 JSON 并将其存储在 var 中:

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

现在从 JSON 中解码:

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

这是遍历联系人数组并从中获取 Key 和 Value 的循环:

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

您可以对已发送的其他数组重复此循环:) 祝您好运!

【讨论】:

  • foreach ($obj['ques'] as $key => $value){// do somthing}
  • 获取错误为 foreach 提供的无效参数 .. 并且在我使用的 java 中
  • 尝试 { JSONcontacts.put("ques", questions); } catch (JSONException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }
  • 当我使用 foreach ($obj as $value){} .. 那么它是正确的并且正在插入数据库中。
  • 我认为 foreach ($obj['contact'] as $key => $value) 将适合当我在 nameValuePairs 中传递 EverythingJSON 时.. 对吗?
【解决方案2】:

您不能将 Arraylist 发送到服务器,它是一个对象。解决您的问题的最佳方法是 用户 JSON ,你需要做类似的事情 -

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

注意:不要忘记在 asynctask 中进行操作

在 php 部分,执行以下操作

<?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.
?>

【讨论】:

  • 好的,我会试试这个。你能给我一些关于这段代码的 php 代码的提示吗……我怎样才能在 php 脚本中检索这些?
【解决方案3】:

非常简单。您应该在 php 中解析 JSON 并获取已发送的对象数组。这是解决方案

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

以此类推,您将获得所有对象数组。

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 2013-11-03
    • 1970-01-01
    • 2018-02-08
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    相关资源
    最近更新 更多