将sqlite与mysql同步

时间:2015-03-25 14:17:23

标签: android mysql json sqlite

我试图将sqlite与mysql数据库同步,所以我创建了一个dbAdapter类,我在其中创建了一个sqlite数据库,另一个类我用json做了一个json响应和putt json在hashmap中

这是Dbadapter类

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

public class DBAdaptert extends SQLiteOpenHelper {
    SQLite lt= new SQLite();

    public DBAdaptert(Context aplicationcontext) {
        super(aplicationcontext, "recept.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        String query;
        query = "CREATE TABLE recept ( id INTEGER, ime TEXT)";
        database.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int i, int i2) {
        String query;
        query = "DROP TABLE IF EXISTS recept";
        database.execSQL(query);
        onCreate(database);
    }

    public void insertIme(HashMap<String, String> queryValues) {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("ime", queryValues.get("ime"));
        database.insert("recept", null, values);
        database.close();
    }

    public ArrayList<HashMap<String, String>> getIme() {
        lt.updateSQLite();
        ArrayList<HashMap<String, String>> imeList;
        imeList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  ime FROM recept";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("ime", cursor.getString(0));
                imeList.add(map);
            } while (cursor.moveToNext());
        }
        database.close();
        return imeList;
    }

}

这里是我做json响应的类

package com.example.koohar;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by bozidar on 23.3.2015..
 */
public class SQLite {
    DBAdaptert ad;
    ArrayList<HashMap<String, String>> usersynclist;
    InputStream isr = null;
    HashMap<String, String> queryValues = new HashMap<String, String>();
    String result = "";

    public SQLite()  {
        try {
            DefaultHttpClient klijent = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://masinko1.comoj.com/sastojci.php");
            HttpResponse respons = null;
            respons = klijent.execute(post);
            HttpEntity entitet = respons.getEntity();
            isr = entitet.getContent();
        } catch (Exception e) {
            Log.e("log..tag", "error in connecting" + e.toString());
        }
        //prebacivanje rez u apl.
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            isr.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log..tag", "greska u prebacivanju resumasa" + e.toString());
        }
    }

    public void updateSQLite() {
        String j="bla";
        queryValues = new HashMap<String, String>();

        try {
            JSONObject json = new JSONObject(result);
            JSONArray jaraj = json.getJSONArray("ime");
            for (int i = 0;i<jaraj.length(); i++) {
                JSONObject joni = (JSONObject) jaraj.get(i);
                j=joni.getString("ime");
                queryValues=new Gson().fromJson(j, new TypeToken<HashMap<String, String>>() {}.getType());

            }

        } catch (
                JSONException e
                )
        {
            // TODO Auto-generated catch block
            throw new RuntimeException(e);        }
      ad.insertIme(queryValues);
    }



}

最后是一个主线程,我想将hashmap放入arraylist

package com.example.koohar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by bozidar on 22.3.2015..
 */
public class DnevniRez extends Activity {
    DBAdaptert ad = new DBAdaptert(this);
    ListView list;
    Button but;
    String[] ajmo;

    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String, String>> map = ad.getIme();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dnevnirez);
        list = (ListView) findViewById(R.id.listView);
        but = (Button) findViewById(R.id.button6);
        if(map.size()!=0) {
            ListAdapter adapter = new SimpleAdapter(DnevniRez.this, map, R.layout.activity_dnevnirez, new String[]{
                    "ime"}, new int[]{R.id.userName});
            list.setAdapter(adapter);
        }
        ProgressDialog prgDialog = new ProgressDialog(this);
        prgDialog.setMessage("Synching SQLite Data with Remote MySQL DB. Please wait...");
        prgDialog.setCancelable(false);
    }



}

当我运行它崩溃时,在logcat中它表示它的jsonexception索引超出范围。这里有完整的堆栈跟踪

03-27 07:06:10.100    1836-1836/com.example.koohar D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
03-27 07:06:11.990    1836-1836/com.example.koohar D/dalvikvm﹕ GC_FOR_ALLOC freed 301K, 13% free 2672K/3064K, paused 66ms, total 69ms
03-27 07:06:12.160    1836-1836/com.example.koohar D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so
03-27 07:06:12.160    1836-1836/com.example.koohar D/﹕ HostConnection::get() New Host Connection established 0xb9551160, tid 1836
03-27 07:06:12.180    1836-1836/com.example.koohar D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so
03-27 07:06:12.180    1836-1836/com.example.koohar D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so
03-27 07:06:12.320    1836-1836/com.example.koohar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-27 07:06:12.320    1836-1836/com.example.koohar D/OpenGLRenderer﹕ Enabling debug mode 0
03-27 07:06:36.350    1836-1836/com.example.koohar W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
03-27 07:06:37.790    1836-1836/com.example.koohar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-27 07:06:38.330    1836-1981/com.example.koohar E/log...tag﹕ org.json.JSONException: Index 40 out of range [0..40)
03-27 07:06:39.260    1836-1836/com.example.koohar D/dalvikvm﹕ GC_FOR_ALLOC freed 197K, 9% free 2988K/3276K, paused 5ms, total 7ms
03-27 07:06:40.960    1987-1987/com.example.koohar D/dalvikvm﹕ Not late-enabling CheckJNI (already on)
03-27 07:06:41.020    1987-1993/com.example.koohar E/jdwp﹕ Failed sending reply to debugger: Broken pipe
03-27 07:06:41.020    1987-1993/com.example.koohar D/dalvikvm﹕ Debugger has detached; object registry had 1 entries
03-27 07:06:41.200    1987-1991/com.example.koohar D/dalvikvm﹕ GC_CONCURRENT freed 60K, 6% free 2848K/3008K, paused 15ms+0ms, total 19ms
03-27 07:06:41.270    1987-1987/com.example.koohar D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so
03-27 07:06:41.300    1987-1987/com.example.koohar D/﹕ HostConnection::get() New Host Connection established 0xb9551160, tid 1987
03-27 07:06:41.320    1987-1987/com.example.koohar D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so
03-27 07:06:41.320    1987-1987/com.example.koohar D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so
03-27 07:06:41.370    1987-1987/com.example.koohar W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-27 07:06:41.400    1987-1987/com.example.koohar D/OpenGLRenderer﹕ Enabling debug mode 0

1 个答案:

答案 0 :(得分:0)

您隐藏StackTrace,因此很难找到错误。记录异常时,最好使用此方法:http://developer.android.com/reference/android/util/Log.html#e%28java.lang.String,%20java.lang.String,%20java.lang.Throwable%29

Log.e(TAG, "my message", exception)

所以用这个替换你的代码:

String TAG = "SQLite";
public SQLite()  {
        try {
            DefaultHttpClient klijent = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://masinko1.comoj.com/sastojci.php");
            HttpResponse respons = null;
            respons = klijent.execute(post);
            HttpEntity entitet = respons.getEntity();
            isr = entitet.getContent();
        } catch (Exception e) {
            Log.e(TAG, "error in connecting" + e.toString(),e);
        }
        //prebacivanje rez u apl.
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            isr.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e(TAG, "greska u prebacivanju resumasa" + e.toString(), e);
        }
    }

    public void updateSQLite() {
        String j="bla";
        queryValues = new HashMap<String, String>();

        try {
            JSONObject json = new JSONObject(result);
            JSONArray jaraj = json.getJSONArray("ime");
            for (int i = 0;i<jaraj.length(); i++) {
                JSONObject joni = (JSONObject) jaraj.get(i);
                j=joni.getString("ime");
                queryValues=new Gson().fromJson(j, new TypeToken<HashMap<String, String>>() {}.getType());

            }

        } catch (JSONException e){
            Log.e(TAG, "error in updateSQLite", e);    
        }
      ad.insertIme(queryValues);
    }

完成此操作后,请发布新的LogCat