2012-05-02 5 views
0

두 개의 응용 프로그램이 있습니다. 하나는 오래 전송합니다. php 파일에 위도 좌표와 다른 응용 프로그램은 long을 검색합니다. 및 위도. coords. 테스트하고 내가 첫 번째 작업을 할 수 있는지 확인하기 위해 위도와 경도를 게시 한 함수를 만듭니다. coords 두 PHP 서비스와 나는 그들에게 같은 응용 프로그램에서 다시있어. 나는 그것이 작동하는지보기 위해 건배에 그들을 배치했다. 필자는 위치 수신기를 구현하여 좌표를 업로드하고 동일한 응용 프로그램에서 검색하여 다른 응용 프로그램에서 수신하려고 시도하기 전에 테스트했습니다. 그것은 잘 작동합니다. 그러나 좌표를 받기 위해 다른 응용 프로그램에서 동일한 코드를 사용하려고하면 빈 좌표가 나타납니다. 내가 그것을 디버깅하고 방금 빈 것처럼, 내가 다른 응용 프로그램에서 서버에 전화를 걸면 PHP 서비스의 현재 값을 지 웁니다.Android : PHP 웹 페이지에서 빈 문자열 얻기

public void postData(String longCord, String latCord) throws JSONException{ 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(".../android/serverFile.php"); 
    JSONObject json = new JSONObject(); 

    try { 
     // JSON data: 
     json.put("longitude", longCord); 
     json.put("latitude", latCord); 
     JSONArray postjson=new JSONArray(); 
     postjson.put(json); 

     // Post the data: 
     httppost.setHeader("json",json.toString()); 
     httppost.getParams().setParameter("jsonpost",postjson); 
     // Execute HTTP Post Request 
     //System.out.print(json); 
     HttpResponse response = httpclient.execute(httppost); 

     // for JSON: 
     if(response != null) 
     { 

      InputStream is = response.getEntity().getContent(); 
      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(); 
       } 
      } 
            JSONObject jsonObj = new JSONObject(jsonStr); 
       // grabbing the menu object 
       String longitudecord = jsonObj.getString("lon"); 
       String latitudecord = jsonObj.getString("lat"); 

       Toast.makeText(getApplicationContext(),longitudecord,Toast.LENGTH_SHORT).show(); 
       Toast.makeText(getApplicationContext(),latitudecord,Toast.LENGTH_SHORT).show(); 
     } 

    }catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

PHP 파일 : 응용 프로그램 하나에 좌표를 배치

코드

<?php 
$json = $_SERVER['HTTP_JSON']; 
$data = json_decode($json); 
$lon = $data->longitude; 
$lat = $data->latitude; 
$variable = array('lon' => "$lon", 'lat' => "$lat"); 
// One JSON for both variables 
echo json_encode($variable); 

지금>

내가 다른 응용 프로그램에서이 코드를 실행 ... 그것? 위의 좌표와 같지 않은 좌표와 같습니다. 나는 ""와 lat : ""를 얻습니다. 일종의 요청을 만들어서 다른 응용 프로그램에서 게시 한 정보를 삭제했습니다. 이 경우인가요?

public void recieveData() throws JSONException{ 
     // Create a new HttpClient and Post Header 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(".../android/serverFile.php"); 
     try { 
      HttpResponse response = httpclient.execute(httppost); 
      // for JSON: 
      if(response != null) 
      { 
       InputStream is = response.getEntity().getContent(); 
       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(); 
        } 
       } 
       String jsonStr = sb.toString(); 
       JSONObject jsonObj = new JSONObject(jsonStr); 
       // grabbing the menu object 
       String longitudecord = jsonObj.getString("lon"); 
       String latitudecord = jsonObj.getString("lat"); 

       Toast.makeText(getApplicationContext(),longitudecord,Toast.LENGTH_SHORT).show(); 
       Toast.makeText(getApplicationContext(),jsonStr,Toast.LENGTH_SHORT).show(); 
      } 
+0

가 ".../안드로이드/serverFile.php"나는이 사이트에 elipses를 넣어 – lenik

+0

나에게 유효한 URL처럼 보이게하지 않습니다 그래서 I 내 파일이 호스팅 된 곳을 공유하지 않습니다 ... URL이 작동합니다. 첫 번째 신청서를 게시하고 가져 오는 중입니다. 두 번째는 공백이되는 곳입니다. – inspired

+0

귀하의 데스크톱 브라우저에서 해당 URL을 치고 페이지에 무엇이 있는지 확인하십시오 – Akram

답변

1

시도는 브라우저에서 URL에 액세스하고 (두 번째 응용 프로그램의 모든 JSON 입력을 제공하지 않기 때문에) 당신의 PHP 스크립트는 다음 줄에 오류를 제공하지 않습니다 확인하십시오 :

$data = json_decode($json); 
$lon = $data->longitude; 
$lat = $data->latitude; 

또한 들으니 좋을 것입니다. 어떻게하면 위도/경도 서버에 저장 했으므로 호출간에 유지됩니다.

것은 예를 들어,이 PHP 코드를 사용할 수 있습니다 :

$db_host = "localhost"; 
$db_name = "********"; 
$db_user = "********"; 
$db_pass = "********"; 

// connect to MySQL 
$db = mysql_connect($db_host, $db_user, $db_pass); 
if(!$db) { 
    die('Unable to connect to server : ' . mysql_error()); 
} 

// select the DB 
if(!mysql_select_db($db_name)) { 
    die('Unable to select DB : ' . mysql_error()); 
} 

// create table, if not exists 
if(!mysql_query("CREATE TABLE IF NOT EXISTS `locations` (
    `id` int(11) NOT NULL auto_increment, 
    `latitude` double NOT NULL COMMENT 'latitude', 
    `longitude` double NOT NULL COMMENT 'longitude', 
    PRIMARY KEY (`id`) 
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;" 
)) { 
    die('Unable to create table : ' . mysql_error()); 
} 

// save values 
mysql_query("INSERT INTO locations (`latitude`, `longitude`) VALUES ('$lat', '$lon')"); 

// read them back 
$track = array() 
$result = mysql_query("SELECT * FROM locations"); 
while($data = mysql_fetch_assoc($result)) { 
    $track[] = array(
     'latitude' => $data['latitude'], 
     'longitude' => $data['longitude']); 
} 

// here you may convert `track` into JSON/XML and send coordinates list to your application 
+0

롤 ... 나는 그것이 문제라고 생각합니다. 오류가 없습니다. 첫 번째 애플리케이션에서 제공 한 JSON 입력은 PHP 파일의 변수 $ lon 및 $ lat에 저장 될 것이라고 생각했습니다. 서버에 위도/경도를 저장하여 계속 유지하려면 어떻게해야합니까? 데이터베이스를 사용해야합니까? – inspired

+0

MySQL 코드를 – lenik

+0

에 추가했습니다. 고맙습니다! 이것은 훌륭하게 작동했습니다. Application # 1이 lon/lat를 업데이트하면 새로운 행이 생성됩니다. 신청서 # 2에 좌표를 하나씩 보내고 싶습니다. 행을 기준으로 테이블 행을 구문 분석하는 방법 ... 검색 코드를 실행할 때마다 증가시킵니다. 이것을하는 것이 최선의 방법입니까? – inspired

관련 문제