2013-09-06 1 views
0

나는 HTTP 응답을 사용하여 PHP 서버에서 데이터를 얻으려고 시도하지만, 여기에있는 하나의 문자열로 응답을 얻는 까다로운 일이 있습니다. 응답을 배열에 넣고 싶습니다. 응답에는 원래 MySQL에서 검색 한 많은 쿼리가 포함되어 있습니다. 어떤 도움을 주셔서 감사합니다.안드로이드에서 배열로 http 응답을 넣는 방법

답변

1

당신은 데이터 교환 형식과 같은 XML 또는 JSON를 사용하여 서버 측에서 응답을 인코딩해야합니다.

그러면 클라이언트 측에서 쉽게 구문 분석 할 수 있습니다.

안드로이드는 JSON이 좀 더 쉬울 지 모르지만 두 가지 모두를 훌륭하게 지원합니다.

데이터 구조는 매우 간단 경우 - 예를 들어, 단어 목록 - 당신이 배열을 얻을 수 String.split()CSV (쉼표로 구분) 사용 수 :

String[] words = response.split(","); 


JSON 예 (문자열 배열)

[ 
    "The quick brown fox jumps over the lazy dog", 
    "Jackdaws love my big sphinx of quartz", 
    "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut" 
] 


JSONArray array = new JSONArray(response); 
String[] sentences = new String[array.length()]; 
for (int i = 0, i < array.length(); i++){ 
    sentences[i] = array.getString(i); 
} 
+0

하지만 내 대답은 문장의 그룹 인 경우? –

+0

JSON 예제를 포함 시켰습니다. –

0

시험해보십시오 ... 응답을 배열로 저장하는 데 도움이됩니다.

  try 
      { 

       URL url = new URL("http:/xx.xxx.xxx.x/sample.php"); 
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
       InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
       BufferedReader r = new BufferedReader(new InputStreamReader(in)); 
       String x = ""; 
       String total = ""; 
       int i=0; 
       ArrayList<String> content = new ArrayList(); 
       while((x = r.readLine()) != null) 
       { 
          content.add(x); 

       } 
       in.close(); 
       r.close(); 
      } 
      catch(Exception e) 
      { 
       e.printStackTrace(); 
       Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show(); 
      } 

arrayList를 array로 변환 할 수 있습니다.

   String ar[]= content.toArray(new String[content.size()]); 
0

더 좋은 방법은 PHP는 웹 서비스는 JSON 데이터를 보낼 수 있도록하는 것입니다. 그런 다음이를 JSON 응답으로 구문 분석하여 필요한 데이터를 파싱합니다. JSON은 xml보다 가볍기 때문에 성능을 향상시켜 대역폭 소비를 줄이므로 권장합니다.

0

JSON 데이터를 반환하는 PHP 스크립트를 만들려고합니다. 데이터를 가져 와서 배열에 넣는 예제입니다.

<?php 
$response = array(); 

require_once __DIR__ . '/db_connect.php'; 

$db = new DB_CONNECT(); 
$result = mysql_query("SELECT * FROM tbl_products") or die(mysql_error()); 

if (mysql_num_rows($result) > 0) { 

$response["product"] = array(); 

while ($row = mysql_fetch_array($result)) { 

    $product   = array(); 
    $product["products_id"]  = $row["table_id"]; 
    $product["products_price"] = $row["transaction_no"]; 
$product['products_name'] = $row["table_total_price"]; 

    array_push($response["product"], $product); 
} 
$response["success"] = 1; 

echo json_encode($response); 

} else { 
$response["success"] = 0; 
$response["message"] = "No products found"; 

echo json_encode($response); 
} 
?> 

는이 사람은 안드로이드를위한 것입니다

JSONObject json = jParser.getJSONFromUrl(NAME_OF_URL); 

     Log.d("All Product List: ", json.toString()); 

     try { 

      int success = json.getInt("success"); 

      if (success == 1) { 

       products = json.getJSONArray("product"); 

       for (int i = 0; i < products.length(); i++) { 

        JSONObject c = products.getJSONObject(i); 

        String id =c.getString("products_id"); 
        String price =c.getString("products_price"); 
        String name = c.getString("products_name"); 

       } 

      } else { 

      } 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
관련 문제