Отправьте значения из Android sqlite3 в базу данных SQL, чтобы иметь операцию синхронизации - PullRequest
0 голосов
/ 31 марта 2012

Я пытаюсь загрузить значения из базы данных Android sqlite3 в базу данных MySQL на моем сервере.Мне удалось опубликовать значения из одного объекта JSON, который я создал.Однако, когда я пытаюсь синхронизировать значения из моей базы данных sqlite3, база данных mysql на сервере не обновляется.Вот мой PHP-код на сервере.

<?php  
mysql_connect('localhost','sapeksha_me','getmein'); 

$json = file_get_contents('php://input');
$obj = json_decode($json);

mysql_select_db("sapeksha_locationdata");

mysql_query("INSERT INTO location (MobileID, Latitude, Longitude, Speed, Acceleration, Time, Date, Sync) VALUES ('".$obj->{'MobileID'}."', '".$obj->{'Latitude'}."', '".$obj->{'Longitude'}."', '".$obj->{'Speed'}."', '".$obj->{'Acceleration'}."', '".$obj->{'Time'}."', '".$obj->{'Date'}."', '".$obj->{'Sync'}."')");

?>

А вот фрагмент кода для отправки содержимого из моей базы данных sqlite3 на сервер.

        SQLiteDatabase db = databasehelper.getWritableDatabase();
        Cursor cursor = db.query(TABLE, null, null, null, null, null, null, null);

        cursor.moveToFirst();
        while(cursor.isAfterLast() == false) {

            if(cursor.getString(cursor.getColumnIndex("Sync")).equals("yes") ) {

                String mob = cursor.getString(cursor.getColumnIndex("MobileID"));
                String lat = cursor.getString(cursor.getColumnIndex("Latitude"));
                String lng = cursor.getString(cursor.getColumnIndex("Longitude"));
                String speed = cursor.getString(cursor.getColumnIndex("Speed"));
                String acc = cursor.getString(cursor.getColumnIndex("Acceleration"));
                String date = cursor.getString(cursor.getColumnIndex("Date"));
                String time = cursor.getString(cursor.getColumnIndex("Time"));
                String update = cursor.getString(cursor.getColumnIndex("Sync"));

                JSONObject json = new JSONObject();
                try {
                    json.put("MobileID", mob);
                    json.put("Latitude", lat);
                    json.put("Longitude", lng);
                    json.put("Speed", speed);
                    json.put("Acceleration", acc);
                    json.put("Time", time);
                    json.put("Date", date);
                    json.put("Sync", update);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    receive = HttpPostExample.SendJsonUpdate(json, Sync_URL);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Toast.makeText(context,  receive,
                        Toast.LENGTH_SHORT).show();
            }
            cursor.moveToNext();    
        }
        cursor.close();

Фрагмент кода с использованием HttpPost ..

public static String SendJsonUpdate(JSONObject json, String URL) throws ClientProtocolException, IOException {


    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT_MILLISEC);

        HttpClient client = new DefaultHttpClient(params);


        HttpPost post = new HttpPost(URL);

        post.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
        post.setHeader("json", json.toString());
        StringEntity se;
        se = new StringEntity(json.toString());

        post.setEntity(se);
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-type", "application/json");
        post.setHeader("Accept-Encoding", "gzip");

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) client.execute(post);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        HttpEntity entity = response.getEntity();

        if(entity != null) {

            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            String resultString = convertStreamToString(instream);
            instream.close();

            Log.i("Read from server", resultString);

            return resultString;
        }

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

    return null;

}        

Logcat показывает операторы "HttpResponse полученный в []", но база данных на сервере не обновляется.Я еще не приобрел опыт в разработке Android и PHP / SQL кодирования.Код может быть не лучшим способом сделать это, но что я делаю не так?

1 Ответ

2 голосов
/ 31 марта 2012

Включена ли ваша автоматическая фиксация?

mysql_query('SET AUTOCOMMIT=1');

Если нет, оберните свои утверждения в

mysql_query('START TRANSACTION');
<your queries>
mysql_query('COMMIT');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...