2011-03-12 82 views
1

我作爲一名PHP開發人員(中級)工作,並在家中練習一些安卓系統的東西。將Android ArrayList的內容發送到PHP

我已經創建和數組列表,它將獲取到我的Android應用程序中的sqlite數據庫並填充ListView。現在我正試圖進一步提高這個水平。

我想將該數組列表內容發送到我的PHP服務器,我可以將給定的數據存儲到mysql中並將數據提取回我的應用程序。

我該如何去做到這一點?

回答

1

您可以使用JSON或XML從Android發送數據到php服務器。 在PHP方面,您所需要的只是內置的json_decode,它將反序列化您的json並返回一個對象或關聯數組。

+1

正是我要說的話。我發現Android OS中包含的JSON或XML支持非常好,要麼會爲你工作,並允許溝通。請記住,您需要獲得訪問ApplicationManifest.xml中的網絡操作的權限,並且您需要通過默認的http對象發送JSON或XML。 – 2011-03-12 07:06:17

1

爲此,您必須在php服務器上發佈數據,然後獲取該數據並存儲到數據庫中。

在這裏我附上一個例子,它發送服務器上的數據並獲得響應在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(); 

這裏樣品[]是其中i的分配數組值上的服務器發送的字段。從服務器端您必須獲取示例[]字段。


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

}

+0

我有多個arraylist,那麼我怎麼能在列表這個所有值? – PankajAndroid 2013-11-18 05:39:22