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

时间:2014-05-22 04:19:21

标签: android sqlite

将数据存储到SQLiteDatabase ,存储到SD卡中,现在我必须将所有SQLite数据发送到服务器。 注意:我有为服务器数据库创建相同的字段 simillar 到SQLite数据库),例如: 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();
}

我可能知道, 如何将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);
    }

}

3 个答案:

答案 0 :(得分: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;
}

现在做,

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();

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

现在根据你的代码,做

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

答案 1 :(得分:1)

我有一些代码片段只是为了你的想法。如果它帮助你我很高兴。

           protected void startSync(Context aContext) {
    try {
        AccountManager am = AccountManager.get(getBaseContext());
        Account[] ac = am.getAccountsByType(Constants.ACCOUNT_TYPE);
        if (ac.length > 0) {
            Toast.makeText(SuperHomeActivity.this,
                    "Synchronization Started", Toast.LENGTH_SHORT).show();
            List<PeriodicSync> aList = ContentResolver.getPeriodicSyncs(
                    ac[0], Constants.AUTHORITY);
            Bundle bundle = new Bundle();
            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
            if (aList != null && aList.size() > 0) {
                while (aList != null && !aList.isEmpty()) {
                    ContentResolver.removePeriodicSync(ac[0],
                            Constants.AUTHORITY, aList.get(0).extras);
                    aList.remove(0);
                }
            }
            // mention only in seconds -> 120 minutes 60 seconds
            ContentResolver.addPeriodicSync(ac[0], Constants.AUTHORITY,
                    bundle, 5 * 60); //15
            ContentResolver.requestSync(ac[0], Constants.AUTHORITY, bundle);
        }
    } catch (Exception ex) {
        Log.e("SyncAccountTriggerError", ex.getMessage());
    }
}

你可以通过

来调用它
                startSync(getApplicationContext());

如有任何更多说明,您可以ping我。

答案 2 :(得分:0)

您可以使用Http Post方法或Get方法,或者如果您想直接更新服务器数据库,则使用Put方法。您可以使用NameValue对通过http请求发送数据,只需从服务器获取该数据并更新您的数据库。就是这样。