Android inserting value in database in background - android

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),
.....
.....

Related

How to parse JSON data in volley liabrary?

I want parse JSON response.I am unable to parse response.It shows org.json.JSONException: No value for String Response this error.
Here is my code ` public void onResponse(JSONObject response) {
Log.d("TAG", "Details:" + response);
responseTV.setText("String Response : " + response.toString());
try {
JSONObject jsonObject = response.getJSONObject("String Response"+response);
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}`
I guess you use Volley JsonObjectRequest, so you need to convert the response to a String and parse it to a JSONObject, like this:
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
response -> {
try {
JSONObject jsonObject = new JSONObject(response.toString());
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}, error -> {}
);
try {
JSONObject jsonObject = response.getJSONObject(response);
strcode = jsonObject.getString("responseCode");
strtext = jsonObject.getString("responseText");
strname = jsonObject.getString("personName");
Log.i("TAG","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
before you will do parsing , you will check all value receice by API exp :- responseCode, responseText, personName ( https://jsonlint.com/ ) , if all value you recived , check its in correct format , after that you will parse the data
you also use this , its will handle the JsonException
jsonObject.optString("responseText");
Solved this problem with this code
public void onResponse(JSONObject response) {
Log.d("TAG", "Details:" + response);
responseTV.setText("String Response : " + response.toString());
try {
// JSONObject jsonObject = response.getJSONObject(response.toString());
strcode = response.getString("responseCode");
strtext = response.getString("responseText");
strname = response.getString("personName");
Log.i("TAGParser","parseData:"+strname);
response_code.setText("" +strcode);
response_text.setText("" +strtext);
person_name.setText("" +strname);
} catch (JSONException e) {
Log.d("TAG", "profile: " + e);
}
}

Does not display incoming data with response

I am writing an application for android and using the volley library. I need to write the received data into TextResult. How to do it?
private void jsonParse() {
String url = "https://api.apixu.com/v1/current.json?key=...&q=Paris";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject location = jsonArray.getJSONObject(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
Json response example
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Use this piece of code.
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response.getJSONObject("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray location = jsonObject.getJSONArray(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Its not a JSONArray its a JSONObject.
First get the location from JSONObject.
String location_value=response.get("location");
JSONObject location=new JSONObject(location_value);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");

AsyncTask with PHP/MySql doesnt work properly

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){
}
}

message NeedPermission when get token code

I use the following snippet to get token:
private class task extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
Bundle appActivities = new Bundle();
appActivities.putString(
GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
Constants.ADD_ACTIVITY_SCHEME + " "
+ Constants.BUY_ACTIVITY_SCHEME);
String serverClientID = "My_Client_Id";
String scopes = "oauth2:server:client_id:" + serverClientID
+ ":api_scope:" + Scopes.PLUS_LOGIN + " "
+ Scopes.PLUS_PROFILE;
String code = null;
try {
code = GoogleAuthUtil.getToken(MainActivity.this, // Context
// context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (IOException transientEx) {
code = "Loi 1";
} catch (UserRecoverableAuthException e) {
code = "Loi 2: "+e.getMessage();
} catch (GoogleAuthException authEx) {
code = "Loi 3";
} catch (Exception e) {
throw new RuntimeException(e);
}
return code;
}
#Override
protected void onPostExecute(String token) {
showToast(token);
}
}
I execute this line of code in onConnected method:
new task.execute();
UserRecoverableAuthException occur and my toast show message: "NeedPermission".
How can i fix it?
Have your added the following permission in your manifest?
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
here is the working code for me!
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
String accountName = mPlusClient.getAccountName();
// Get user's information
task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String token = null;
try {
token = GoogleAuthUtil.getToken(MyNetwork.this,
mPlusClient.getAccountName(), "oauth2:"
+ Scopes.PROFILE);
Log.i("TAG", "token" + token);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
Log.e(TAG, e.toString());
Intent recover = e.getIntent();
startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
} catch (GoogleAuthException authEx) {
Log.e(TAG, authEx.toString());
}
return token;
}
#Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
mHandler.sendEmptyMessage(STOP_PROGRESS);
getProfileInformation(token);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler.sendEmptyMessage(SHOW_PROGRESS);
}
};
task.execute();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG)
.show();
}
and i am getting user information like the following.
/**
* Fetching user's information name, email, profile pic
* */
private void getProfileInformation(String mToken) {
String mAccessToken = mToken == null ? "" : mToken;
String mProfileId = "";
String mProfileName = "";
String mImageUrl = "";
String mSecretKey = "";
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
txtGooglePlus.setText(currentPerson.getDisplayName());
mProfileName = currentPerson.getDisplayName();
mImageUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + mProfileName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + mImageUrl);
mProfileId = currentPerson.getId();
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
It is working fine for me. Tested. Check and feel free to ask if there is any issue.

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