AsyncTask with PHP/MySql doesnt work properly - android

I got an Array:
[{"stammkost":"IWXI","call":"name1","ean":"802.6180.222","number":"5"},{"stammkost":"8566","call":"name2","ean":"657.7121.393","number":"5"}]
I want to send a PHP-Call for every Object in it like this (using the asynctask for it. This works for one reason not right. The Asynctask should executed for every object in the array, right? But it only gets executed the first time, or like logcat the last time. The tablenames are right, but obvious the asynctask doesnt get executed right.. Can you help me?
Logcat:
04-15 21:01:54.207: V/Button(3938): Send
04-15 21:01:54.207: V/stammkost(3938): IWXI
04-15 21:01:54.207: V/tablename(3938): IWAA_IWXI_15.04.2015
04-15 21:01:54.207: V/stammkost(3938): 8566
04-15 21:01:54.207: V/tablename(3938): IWAA_8566_15.04.2015
04-15 21:01:54.207: V/jsArray(3938): [{"ean":"802.6180.222","number":"5"},{"ean":"657.7121.393","number":"5"}]
04-15 21:01:54.407: D/CreateMovementAsyncTask(3938): CREATE TABLE `IWAA_8566_15.04.2015` (uid int(11) primary key auto_increment, unique_id varchar(23) not null unique, ean varchar(20) not null, number varchar(6) not null,accepted varchar(1) not null) comment='{"out_user":"pb","out_email":"test#test.com","out_date":"15.04.2015"}'1
04-15 21:01:54.447: D/CreateMovementAsyncTask(3938): CREATE TABLE `IWAA_8566_15.04.2015` (uid int(11) primary key auto_increment, unique_id varchar(23) not null unique, ean varchar(20) not null, number varchar(6) not null,accepted varchar(1) not null) comment='{"out_user":"pb","out_email":"test#test.com","out_date":"15.04.2015"}'MYSQL Error: Table 'IWAA_8566_15.04.2015' already exists
the function:
private void CreateMovement(){
for (int i = 0; i < GlobalClass.jsArrayGeraete.length(); i++) {
try {
JSONObject jsonObj = GlobalClass.jsArrayGeraete.getJSONObject(i);
GlobalClass.KOST_NEW = jsonObj.getString("stammkost");
GlobalClass.tablename = SelectKostActivity.KOST + "_" + GlobalClass.KOST_NEW + "_" + GlobalClass.date;
new CreateMovementAsyncTask().execute();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and the AsyncTask:
class CreateMovementAsyncTask extends AsyncTask<Void,Void,Void>{
protected Void doInBackground(Void... arg0) {
DBFunctions DBFunction = new DBFunctions();
try {
JSONObject jObjComment = new JSONObject();
jObjComment.put("out_user", LoginActivity.name);
jObjComment.put("out_email", GlobalClass.email);
jObjComment.put("out_date", GlobalClass.date);
String json = DBFunction.create_movement(GlobalClass.tablename,jObjComment.toString());
Log.d("CreateMovementAsyncTask", json);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(Void json){
}
}
EDIT:
public String create_movement(String tablename, String comment){
// Building Parameters
//Log.e("tablename", tablename);
//Log.e("comment", comment);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", "create_movement"));
params.add(new BasicNameValuePair("tablename", tablename));
params.add(new BasicNameValuePair("comment", comment));
ServiceHandler jsonStr = new ServiceHandler();
String json = jsonStr.makeServiceCall(requesteanURL, ServiceHandler.POST, params);
return json;
PHP:
else if ($tag == 'create_movement') {
$coni=mysqli_connect("localhost","LOGIN","PW","movement");
$tablename = $_POST['tablename'];
$comment = $_POST['comment'];
//$jcomment = json_decode($comment, true);
$sql = "CREATE TABLE `" .$tablename. "` (uid int(11) primary key auto_increment, unique_id varchar(23) not null unique, ean varchar(20) not null, betriebszahl varchar(6) not null,accepted varchar(1) not null) comment='".$comment."'";
echo $sql;
$result = mysqli_query($coni, $sql) or die("Query failed : " . mysqli_error($coni));
echo $result;

Edit:
I think that the GlobalClass.tablename might be out of sync with the multiple AsyncTask instances.
Try passing the arguments in through the varargs, here is an example:
private void CreateMovement(){
for (int i = 0; i < GlobalClass.jsArrayGeraete.length(); i++) {
try {
JSONObject jsonObj = GlobalClass.jsArrayGeraete.getJSONObject(i);
GlobalClass.KOST_NEW = jsonObj.getString("stammkost");
//GlobalClass.tablename = SelectKostActivity.KOST + "_" + GlobalClass.KOST_NEW + "_" + GlobalClass.date;
String tableName = SelectKostActivity.KOST + "_" + GlobalClass.KOST_NEW + "_" + GlobalClass.date;
//pass in the table name and data
new CreateMovementAsyncTask().execute(tableName, GlobalClass.email, GlobalClass.date);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In your AsyncTask:
class CreateMovementAsyncTask extends AsyncTask<String,Void,Void>{
protected Void doInBackground(String... arg0) {
DBFunctions DBFunction = new DBFunctions();
try {
JSONObject jObjComment = new JSONObject();
jObjComment.put("out_user", LoginActivity.name);
jObjComment.put("out_email", arg0[1]); //use varargs instead
jObjComment.put("out_date", arg0[2]); //use varargs instead
//String json = DBFunction.create_movement(GlobalClass.tablename,jObjComment.toString());
String json = DBFunction.create_movement(arg0[0], jObjComment.toString());
Log.d("CreateMovementAsyncTask", json);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(Void json){
}
}

Related

What prevent me from get this json data

I'm trying to get this array of images in this json bellow and display it in GridView but i don't know why i can't reach that >>>
{
id: 241,
title: "title",
image: "1469370455.jpg",
description: " descriotion ",
images: [
"1469370455.jpg",
"1469370458.jpg",
"1469370481.jpg",
"1469370484.jpg"
]}
and this is my full AyncTask.
private class AysncImages extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
// pDialog = new ProgressDialog(getActivity());
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
// pDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
Log.i(TAG, "array: "+ jsonObj);
GridItem item = new GridItem();
for (int i = 0; i < arrayObj.length(); i++) {
String images = arrayObj.getString(i);
Log.i(TAG, "parseResult: " + jsonObj);
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
// Getting JSON Array node
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
// if (result == 1) {
mGridAdapter.setGridData(mGridData);
//} else {
// Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
// }
//Hide progressbar
mProgressBar.setVisibility(View.GONE);
}
}
In my log i can't reach jsonObj or arrayObj I just can reach jsonStr what I'm missing ?
My Log for jsonStr
the json string you get is [{id:abc,...}]
but a JsonObject should start with {id:abc,...}
maybe you try to remove the '[' and ']' at the end of string in order to get the object
as start with '[' should be an array

How to get Multiple return value From JSON in Android

I have received a string value from JSON, but when I add that JSON value to a JSON array it gives an error stating that it can not convert String value to JSONArray. Please help me.
In the response there are a 3 values in "Value"
protected class AsyncMenuRate extends
AsyncTask<ForGettingRate, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected void onPostExecute(JSONObject objects) {
try {
//String ss= objects.getString("Value").;
JSONArray jarray=objects.getJSONArray("Value");
//jarray = new JSONArray(ss);
for (int i = 0; i < jarray.length(); i++) {
jsonObj = jarray.getJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(DisplayActivity.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
This is a function that I have return value:
String menuTotal = "0";
String item_rate;
public String MenuRate(int t_id, String menunameoflist) {
if (dbConnection.State.ToString() == "Closed") {
dbConnection.Open();
}
if (db.ChkDb_Value("select * from table_status where table_type='" + "A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select rate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else if (db.ChkDb_Value("select * from table_status where table_type='" + "Non A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select non_ACrate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else
item_rate = db.getDb_Value("select driverRate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
//menuRate = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return item_rate;
}
This is the JSON format:
{
"name": "MenuRate",
"parameters": [
{
"name": "t_id",
"type": "int32"
},
{
"name": "menunameoflist",
"type": "string"
}
],
"returnvalue": "string"
}
This is function that I have get a response from JSON:
public JSONObject MenuRate(int t_id, String menunameoflist) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuRate");
p.put("t_id",mapObject(t_id));
p.put("menunameoflist",mapObject(menunameoflist));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
First your MenuRate method returns String not JSONObject. So you had to get that as String and convert it into JSONObject, as shown below.
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
String jsonString = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
return new JSonObject(jsonString);
} catch (Exception | JsonException e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
Don't forgot to add the JsonException, no problem some how it will ask to add the exception.
Now the string value is converted to JSON, so now you can fetch the values and while fetching use opt instead of get like optJsonArray("key") instead of getJsonArray("key") by this way we will get null value instead of exception, if the key is not present in the JSON.
Now coming to the "value" key access in your JSON response. Below is the JSON value which you have provided,
{
"name": "MenuRate",
"parameters": [{
"name": "t_id",
"type": "int32"
}, {
"name": "menunameoflist",
"type": "string"
}],
"returnvalue": "string"
}
In your question you have mentioned that you need access a json array with the key "Value". But in this there is no array with key "Value". So the below code will explain you how to access the "name" string value and "parameters" Json array.
try {
//Name String value...
String name = objects.optString("name");
//Parameter Json Array...
JSONArray parameterarray =objects.optJSONArray("parameters");
for (int i = 0; i < parameterarray.length(); i++) {
JsonObject jsonObj = parameterarray.optJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope this is helpful :)

Cancelling an Async Task In Android

i am trying to cancel an async task after a period of time. i have searched and found a lot of questions about this and all having the same answer like what i am doing below.
problem: after calling cancel, the webservice does not seem to cancel because it never reaches the onPostExecute.
please any help will be appreciated.
what i have tried:
after a certain period of time i call
class TimeOut that takes an asyncTask as its argument and performs the below:
if (task.getStatus() == AsyncTask.Status.RUNNING )
{task.cancel(true);}
if(task.isCancelled()==true)
{
Log.e(TAG,"TASK IS CANCELLED");
}
and in my async class
#Override
protected void onCancelled() {
webServiceError=true; //when timeout change it to true.(default false)
Toast.makeText(context, R.string.webserviceDownloadUserDataError, Toast.LENGTH_LONG).show();
if (pd.isShowing()) {
pd.dismiss();
}
super.onCancelled();
}
#Override
protected String doInBackground(String... params) {
int paramsTracker = 0;
webServiceError = false;
while(webServiceError==false) {
HttpClient httpclient = new DefaultHttpClient();
String url = params[paramsTracker];
paramsTracker = paramsTracker + 1;
HttpPost httppost = new HttpPost(url);
int paramsCount = params.length;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(paramsCount);
for (int i = 0; i < (paramsCount - 1) / 2; i++) {
Log.d(TAG, "parameters: " + params[paramsTracker] + " - " + params[paramsTracker + 1]);
nameValuePairs.add(new BasicNameValuePair(params[paramsTracker], params[paramsTracker + 1]));
paramsTracker = paramsTracker + 2;
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute http post request, call web service
response = httpclient.execute(httppost);
}
catch (Exception e) {
webServiceError = true;
Log.e(TAG, e.toString());
try {
AppLogging(TAG, "Error in calling web service " + e.toString(), LogFileName.ErrorLogFilename);
} catch (Exception a) {
}
}
if (webServiceError == false) {
int CNT = 0;
try {
String query = "SELECT COUNT(*) AS CNT FROM TASKS";
Cursor cursor = MainActivity.myDataBase.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
CNT = Integer.parseInt(cursor.getString(cursor.getColumnIndex("CNT")));
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
Log.e(TAG, e.toString());
try {
AppLogging(TAG, "Error in Database error getting task count " + e.toString(), LogFileName.ErrorLogFilename);
} catch (Exception a) {
}
}
if (CNT == 0) {
String webServiceResponse = "";
try {
Log.d(TAG, "Getting web service response");
// get web service response
HttpEntity entity = response.getEntity();
String content;
content = EntityUtils.toString(entity);
// Log.d(TAG, "content: "+ content);
// parse XML response
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(content));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("string");
Element line = (Element) nodes.item(0);
webServiceResponse = getCharacterDataFromElement(line);
String patternForON = "SET IDENTITY_INSERT \\[.*?\\] O?((N)|(FF))\\s*?;";
Pattern rForON = Pattern.compile(patternForON);
Matcher mForON = rForON.matcher(webServiceResponse);
String webServiceResponseWithOutIdentityInsert = mForON.replaceAll("");
String patternForInsert = "\\bINSERT (?!INTO)";
Pattern rForInsert = Pattern.compile(patternForInsert);
Matcher mForInsert = rForInsert.matcher(webServiceResponseWithOutIdentityInsert);
String webServiceResponseWITHOUTINSERTALONE = mForInsert.replaceAll("INSERT INTO ");
String webServiceResponsePURIFIED = webServiceResponseWITHOUTINSERTALONE.replaceAll(";;", ";");
Log.d(TAG, "content: " + webServiceResponsePURIFIED);
///////////END OF for removing queries that are not applicable in SQLITE
//FOR SPLITTING THE QUERIES AND PLACING EACH AT AN INDEX IN contentArray ARRAY
//String contentArray [] = webServiceResponse.split(";");
String contentArray[] = webServiceResponsePURIFIED.split(";");
Log.d(TAG, "contentArray length" + contentArray.length + ""); //GETS THE NUMBER OF QUERIES
pd.setMax(contentArray.length); //SETTING THE PROGRESS DIALOG (MAX PROGRESS)
for (int i = 0; i < contentArray.length; i++) {
// add the downloaded data to the local database
String query = contentArray[i];
try {
AppLogging(TAG, "Queries Downloaded splitted and purified\n query " + i + " :" + contentArray[i], LogFileName.LogFilename);
} catch (Exception l) {
}
Log.d(TAG, "query: " + query);
// if query contains "getdate()" replace with DATETIME('now'), to render the query executable in sqlite
query = query.replace("GETDATE()", "DATETIME('now')");
try {
MainActivity.myDataBase.execSQL(query); //EXECUTE QUERY
} catch (Exception e) {
Log.e(TAG, e.toString());
try {
AppLogging(TAG, "Error in performing query: " + query + "\nError: " + e, LogFileName.ErrorLogFilename);
} catch (Exception a) {
}
}
//Log.d("Initialize database, HTTPRequestGetUserData ", query);
publishProgress();
}
} catch (Exception e) {
webServiceError = true;
Log.e(TAG, e.toString());
try {
AppLogging(TAG, "Error: " + e.toString(), LogFileName.ErrorLogFilename);
} catch (Exception a) {
}
}
}
}
if (isCancelled()) return "0";
}
return "1";
}
As per Android AsyncTask documents, after calling cancel() on AsyncTask it won't call onPostExecute() instead it will call onCancelled(). So the flow is desired.
Now as per documentation here in, your code
#Override
protected String doInBackground(String... params) {
while(webServiceError=false) {
.....//calling webservice
if (isCancelled()) return "0";
}
return "1";
}
And now your onCancelled() looks like, with String parameters
#Override
protected void onCancelled(String object) { // Here object should be 0
webServiceError=true; //when timeout change it to true.(default false)
Toast.makeText(context, R.string.webserviceDownloadUserDataError, Toast.LENGTH_LONG).show();
if (pd.isShowing()) {
pd.dismiss();
}
super.onCancelled();
}
Now in this method argument object will be 0. And don't worry both methods onPostExecute() and onCancelled() will run on Main UI thread.
Now what I suggest you is, create a private method which you want to execute from onPostExecute() and onCancelled() with String parameters.
When you cancel a AsyncTask it will never hit the OnPostExecute procedure. It is mentioned here in the API Doc:
http://developer.android.com/reference/android/os/AsyncTask.html
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

Android inserting value in database in background

I am using asyntask to enter value in database. in do in backgroud method i am calling this method.
private void callLogin() {
GetDataFromApi getDataFromApi = new GetDataFromApi(url);
if (!isTableFalse) {
Log.e("MAI A GAAYA SYNCRONISE DATA BASE MAI", "HA MAI AYA");
String message =
getDataFromApi.postSignIn().toString().trim();
syncroniseDatabase(message);
populateChurchListOnValidating
.populateChurchList(parseJsonToArrayList());
} else {
try {
loginValue =
Integer.parseInt(getDataFromApi.postSignIn());
Log.e("Login VAlue", "" + loginValue);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
}
}
and my syncroniseDatabase(message) is like this
private void syncroniseDatabase(String mesString) {
Log.e("URL IN SYNCRONISATION", ""+ url);
try {
InsertTable insertTable = new InsertTable();
JSONObject jsonObject = new JSONObject(mesString);
insertTable.addRowforMemberTable(jsonObject.getString(
RegistrationAppConstant.MEMBER_ID),
jsonObject.getString(RegistrationAppConstant.CLIENT_ID),
jsonObject.getString(RegistrationAppConstant.FIRSTNAME),
jsonObject.getString(RegistrationAppConstant.SURNAME),
jsonObject.getString(RegistrationAppConstant.EMAIL_ID),
jsonObject.getString(RegistrationAppConstant.PASSWORD));
Log.e("Inserting Data DONE", "" + "Done");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and my class forInsertTable is like this
public class InsertTable {
public void addRowforMemberTable(String memberID,
String clientID, String
firstName,String surName, String emailIDString, String passWordString)
{
Log.e("NAME", "" + memberID + " " + clientID + " " + firstName + " "
+ surName + " " + emailIDString + " " +
passWordString);
ContentValues contentValue = new ContentValues();
contentValue.put(AppConstant.MCM_MEMBER_MEMEBER_ID, memberID);
contentValue.put(AppConstant.MCM_MEMBER_CLIENT_ID, clientID);
contentValue.put(AppConstant.MCM_MEMBER_FIRST_NAME, firstName);
contentValue.put(AppConstant.MCM_MEMBER_LAST_NAME, surName);
contentValue.put(AppConstant.MCM_MEMBER_EMAIL_ID, emailIDString);
contentValue.put(AppConstant.MCM_MEMBER_PASSWORD, passWordString);
Log.e("Cotent value", "" + contentValue);
try {
SplashActivity.databaseHelper.insertInToTable(
SplashActivity.databaseHelper.getWritableDatabase(),
AppConstant.MEMBER_TABLE_NAME,
contentValue);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
this is my json String
[{"MemberId":77,"ClientId":37,"FirstName":"John","SurName":"Banian","Address1":null,"Address2":null,"Street":null,"Town":null,"City":null,"County":null,"State":null,"Country":null,"PostCode":null,"Mobile":null,"HomeTelephone":null,"WorkTelephone":null,"EmailId":"jbunian#yahoo.com","ConfirmEmailId":null,"Password":"123","Age":null,"Sex":null,"Profession":null,"MartialStatus":null,"Nationality":null,"Children":null,"ChurchMembershipId":null,"SecurityQuestion":null,"SecurityAnswer":null,"IsApproved":null,"IsLockedOut":null,"CreateDate":null,"LastLoginDate":null,"LastPasswordChangedDate":null,"LastLogOutDate":null,"FailedPasswordAttemptDate":null,"FailedPasswordAttemptWindowStart":null,"FailedPasswordAnswerAttemptCount":null,"FailedPasswordAnswerAttemptWindowStart":null,"Comment":null,"Active":null,"IsAuthToApproveNewMember":null,"Record_Created":null,"Record_Updated":null,"LastUpdated_LoginUserID":null,"LastUpdated_WindowsUser":null,"ClientAdminEmailId":null,"EmailListForApproval":null,"AppRegistrationStatus":null,"MemberEmailMessage":null,"AdminEmailMessage":null,"PhysicalDeviceId":null,"DeviceOS":null,"DeviceIdFromGCMorAPNS":null,"DeviceType":null}]
but my code will not executing after this line and hence i am not able to insert value.I have bold the log after which its not executing.please tell why its not executing?
Problem is that you tring to get values from JSONObject, but in reality it's JSON array. (json string starts with [.
Try to do something like this:
JSONArray jsonArray = new JSONArray(mesString);
JSONObject jsonObject = jsonArray.get(0);
insertTable.addRowforMemberTable(jsonObject.getString(RegistrationAppConstant.MEMBER_ID),
jsonObject.getString(RegistrationAppConstant.CLIENT_ID),
.....
.....

How to Pass SQLite Table values row wise into JSON?

Hi I pass the Data base values into webservices. but it passing only resent entry valules only. I need to pass all rows one by one into JSON.
Can any one help me with sample code.
SQLite in DB
Cursor cursor;
cursor = myDataBase.rawQuery(" SELECT " + VENDORID + " FROM " + VENDORINFO_TABLE
+ " WHERE " + CATEGORYID + " = " + id,null);
while (cursor.moveToNext())
{
id = cursor.getInt(cursor.getColumnIndex(VENDORID));
// your JSON put Code
JSONObject jsMain = new JSONObject();
try {
jsMain.put("email", id);
return jsMain.toString();
} catch (JSONException e) {
e.printStackTrace();
return "";
}
}
cursor.close();
check below code try this way. this is just advice for you.
Cursor cus = db.selectAll_delete();
JSONObject jon1 = new JSONObject();
JSONArray jaa = new JSONArray();
int i = 0;
try {
if (cus.moveToFirst()) {
do {
String a = cus.getString(1);
// Toast.makeText(this, ""+ a,
// Toast.LENGTH_LONG).show();
JSONObject job_get = getData_b(a);
jaa.put(i, job_get);
i++;
} while (cus.moveToNext());
}
jon1.accumulate("details", jaa);
} catch (Exception e) {
// TODO: handle exception
}
if (cus != null && !cus.isClosed()) {
cus.close();
}
String js = jon1.toString();
send_to_server(js);
Log.d("test json", "" + js);
method getData_b();
private JSONObject getData_b(String a) {
// TODO Auto-generated method stub
Cursor cus = db.fetchRow(a);
JSONObject job = new JSONObject();
try {
if (cus.moveToFirst()) {
do {
job.put("B", cus.getInt(1));
job.put("I", cus.getString(2));
job.put("O", cus.getString(3));
job.put("D", cus.getString(4));
job.put("D u", cus.getString(5));
job.put("L", cus.getString(6));
job.put("B", cus.getString(7));
job.put("A", cus.getString(8));
job.put("K", cus.getString(9));
job.put("A", cus.getString(10));
job.put("Time", cus.getString(11));
job.put("Upd", cus.getString(12));
job.put("Deleted", cus.getString(13));
} while (cus.moveToNext());
}
} catch (Exception e) {
// TODO: handle exception
}
return job;
}

Categories

Resources