发送Android的ArrayList的内容到PHP内容、Android、ArrayList、PHP

2023-09-03 21:00:46 作者:乱世巨星

我的工作作为一个PHP开发人员(中级),做练习一些Android的东西在家里。

I am working as a PHP developer (intermediate level) and do practice some android stuff at home.

我已经创建和数组列表,它会取到一个SQLite数据库在我的Andr​​oid应用程序和填充一个ListView。现在,我想采取一个级别上的。

I have created and array list which will fetch into an sqlite db inside my Android app and populate a ListView. Now I am trying to take that one level further.

我想这个数组列表内容发送到我的PHP服务器,我可以给存储到MySQL的数据,并获取回我的应用程序。

I want to send that array list content to my PHP server where I can store the data given into mysql and fetch back to my app.

我将如何去实现呢?

推荐答案

对于您有权发布数据的PHP服务器上,然后获取这些数据,并存储到数据库中。

For that you have to post your data on php server, then fetch that data and store into your database .

下面我附上一份发送给服务器并得到响应的JSON数据的一个例子。

Here i attach one example which send data on server and getting response in json .

                    HttpPost postMethod = new HttpPost("Your Url");
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();


                    // test is a one array list

                    for(int i=0;i<test.size();i++)
                    {
                        nameValuePairs.add(new BasicNameValuePair("sample[]", Integer.toString(test.get(i))));
                    }

                    postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    DefaultHttpClient hc = new DefaultHttpClient();

                    HttpResponse response = hc.execute(postMethod);
                    HttpEntity entity = response.getEntity();

                    // If the response does not enclose an entity, there is no need
                    // to worry about connection release

                    if (entity != null) 
                    {
                        InputStream inStream = entity.getContent();
                        result= convertStreamToString(inStream);
                        jsonObject = new JSONObject(result);
                        responseHandler.sendEmptyMessage(0);
                    }
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }.start();

下面示例[]是我数组赋值送价值在服务器领域。从服务器端,您必须获取样本[]字段。

Here sample[] is a field in which i assign array value to send on server . From server side you have to fetch the sample[] field .

public static String convertStreamToString(InputStream is)
{
   BufferedReader reader = new BufferedReader(new InputStreamReader(is));
   StringBuilder sb = new StringBuilder();

   String line = null;
   try 
   {
       while ((line = reader.readLine()) != null) 
       {
           sb.append(line + "\n");
       }
   } 
   catch (IOException e) 
   {
       e.printStackTrace();
   } 
   finally 
   {
       try 
       {
           is.close();
       } 
       catch (IOException e) 
       {
           e.printStackTrace();
       }
   }
   return sb.toString();

}