2013-04-12 5 views
3

Android 기기에서 동적으로 생성 된 특정 JSON 파일을 가져 와서 HTTP 게시물 요청을 사용하여 해당 데이터를 PHP 스크립트에 보내 텍스트 파일에 저장하려고합니다. 나중에 사용하기 위해. 결국 데이터가 MySQL 데이터베이스에 저장되도록해야하지만 한 번에 한 단계 씩 작업해야합니다. JSON 파일의 형식이 모습의 예는 이것이다 :Android에서 PHP로 JSON 데이터 보내기 및 텍스트 파일에 쓰기

{"timestamp": 1351181576.64078, "name": "engine_speed", "value": 714.0} 
{"timestamp": 1351181576.64578, "name": "vehicle_speed", "value": 0.0} 
{"timestamp": 1351181576.6507802, "name": "brake_pedal_status", "value": true} 

이 파일은 동적으로 안드로이드에 라인으로 라인을 만들어, 그래서 한 번에 전체 파일을 보낼 수 있지만, 각 라인이 만들어집니다 PHP 스크립트를 보내고 싶습니다. 단추를 누를 때 JSONObject를 사용하여 HTTP Post를 사용하여 PHP 스크립트로 보내는 기본적인 Android 애플리케이션을 작성했습니다. 지금 당장은 실제 JSON 파일을 보낼 객체로 파싱하는 것에 대해 걱정할 필요가 없으며 두 개의 테스트 JSONObject를 사용하고 있습니다. PHP 스크립트는 첫 번째 객체를 가져 와서 문제없이 텍스트 파일에 저장하지만 다른 객체는 null로 계속 읽습니다. 이유는 알 수 없습니다. 나는 상대적으로 PHP와 안드로이드 프로그래밍에 익숙하지 않고 올바른 방식으로 데이터를 보내고 받는지 확실치 않습니다. 현재 출력

<?php 
    $filename = __DIR__.DIRECTORY_SEPARATOR."jsontest.txt"; 
    $json = $_POST['json']; 
    $data = json_decode($json, TRUE); 

    if(is_null($json) == false){ 
     file_put_contents($filename, "$json \n", FILE_APPEND); 
     foreach ($data as $name => $value) { 
     file_put_contents($filename, "$name -> $value \t", FILE_APPEND); 
     } 
     file_put_contents($filename, "\n", FILE_APPEND); 
    } 

    $myFile = "jsontest.txt"; 
    $fh = fopen($myFile, 'r'); 
    $theData = fread($fh, filesize($myFile)); 
    fclose($fh); 
    ?> 

    <meta http-equiv="refresh" content="3" > 
    <html> 
     <!-- Displaying the data from text file, not really needed --> 
     <p><?php echo $theData; ?></p> 
    </html> 

: 아래

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    final Button button = (Button) findViewById(R.id.sendData); 
    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // Perform action on click 
      Toast.makeText(MainActivity.this, "button was pressed", 
        Toast.LENGTH_SHORT).show(); 
      try { 
       JSONObject json = new JSONObject(); 
       json.put("timestamp", 1351181576.64078); 
       json.put("name", "engine_speed"); 
       json.put("value", 714.0); 
       postData(json); 

       JSONObject json2 = new JSONObject(); 
       json.put("timestamp", 1351181576.7207818); 
       json.put("name", "steering_wheel_angle"); 
       json.put("value", 11.1633); 
       postData(json2); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

     } 
    });  
} 

public void postData(JSONObject json) throws JSONException { 
    HttpClient httpclient = new DefaultHttpClient(); 

    try { 
     HttpPost httppost = new HttpPost(URL); 

     List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);  
     nvp.add(new BasicNameValuePair("json", json.toString())); 
     //httppost.setHeader("Content-type", "application/json"); 
     httppost.setEntity(new UrlEncodedFormEntity(nvp)); 
     HttpResponse response = httpclient.execute(httppost); 

     if(response != null) { 
      InputStream is = response.getEntity().getContent(); 
      //input stream is response that can be shown back on android 
     } 

    }catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

는 HTTP 포스트에서 데이터를 가지고 텍스트 파일로 작성하는 PHP 코드입니다 : 다음은 내 관련 안드로이드 응용 프로그램 코드의 세그먼트는

{"value":714,"timestamp":1.35118157664078E9,"name":"engine_speed"} 
value -> 714 timestamp -> 1351181576.64  name -> engine_speed  
{} 

답변

6

귀하의 문제는 안드로이드 응용 프로그램에 있습니다 : 첫 번째 개체가 완벽하게 정상적으로 저장되는 두 번째 오브젝트가 null로 최대 보여주는 텍스트 파일은 다음과 같습니다

  JSONObject json = new JSONObject(); 
      json.put("timestamp", 1351181576.64078); 
      json.put("name", "engine_speed"); 
      json.put("value", 714.0); 
      postData(json); 

      JSONObject json2 = new JSONObject(); 
      json.put("timestamp", 1351181576.7207818); 
      json.put("name", "steering_wheel_angle"); 
      json.put("value", 11.1633); 
      postData(json2); 

json2에 데이터를 입력하지 않고 json을 수정하고 있습니다. 그런 다음 완전히 수정되지 않은 - 따라서 비어있는 - json2 객체를 PHP에 보내면, 실수로 {}으로 출력됩니다. 제대로 json2을 작성 안드로이드 응용 프로그램을 수정하는 경우

상황이 작동합니다 :

  JSONObject json2 = new JSONObject(); 
      json2.put("timestamp", 1351181576.7207818); 
      json2.put("name", "steering_wheel_angle"); 
      json2.put("value", 11.1633); 
      postData(json2); 
+0

멋진 캐치 .......... – Triode

+0

오 나의 신 나는 그런 바보 같은 느낌이 .. 나를 사로 잡는 것은 항상 작은 것들입니다. 도와 주셔서 감사합니다! – mbecker73

관련 문제