I am trying save the data's which i get from API and my function is as below
try {
// Simulate network access.
mNetworkSubscription = NetworkRequest.performAsyncRequest(api.getPatientsData(tenantID), (data) -> {
// Update UI on main thread
try {
// long pat_id = 0;
if(data != null) {
if(data.getAsJsonObject().get("error") != null){
publishResults("getPatientsData",STATUS_ERROR, null);
}
if (data != null && data.get("result") != null && data.get("result").toString() != "false") {
Realm realm = Realm.getDefaultInstance();
JsonParser parser = new JsonParser();
// realm.beginTransaction();
// realm.where(Patient.class).findAll().deleteAllFromRealm();
//realm.commitTransaction();
try {
JsonArray casesJsonArray = data.get("result").getAsJsonArray();//parser.parse(data.get("result").getAsJsonObject().toString()).getAsJsonArray();
Log.v(Constants.TAG,"PatientJsonArray: "+casesJsonArray);
if(casesJsonArray.size() > 0) {
Patient patientRecord = new Patient();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
for (int i = 0; i < casesJsonArray.size(); i++) {
try {
JsonObject jsonObject = (JsonObject) casesJsonArray.get(i);
Log.e(Constants.TAG, "execute: jsonObject "+jsonObject);
Log.e(Constants.TAG, "execute: id "+id);
if(realm.where(Patient.class).max("id") != null) {
id = realm.where(Patient.class).max("id").intValue();
Log.e(Constants.TAG, "execute:getPatientsData : In DataSync: " + id);
}
Log.e(Constants.TAG, "execute: jsonObject "+jsonObject);
Log.e(Constants.TAG, "execute: id "+pat_id);
patientRecord.setId(id + 1);
patientRecord.setTenantID(jsonObject.get("tenant_id").getAsLong());
patientRecord.setPatientID(jsonObject.get("patient_id").getAsLong());
patientRecord.setFirstName(jsonObject.get("first_name").getAsString());
patientRecord.setLastName(jsonObject.get("last_name").getAsString());
patientRecord.setPatientWeight(jsonObject.get("patient_weight").getAsString());
patientRecord.setPatientAge(jsonObject.get("patient_age").getAsString());
patientRecord.setGender(jsonObject.get("gender").getAsString());
patientRecord.setStreetAddress(jsonObject.get("street_address").getAsString());
patientRecord.setArea(jsonObject.get("area").getAsString());
patientRecord.setCity(jsonObject.get("city").getAsString());
patientRecord.setZipcode(jsonObject.get("zipcode").getAsString());
patientRecord.setState(jsonObject.get("state").getAsString());
patientRecord.setEmail(jsonObject.get("email").getAsString());
patientRecord.setEnqNumber(jsonObject.get("alternate_number").getAsString());
patientRecord.setEnqName(jsonObject.get("enquirer_name").getAsString());
realm.copyToRealmOrUpdate(patientRecord);
}catch (Exception e){
Log.v(Constants.TAG,"caseList Insert exception: "+e.toString());
}
}
}
});
//realm.close();
}
} catch (Exception e) {
Log.v(Constants.TAG, "getPatientsData Exception: " + e.toString());
}
realm.close();
}
}
} catch (Exception e) {
Log.e(Constants.TAG, "getPatientsData() exception: " + e.toString());
publishResults("getPatientsData",STATUS_ERROR, null);
}finally {
publishResults("getPatientsData",STATUS_FINISHED, null);
}
}, (error) -> {
// Handle Error
Log.e(Constants.TAG,"getPatientsData() Error: "+error.getCause());
publishResults("getPatientsData",STATUS_ERROR, null);
});
}catch (Exception e){
Log.e(Constants.TAG,"getPatientsData() Exception: "+e.toString());
publishResults("getPatientsData",STATUS_ERROR, null);
}
But realm.copyOrUpdate(patientRecords);
is not creating/saving a record in local.
First confirm, if there is no exceptions arises?
Try following workarounds,
Check casesJsonArray.size() > 0 must be true. (OR)
Remove realm.close() and try it once. Sometime it will close realm database connection in between the operation. (OR)
Try with hardcoded(dummy) data.
If above doesn't work then post your Patient Model here.
Note: For auto increment of id you can use following code which will reduce no of database calls-
Number num = realm.where(Patient.class).max("id");
int l_id;
if (num == null) {
i_id = 0;
} else {
i_id = num.intValue() + 1;
}
Related
i am trying to change my api from last.fm to deezer and it has been a hurdle for me. please help. below is my code and endpoints.
LAST.fm endpoint : http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=c3bbdcbc61af20f159e92612a56c4122&artist=ynw%20melly&track=suicidal&format=json
Deezer endpoint : http://api.deezer.com/search?q=Alan%20Walker%20-%20Darkside
JAVA CODE
static String parsingImageSong(String data) {
if (!TextUtils.isEmpty(data)) {
try {
JSONObject mJsonObject = new JSONObject(data);
if (mJsonObject.opt("track") != null) {
JSONObject mJsTracks = mJsonObject.getJSONObject("track");
if (mJsTracks.opt("album") != null) {
JSONObject mJsAlbum = mJsTracks.getJSONObject("album");
if (mJsAlbum.opt("image") != null) {
JSONArray mJsImgs = mJsAlbum.getJSONArray("image");
if (mJsImgs.length() > 0) {
for (int j = 0; j < mJsImgs.length(); j++) {
JSONObject mJsImg = mJsImgs.getJSONObject(j);
String sizeImg = mJsImg.getString("size");
if (sizeImg.equalsIgnoreCase("extralarge")) {
return mJsImg.getString("#text").replace("300x300","3000x3000");
}
}
}
}
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
I'm very new in spring development because I'm not a back developer.
I create a back to manage sports training.
I has several times a TransactionSystemException like
Exceptionorg.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
I don't understand what it mean.
I have a class Person who contains a Coordinates object on #OneToOne relation.
Each class have a Service class that has a method of adding.
In PersonService's add method, I call the Coordinates add method which save and return saved object.
This is the add method of PersonClass
public ResponseService<ObjectCreatedModel<UUID, PersonneMorale>> add(PersonneMorale personneMorale) {
String messageErreur = TAG + " - add - ";
StatusReturn status = StatusReturn.ERROR;
String message = null;
ObjectCreatedModel<UUID, PersonneMorale> objectCreatedModel = null;
if (personneMorale != null) {
if (personneMorale.getId() == null) {
personneMorale.setId(UUID.randomUUID());
try {
// Gestion des coordonnees
ResponseService<ObjectCreatedModel<UUID, Coordonnees>> responseServiceCoordonnees =
coordonneesService.add(personneMorale.getCoordonnees());
if (responseServiceCoordonnees.isSuccess() || responseServiceCoordonnees.exist()) {
ResponseService<Coordonnees> responseServiceCoordonneesGet = coordonneesService
.getOne(responseServiceCoordonnees.getObjectReturn().getId());
Coordonnees coordonnees = responseServiceCoordonneesGet.getObjectReturn();
personneMorale.setCoordonnees(coordonnees);
personneMorale = personneMoraleRepository.save(personneMorale);
if (personneMorale != null) {
status = StatusReturn.SUCCESS;
objectCreatedModel = new ObjectCreatedModel<>(personneMorale.getId(), null);
} else {
message = messageErreur + StringResource.E_OCCURRED;
}
} else {
status = responseServiceCoordonnees.getStatusReturn();
message = responseServiceCoordonnees.getMessage();
}
} catch (ConstraintViolationException violationException) {
status = StatusReturn.EXCEPTION;
message = messageErreur + ConstraintViolationReader.extractException(violationException);
} catch (Exception ex) {
status = StatusReturn.EXCEPTION;
message = messageErreur + ex.toString();
}
} else {
message = messageErreur + StringResource.E_MUST_NULL;
}
} else {
message = messageErreur + StringResource.E_SET_PARAMETER;
}
return new ResponseService<>(status, message, objectCreatedModel);
}
This is the add method of CoordinatesService
public ResponseService<ObjectCreatedModel<UUID, Coordonnees>> add(Coordonnees coordonnees) {
StatusReturn status = StatusReturn.ERROR;
String message = "";
ObjectCreatedModel<UUID, Coordonnees> objectCreatedModel = null;
if (coordonnees != null) {
if (coordonnees.getIdCoordonnees() == null) {
try {
coordonnees.setIdCoordonnees(UUID.randomUUID());
Coordonnees coordonneesBase = coordonneesRepository.save(coordonnees);
if (coordonneesBase != null) {
status = StatusReturn.SUCCESS;
objectCreatedModel = new ObjectCreatedModel<>(coordonneesBase.getIdCoordonnees(), null);
} else {
message = StringResource.E_ERROR_OCCURRED;
}
} catch (ConstraintViolationException violationException) {
status = StatusReturn.EXCEPTION;
message = "Exception" + ConstraintViolationReader.extractException(violationException);
} catch (Exception ex) {
status = StatusReturn.EXCEPTION;
message = "Exception" + ex.toString();
}
} else {
message = "Coordonnées" + ErrorsString.ERROR_COMMON_ID_MUST_BE_EMPTY;
}
} else {
message = ErrorsString.ERROR_COORDINATES_MANDATORY;
}
return new ResponseService<>(status, message, objectCreatedModel);
}
The error occurs when CoordinatesService try to save coordinates and pass to the catch (Exception e)
Could you help me to understand what Transaction error mean with an example like my code please ?
After many attempts I have been unable to retrieve all of my tagged photos from the facebook sdk. I would like something similar to what tinder has, but my query only returns 110 photos, of which some repeat, compared to tinder retrieving all 296 tagged photos.
Here is the code for my request:
Bundle paramaters = new Bundle();
paramaters.putString("fields", "source");
paramaters.putInt("limit", 1000);
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + userId + "/photos",
paramaters,
HttpMethod.GET,
graphCallback
).executeAsync();
GraphRequest.Callback graphCallback = new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
try {
if (response.getError() == null) {
JSONObject joMain = response.getJSONObject();
if (joMain.has("data")) {
final JSONArray jaData = joMain.optJSONArray("data");
for (int i = 0; i < jaData.length(); i++) {
JSONObject joImages = jaData.getJSONObject(i);
String url = (String) joImages.get("source");
if (i == 0) {
facebookAlbum.setDisplayUrl(url);
}
facebookAlbum.addImage(url);
albumnListAdapter.notifyDataSetChanged();
}
}
}
GraphRequest nextRequest = response.getRequestForPagedResults(GraphResponse.PagingDirection.NEXT);
if(nextRequest != null) {
nextRequest.setCallback(this);
nextRequest.executeAsync();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};
Every time I called this method it always return null even if the value of userProfile.get("facebookId") is not null.
public String updateProfilePicture() {
String facebookId = null;
if (currentUser.get("profile") != null) {
JSONObject userProfile = currentUser.getJSONObject("profile");
try {
if (userProfile.getString("facebookId") != null) {
facebookId = userProfile.get("facebookId").toString();
} else {
facebookId = null;
}
} catch (JSONException e) {
// handle error
facebookId = null;
}
}
return facebookId;
}
The following code i am using for Getting Friend List From Facebook, I have Session in Another class But Session data comming in this class properly . But after Request for getting Friend list from Facebook. i am getting graphObject {data:[] Just like this .. After that getting JArry Null..
//Class For Getting FacebookUserdata
private void getFacebookUserData() {
Log.d(Utilities.logg, "getFacebookUserData");
//Getting Session information
Log.d(Utilities.logg, "session=" + session);
Request requests;
//Making request for getting Friend list
requests = new Request(session, "me/friends", null, HttpMethod.GET,
new Request.Callback() {
//On Complete Request
public void onCompleted(Response response) {
// threadForUI();
GraphObject graphObject = response.getGraphObject();
FacebookUserDataClass userData = null;
try {
JSONObject json = graphObject.getInnerJSONObject();
//Exit from Dailog
if (json != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mrootInnerInviteFriendsInitiateWars
.setVisibility(RelativeLayout.VISIBLE);
mrootInnerInitiateWars
.setVisibility(RelativeLayout.INVISIBLE);
}
}
//Array for getting data
JSONArray JArray = json.getJSONArray("data");
for (int i = 0; i < JArray.length(); i++) {
if (i == 10) {
mtvFriendLoadingInviteFriend
.setVisibility(TextView.GONE);
setListAdapte(mChoose);
}
//Set Json Object for getting all friends
JSONObject innerObject1 = JArray.getJSONObject(i);
//.get(i);
//Geting Pojo Class
userData = new FacebookUserDataClass();
userData.setUserId((String) innerObject1
.getString("id"));
userData.setUserName((String) innerObject1
.getString("name"));
mFacebookUserDataListFull.add(userData);
}
placeFcaebookList();
mtvFriendLoadingInviteFriend
.setVisibility(TextView.GONE);
// if(Utilities.getSharedPref(Utilities.API_regId,
// "").isEmpty())
// {
// getSelfFacebookProfile();
// }
//Storing data into local database
Utilities.database
.insertIntoFacebookFriendListTable(mFacebookUserDataListFull);
mckbCheckAll.setChecked(true);
checkUncheckAll(mChoose, true);
mbtnRefreshInviteFriend.setEnabled(true);
Utilities.foolFlag = false;
Utilities.saveFriendListOnServer(
mFacebookUserDataListFull,
Utilities.FACEBOOK);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e(logg,
"getUserData EXCEPTION1 " + e.toString());
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
Log.e(logg,
"getUserData EXCEPTION2 " + e.toString());
e.printStackTrace();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
Utilities.errorFlag = true;
// onClickFacebookButton();
}
}
});
pendingRequest = false;
requests.executeAsync();
// Utilities.database
// .insertIntoFacebookFriendListTable(mFacebookUserDataListFull);
// Utilities.foolFlag = false;
// Utilities.saveFriendListOnServer(mFacebookUserDataListFull,
// Utilities.FACEBOOK);
// Log.d(logg, "frnds loding done");
// getFacebookImages();
//Getting Image from the Image Class
new GetFacebookImagesUrl().execute();
}