2013-11-24 1 views
0

잘하고 있습니다. 나는 안드로이드 애플 리케이션을 개발하고 있는데, 로컬 SQL과 서버의 데이터베이스를 동기화해야한다. 서버 측에서 PHP를 사용하고 있습니다 (JSON을 사용하여 날짜를 가져옵니다). 내 문제는 내가 처음으로 응용 프로그램을 시작하면 서버에있는 데이터를 다운로드하고 두 번째로 실행하면 데이터가 다시 다운로드되고 때로는 발생하지만 때로는 그렇지 않은 경우입니다. 그리고 새 데이터를 추가 할 때 데이터가 다운로드되지만 문제가 계속 발생하면 데이터가 복제됩니다. 휴대 전화에서 앱을 사용해 보면 데이터가 한 번 다운로드되지만 새 데이터를 추가하면 다운로드되지 않습니다! 내 코드는 다음과 같습니다.로컬 SQL과 서버 데이터베이스 간의 동기화

protected Void doInBackground(Void... uri) { 
     myDatabaseHandler.openToRead(); 
     Cursor cursor = myDatabaseHandler.queueBranchId(); 
     try { 
      HttpParams params = new BasicHttpParams(); 
      HttpConnectionParams.setSoTimeout(params, 0); 
      HttpClient httpClient = new DefaultHttpClient(params); 

      //prepare the HTTP GET call 
      HttpGet httpget = new HttpGet("http://restaurants.bugs3.com/branches.php"); 
      //get the response entity 
      HttpEntity entity = httpClient.execute(httpget).getEntity(); 

      if (entity != null) { 
       //get the response content as a string 
       String response = EntityUtils.toString(entity); 
       //consume the entity 
       entity.consumeContent(); 

       // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources 
       httpClient.getConnectionManager().shutdown(); 

       //return the JSON response 
       JSONObject object = new JSONObject(response.trim()); 
       JSONArray jsonArray = object.getJSONArray("branches"); 
       if(jsonArray != null) { 
        for(int i = 0 ; i < jsonArray.length() ; i++) { 
          JSONObject object1 = (JSONObject) jsonArray.get(i); 
          int server_branch_id = object1.getInt("server_branch_id"); 
          String branch_name = object1.getString("branch_name"); 
          double branch_lat = object1.getDouble("branch_lat"); 
          double branch_lon = object1.getDouble("branch_lon"); 
          double distance = object1.getDouble("distance"); 
          String restaurant_name = object1.getString("restaurant_name"); 
          boolean exist = false; 
if (cursor.moveToFirst()) 
          { 
           do 
           { 
            try 
            { 
             if (server_branch_id == cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_LOCAL_BRANCH_ID))) 
             { 
              exist = true; 
             } 
            } 
            catch(Exception e) 
            { 
            } 
           }while(cursor.moveToNext()); 
           cursor.close(); 
          } 
          myDatabaseHandler.close(); 

          if (!exist) 
          { 
           myDatabaseHandler.openToWrite(); 
           myDatabaseHandler.insertBranchWithID(server_branch_id, branch_name, restaurant_name, branch_lat, branch_lon, distance); 
           myDatabaseHandler.close(); 
          } 

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

답변

0

여기에는 몇 가지 해결 방법이있을 수 있습니다. 이 경우 새로운 ID가있을 경우 서버를 물어, 로컬 SQL에서 마지막 ID의

  1. 보관할 트랙, 응용 프로그램 시작시와 : 나는 (당신이 다운로드 어떤 항목에 대한 특정 ID를 가지고 가정) 두 가지 방법을 제안 할 수 있습니다 다운로드하십시오. 이렇게하면 복제를 피할 수 있습니다.
  2. 테이블에 기본 키 제약 조건을 사용하고 삽입을 위해 insertWithOnConflict (..., CONFLICT_IGNORE)를 사용합니다. 이 메소드는 동일한 ID를 복제하지 않고 다른 것이 있으면 삽입합니다.

희망이 여기 내가 local_id WIH 모든 SERVER_ID을 비교하고있어, 관심을

+0

감사를하는 데 도움이, SERVER_ID는 AUTO_INCREMENT입니다. 그래서 왜 데이터가 복제되었는지 알 수 없습니다! insertWithOnConflict를 시도 할 것이지만 잘못된 코드를 발견하면 내 코드의 문제점을 알고 싶습니다. –

+0

감사합니다. 귀하의 솔루션을 시도했지만 정상적으로 작동합니다. –

관련 문제