如何将所有SQLite数据发送到在线服务器

Sop*_*hie 1 sqlite android

将数据存储到存储在SD卡中的SQLiteDatabase中,现在我必须将所有SQLite数据发送到服务器.注意:我也为服务器数据库创建了相同的字段(simillar到SQLite DB),例如:PersonName

下面我用来检查的代码,我能够将数据存储到服务器(用于测试目的 - 我用户接受数据到edittext),然后发送到服务器,我成功了.

String url = "http://localhost/ChurchData.php";                                         
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sPersonName", editPersonName.getText().toString()));
String resultServer  = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);

/*** Default Value ***/
strStatusID = "0";
strError = "";

JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
 }
 // prepare save data
 if(strStatusID.equals("0"))
 {
Toast.makeText(getApplicationContext(), "Already Exist !", Toast.LENGTH_LONG).show();
 }
 else
 {
Toast.makeText(getApplicationContext(), "Data Uploaded Successfully!", Toast.LENGTH_SHORT).show();                          
 }
 return true;
}

private String getHttpPost(String url,
 List<NameValuePair> params) {
 StringBuilder str = new StringBuilder();
 HttpClient client = new DefaultHttpClient();
 HttpPost httpPost = new HttpPost(url);
 try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
 return str.toString();
}
Run Code Online (Sandbox Code Playgroud)

所以我可以知道,我如何将SQLite数据库记录发送到服务器?我的数据库类如下所示:

public class myDBClasss extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 2;
    // Database Name
    private static final String DATABASE_NAME = "ChurchDB";
    // Table Name
    private static final String TABLE_MEMBER = "DataTable";

    public myDBClasss(Context context) {
        // to store data into SD Card   
       super(context, Environment.getExternalStorageDirectory()
                + File.separator + "ChurchData"
                + File.separator + DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        // Create Table Name
        db.execSQL("CREATE TABLE " + TABLE_MEMBER + 
                  "(PersonName VARCHAR(100)," +
                  " PersonEmail VARCHAR(100)," +
                  " PersonTelephone VARCHAR(100)," +
                  " Newsletter VARCHAR(100));");       // checkbox

        Log.d("CREATE TABLE","Create Table Successfully - classs");
    }

    // Insert Data
    public long insertData(String strPersonName, String strPersonEmail, String strPersonTelephone, String strNewsletter) {
        // TODO Auto-generated method stub

         try {
            SQLiteDatabase db;
            db = this.getWritableDatabase(); // Write Data

            ContentValues Val = new ContentValues(); 
            Val.put("PersonName", strPersonName);
            Val.put("PersonEmail", strPersonEmail);
            Val.put("PersonTelephone", strPersonTelephone);
            Val.put("Newsletter", strNewsletter);       // checkbox

            long rows = db.insert(TABLE_MEMBER, null, Val);

            db.close();
            return rows; // return rows inserted.

         } catch (Exception e) {
            return -1;
         }
    }

    // Update Data
    public long updateData(String strPersonName, String strPersonEmail, String strPersonTelephone, String strNewsletter){
    // TODO Auto-generated method stub

        try {
            SQLiteDatabase db;
            db = this.getWritableDatabase(); // Write Data

            ContentValues Val = new ContentValues();
            Val.put("PersonName", strPersonName);
            Val.put("PersonEmail", strPersonEmail);
                    Val.put("PersonTelephone", strPersonTelephone);
            Val.put("Newsletter", strNewsletter);       // checkbox

            long rows = db.update(TABLE_MEMBER, Val, "PersonName=?",
                    new String[] { String.valueOf(strPersonName) });

            db.close();
            return rows; // return rows updated.

        } catch (Exception e) {
            return -1;
        }   
    }

    // Fetch data
    public String[] selectData(String strPersonName) {
        // TODO Auto-generated method stub

         try {
            String arrData[] = null;    

             SQLiteDatabase db;
             db = this.getReadableDatabase(); // Read Data

             Cursor cursor = db.query(TABLE_MEMBER, new String[] { "*" }, 
                        "PersonName=?",
                        new String[] { String.valueOf(strPersonName) }, null, null, null, null);

                if(cursor != null)
                {
                    if (cursor.moveToFirst()) {
                        arrData = new String[cursor.getColumnCount()];

                        arrData[0] = cursor.getString(0);
                        arrData[1] = cursor.getString(1);
                        arrData[2] = cursor.getString(2);
                        arrData[3] = cursor.getString(3);       // checkbox
                    }
                }
                cursor.close();
                db.close();
                return arrData;

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

    // Check for data(s) using PersonName field
    public boolean exists(String strImageName) {
           SQLiteDatabase db;
           db = this.getReadableDatabase(); // Read Data
           Cursor cursor = db.rawQuery("select 1 from DataTable where PersonName= ?", 
                new String[] { strImageName });
           boolean exists = (cursor.getCount() > 0);
           cursor.close();
           return exists;
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
        // Re Create on method  onCreate
        onCreate(db);
    }

}
Run Code Online (Sandbox Code Playgroud)

Waq*_*med 6

我认为简单的方法是将所有sqlite数据转换为xml或json,然后只需要一个http请求即可将所有数据发送到在线服务器.在在线服务器上,您可以轻松地解析数据,因为您已经知道xml或json的结构.

假设您的数据库中有2个字段.ID,名称.你有10条记录.您将所有记录转换为json.

假设您在数据库中查询所有记录,现在cursor对象将保存所有sqlite数据.

添加getAllData()方法来检索所有数据库数据.

public Cursor getAllData() {
     String selectQuery = "Select * from "+TABLE_MEMBER; 
     SQLiteDatabase db = this.getReadableDatabase();
     Cursor cursor = db.rawQuery(selectQuery, null);
     return cursor;
}
Run Code Online (Sandbox Code Playgroud)

现在做,

Cursor cursor = getAllData();  //cursor hold all your data
JSONObject jobj ;
JSONArray arr = new JSONArray();
cursor.moveToFIrst();
while(cursor.moveToNext()) {
   jobj = new JSONObject();
   jboj.put("Id", cursor.getInt("Id"));
   jboj.put("Name", cursor.getString("Name"));
   arr.put(jobj);
}

jobj = new JSONObject();
jobj.put("data", arr);

String st = jboj.toString();
Run Code Online (Sandbox Code Playgroud)

现在只需使用字符串参数进行http调用并发送到server.and并通过将此字符串转换为jsonobject来解析服务器.

现在根据你的代码,做

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("allData", st));
String resultServer  = getHttpPost(url,params);
Run Code Online (Sandbox Code Playgroud)