Reputation: 2634
I am storing data into SQLiteDatabase which is stored into SD Card, now i have to send all SQLite data to server. Note: I have created same fields to server database as well (simillar to SQLite DB) for an eg: PersonName
Below code i used to check, am i able to store data to server (for testing purpose - i accepted data by user into edittext) and then sent to server, and i was successful in that.
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();
}
So may i know, How can i send SQLite database records to server ? My database class looks like this:
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);
}
}
Upvotes: 2
Views: 13263
Reputation: 5068
I think easy way is that you convert all your sqlite data into xml or json and then only one http request is required to send all your data to online server. At online server you can easily parse your data as you already know the structure of your xml or json whatever you used.
let say you have 2 fields in your database. ID , Name. you have 10 records. you convert all your records into json .
let say you query your database for all records and now cursor
object will hold all your sqlite data.
add getAllData()
method to retrieve all your database data.
public Cursor getAllData() {
String selectQuery = "Select * from "+TABLE_MEMBER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
now do,
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();
now simply make an http call with string parameter and send to server.and parse at server by converting this string into jsonobject.
now according to your code, do
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("allData", st));
String resultServer = getHttpPost(url,params);
Upvotes: 6
Reputation: 1518
I have some snippet of code just for your idea.If it help you it my pleasure.
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());
}
}
And you can call it by
startSync(getApplicationContext());
For any more clarification you can ping me.
Upvotes: 1
Reputation: 7439
you can use Http Post method or Get method or if you directly wants to update your server DB then use Put method. You can send data by http request with NameValue pair and just get that data from server and update your DB. That's it.
Upvotes: 0