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;
}
Related
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.)
Here is some part of my main activity
MainActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp_country = (Spinner) findViewById(R.id.spin_country);
sp_operator = (Spinner) findViewById(R.id.spin_operator);
sp_prod = (Spinner) findViewById(R.id.spin_prod);
sp_voc = (Spinner) findViewById(R.id.spin_voc);
logoo = (ImageView) findViewById(R.id.b_logo);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
/*-----------Check if Wifi Connection----------------------*/
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
finish();
Toast.makeText(getApplicationContext(),
"INTERNET CONNECTION NOT PRESENT", Toast.LENGTH_SHORT)
.show();
}
}
String data = "";
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("785", data));
try {
CustomHTTPClient.executeHttpGet("785");
} catch (Exception e1) {
e1.printStackTrace();
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHTTPClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
JSONArray jArray = new JSONArray(result);
name = new String[jArray.length() + 1];
c_id = new String[jArray.length()];
/*----set default value in spinner----*/
name[0] = "Select Country";
// end
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
// Log.i("tagconvertstr", "[" + data + "]");
name[i + 1] = json_data.getString("c_name");
c_id[i] = json_data.getString("c_id");
Log.d("id is", "" + c_id[i]);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
dataAdapter1 = new ArrayAdapter<String>(
getApplicationContext(), R.layout.spinner_item, name);
dataAdapter1.setDropDownViewResource(R.layout.spinner_item);
sp_country.setAdapter(dataAdapter1);
} catch (Exception e) {
Log.e("log_tag", "Error in Display!" + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
sp_country.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long ii) {
int aa = sp_country.getPositionForView(view);
long id = sp_country.getSelectedItemId();
String stringpf = String.valueOf(id);
Toast.makeText(getApplicationContext(), "" + stringpf, 0)
.show();
}
i'm getting id for all items of sp_country from sql databases.. in the case i have this type of data
c_id | c_name
1 | A
2 | B
4 | C
5 | F
i want to use c_id to get items from databases for next spinner similarly so on for next spinner use previous db item id of spinner.....
i am using the code below to generate a crash file, the file is created at parse.com but it is empty.
any idea why?
Another problem is that "ACRA.DEFAULT_REPORT_FIELDS;" has an error, default report fields is not available.
public class LocalSender implements ReportSender {
private final Map<ReportField, String> mMapping = new HashMap<ReportField, String>() ;
private FileOutputStream crashReport = null;
private Context ctx;
public LocalSender(Context ct) {
ctx = ct;
}
public void send(CrashReportData report) throws ReportSenderException {
final Map<String, String> finalReport = remap(report);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
Log.i("hcsh","Report send");
try {
Set set = finalReport.entrySet();
Iterator i = set.iterator();
String tmp;
while (i.hasNext()) {
Map.Entry<String,String> me = (Map.Entry) i.next();
tmp = "[" + me.getKey() + "]=" + me.getValue();
buf.write(tmp.getBytes());
}
ParseFile myFile = new ParseFile("crash.txt", buf.toByteArray());
myFile.save();
ParseObject jobApplication = new ParseObject("AppCrash");
jobApplication.put("MyCrash", "app name");
jobApplication.put("applicantResumeFile", myFile);
try {
jobApplication.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (FileNotFoundException e) {
Log.e("TAG", "IO ERROR",e);
}
catch (IOException e) {
Log.e("TAG", "IO ERROR",e);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Map<String, String> remap(Map<ReportField, String> report) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final Map<String, String> finalReport = new HashMap<String, String>(
report.size());
for (ReportField field : fields) {
if (mMapping == null || mMapping.get(field) == null) {
finalReport.put(field.toString(), report.get(field));
} else {
finalReport.put(mMapping.get(field), report.get(field));
}
}
return finalReport;
}
}
There is no such constant as ACRA.DEFAULT_REPORT_FIELDS. You are looking for ACRAConstants.DEFAULT_REPORT_FIELDS
ACRA.DEFAULT_REPORT_FIELDS constant value is in acra-4.3.0 version ...
if you are using acra-4.5.0 version ACRA you will get this error "DEFAULT_REPORT_FIELDS cannot be resolved or is not a field" .
try to use acra-4.5.0 version and then use following code
// Extract the required data out of the crash report.
String reportBody = createCrashReport(report);
/** Extract the required data out of the crash report. */
private String createCrashReport(CrashReportData report) {
// I've extracted only basic information.
// U can add loads more data using the enum ReportField. See below.
StringBuilder body = new StringBuilder();
body.append(
"Device : " + report.getProperty(ReportField.BRAND) + "-"
+ report.getProperty(ReportField.PHONE_MODEL))
.append("\n")
.append("Android Version :"
+ report.getProperty(ReportField.ANDROID_VERSION))
.append("\n")
.append("App Version : "
+ report.getProperty(ReportField.APP_VERSION_CODE))
.append("\n")
.append("STACK TRACE : \n"
+ report.getProperty(ReportField.STACK_TRACE));
return body.toString();
}
Don't use following code
////////////////////////
final String reportBody = buildBody(arg0);
private String buildBody(CrashReportData errorContent) {
ReportField[] fields = ACRA.getConfig().customReportContent();
if (fields.length == 0) {
// fields = ACRA.DEFAULT_MAIL_REPORT_FIELDS;
fields = ACRA.DEFAULT_REPORT_FIELDS;
}
final StringBuilder builder = new StringBuilder();
for (ReportField field : fields) {
builder.append(field.toString()).append("=");
builder.append(errorContent.get(field));
builder.append('\n');
}
return builder.toString();
}
Happy Coding....
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),
.....
.....
Following is My Json File:-
"Restaurants":{
"8":{
"Res_name":"Purple Cafe and Wine Bar",
"foodtype":"American, Wine",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"9":{
"Res_name":"Quinn's",
"foodtype":"American, Pubs",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"19":{
"Res_name":"Dahlia Lounge",
"foodtype":"American",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
},
I am Using below code for json parsing:-
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurant = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
System.out.println("mRestaurant is:- " + mRestaurant);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The mRestaurant Value is below:-
{"487":{"state":"WA","Res_name":"SAM Taste","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"332":{"state":"WA","Res_name":"Luna Park Cafe","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"35":{"state":"WA","Res_name":"Restaurant Zoe","longitude":"0","latitude":"0","foodtype":"American, Bar","city":"Seattle"},"
but what is the next step for getting Res_Name, foodtype from above response.
Any Help would be appreciated.
The below code is next step for json parsing.
public void getdata() {
String res = mWebRequest.performGet(Constants.url+ "restaurants.php? action=searchRestaurant&lat=0&lon=0&foodtype="+ mEdttxtSearch.getText().toString() + "&state="+ mEdttxtSearch.getText().toString() + "&city="+ mEdttxtSearch.getText().toString()+ "&devType=Android");
System.out.println("res is:- " + res);
if (res != null) {
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurants = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
if (jsonObj.has("Restaurants")) {
Iterator<Object> keys = mRestaurants.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = mRestaurants.getJSONObject(key);
mRes_Name.add(obj.getString("Res_name"));
mLatitude.add(obj.getString("latitude"));
mLongitude.add(obj.getString("longitude"));
mState.add(obj.getString("state"));
mCity.add(obj.getString("city"));
mFood_Type.add(obj.getString("foodtype"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use the get() method:
String mRestaurant = jsonObj.get("487").get("Res_name");
use gson for the same, as it supports direct conversion from json to java and java to json, please see following link:
Converting JSON to Java