i have data in table named table_selected with fields(_ItemID, _ItemName, _CategoryID) in sqlite i want to get data from sqlite and Post to server in json format any help.....i am using AsyncTask to post data
this is how i am getting data from sqlite
public ArrayList<String> getAllSelectedToPost() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> selectedList = new ArrayList<>();
try {
String query = "SELECT * FROM " + TABLE_SELECTED;
Cursor c = db.rawQuery(query, null);
JSONObject obj;
JSONArray arr = new JSONArray();
c.moveToFirst();
while (c.moveToNext()) {
obj = new JSONObject();
obj.put("ItemID", c.getString(0));
obj.put("ItemName", c.getString(1));
obj.put("CategoryID", c.getString(2));
arr.put(obj);
}
obj = new JSONObject();
obj.put("Selected",arr);
selectedList = new ArrayList<>();
selectedList.add(obj.toString());
}catch (Exception e){
e.printStackTrace();
}
return selectedList;
}
this is how i am posting data to server using AsyncTask.. i am doing this in OnCreate
handler = new DBSQLite(this);
postSelected = new ArrayList<>();
postSelected = handler.getAllSelectedToPost();
String resultserver = url + postSelected;
Post_Selected runner = new Post_Selected();
runner.execute(resultserver);
public class Post_Selected extends AsyncTask<String, Void, Integer>{
@Override
protected Integer doInBackground(String... params) {
HttpURLConnection urlConnection = null;
Integer result = 0;
try{
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
// urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200){
result = 1;
}else{
result = 0;
}
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
is this the right way i am doing.....
Aucun commentaire:
Enregistrer un commentaire