Java update and delete function is giving me 'java.lang.IllegalStateException' - java

I am doing my android project and I am using an external API to connect it with the database. I have done the create and view by id. But when it comes to update and deleteI am getting error as E/Failure message: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $. But I am getting the success message and the the error.
When I delete I am getting this error but when I re build the app the data is deleted. But the update is not working.
This is my external API
//Update fuel details
#PUT("/api/fuel/{id}")
Call<Fuel> updateFuel(#Path("id") int id,#Body Fuel fuel);
//Delete fuel details
#DELETE("/api/fuel/{id}")
Call<Fuel> deleteFuel(#Path("id") int id);
And this is my java class for the update and delete. I have tried for 2 days and still couldn't find a solution for this. Please give me some support. Thank You.
public class ShedFuelUpdateFormActivity extends AppCompatActivity {
EditText fuelType, arrivalTime, arrivalAmount, availableAmount, finishTime;
Button deleteButton, updateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shed_fuel_update_form_screen);
fuelType = findViewById(R.id.fuelType );
arrivalTime = findViewById(R.id.arrivalTime );
arrivalAmount = findViewById(R.id.arrivalAmount );
availableAmount = findViewById(R.id.availableAmount );
finishTime = findViewById(R.id.finishTime );
deleteButton = findViewById(R.id.deleteButton );
updateButton = findViewById(R.id.updateButton );
Intent intent = getIntent();
int fuelId = Integer.parseInt(intent.getStringExtra("fuelId"));
//Get fuel by id
new Handler(Looper.myLooper()).postDelayed(new Runnable() {
#Override
public void run() {
getFuel(fuelId);
}
}, 1000);
//Call delete function
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteFuel(fuelId);
}
});
//Call update function
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveFuel(fuelId, updateFuel());
}
});
}
//Get fuel by id details
public void getFuel(int id){
Call<Fuel> getFuelCall = ApiClient.getFuelServices().getFuelById(id);
getFuelCall.enqueue(new Callback<Fuel>() {
#Override
public void onResponse(Call<Fuel> call, Response<Fuel> response) {
if(response.isSuccessful()){
String fuelTypeData = response.body().getFuelType();
String arrivalTimeData = response.body().getFuelArivalTime();
String arrivalAmountData = String.valueOf(response.body().getArivalAmount());
String availableAmountData = String.valueOf(response.body().getCurrentAvailableAmount());
String finishTimeData = response.body().getFuelFinishedTime();
fuelType.setText(fuelTypeData);
arrivalTime.setText(arrivalTimeData);
arrivalAmount.setText(arrivalAmountData);
availableAmount.setText(availableAmountData);
finishTime.setText(finishTimeData);
}
}
#Override
public void onFailure(Call<Fuel> call, Throwable t) {
Log.e("Failure message",t.getLocalizedMessage());
}
});
}
//Delete fuel details
public void deleteFuel(int id){
Call<Fuel> deleteFuelCall = ApiClient.getFuelServices().deleteFuel(id);
deleteFuelCall.enqueue(new Callback<Fuel>() {
#Override
public void onResponse(Call<Fuel> call, Response<Fuel> response) {
if(response.isSuccessful()){
Toast.makeText(ShedFuelUpdateFormActivity.this, "Fuel deleted successfully", Toast.LENGTH_LONG).show();
Intent intent = getIntent();
String shedId = intent.getStringExtra("shedId");
Intent i = new Intent(ShedFuelUpdateFormActivity.this, ShedOwnerHomeActivity.class).putExtra("shedId",shedId);;
startActivity(i);
}
else{
Toast.makeText(ShedFuelUpdateFormActivity.this, "Failed to delete fuel", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Fuel> call, Throwable t) {
Log.e("Failure message",t.getLocalizedMessage());
}
});
}
//Update fuel
public Fuel updateFuel(){
Fuel fuel = new Fuel();
Intent intent = getIntent();
int shedId = Integer.parseInt(intent.getStringExtra("shedId"));
fuel.setShedId(shedId);
fuel.setFuelType(fuelType.getText().toString());
fuel.setFuelArivalTime(arrivalTime.getText().toString());
fuel.setArivalAmount(Integer.parseInt(arrivalAmount.getText().toString()));
fuel.setCurrentAvailableAmount(Integer.parseInt(availableAmount.getText().toString()));
fuel.setFuelFinishedTime(finishTime.getText().toString());
return fuel;
}
//Save updated fuel
public void saveFuel (int id, Fuel fuel){
Call<Fuel> createFuelCall = ApiClient.getFuelServices().updateFuel(id, fuel);
createFuelCall.enqueue(new Callback<Fuel>() {
#Override
public void onResponse(Call<Fuel> call, Response<Fuel> response) {
if(response.isSuccessful()){
Toast.makeText(ShedFuelUpdateFormActivity.this, "Fuel details updated successfully", Toast.LENGTH_LONG).show();
Intent intent = getIntent();
String shedId = intent.getStringExtra("shedId");
Intent i = new Intent(ShedFuelUpdateFormActivity.this, ShedOwnerHomeActivity.class).putExtra("shedId",shedId);;
startActivity(i);
}
else{
Toast.makeText(ShedFuelUpdateFormActivity.this, "Failed to update fuel", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Fuel> call, Throwable t) {
Log.e("Failure message",t.getLocalizedMessage());
}
});
}
}

Related

REST POST API using with request Query Params in android Studio

I'm using the Retrofit2 Library to consume Rest API with a post request that delivers data in query parameters not in body. Now I want to integrate that api but retrofit stops us from providing data as a query parameters through a post request. It is possible to use a post request with retrofit to deliver data in query parameters?
Here is API Interface
#POST("calculation")
Call<QuestionResponse> calculation(
#Query("height") Double height,
#Query("age") Integer age,
#Query("gender") Boolean gender,
#Query("current_weight") Double current_weight,
#Query("activity_level") Double activity_level,
#Query("user_id") Integer user_id
Here is Question.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentWeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if (rbMale.isSelected()) {
gender= Boolean.valueOf("0");
}
if (rbFemale.isSelected()) {
gender= Boolean.valueOf("1");
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
}
}
public void openHomePage() {
Double userHeight = Double.valueOf(height.getText().toString());
Double userWeight = Double.valueOf(weight.getText().toString());
Integer userAge = Integer.valueOf(age.getText().toString());
if(rgGender.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please Select Gender", Toast.LENGTH_SHORT).show();
return;
}
Intent i=new Intent(BMIquestions.this,ActivityLevel.class);
i.putExtra("age",userAge);
i.putExtra("height",userHeight);
i.putExtra("weight",userWeight);
i.putExtra("gender",gender);
startActivity(i);
Here is Activity_level.java
public class ActivityLevel extends AppCompatActivity implements View.OnClickListener {
ImageButton next;
ImageButton previous;
CardView card1,card2,card3,card4;
SharedPreferenceManager sharedPreferenceManager;
SharedPreferences.Editor editor;
TextView l1,l2,l3,l4;
Double activity_level;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
getSupportActionBar().hide();
next = findViewById(R.id.NextButton);
previous = findViewById(R.id.PreviousButton);
card1 = (CardView) findViewById(R.id.level1);
card2 = (CardView) findViewById(R.id.level2);
card3 = (CardView) findViewById(R.id.level3);
card4 = (CardView) findViewById(R.id.level4);
card1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.55;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.725;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.75;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=2.04;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openHomePage();
}
});
sharedPreferenceManager=new SharedPreferenceManager(getApplicationContext());
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.PreviousButton:
openBMIPage();
break;
}
}
public void openHomePage() {
Integer age= Integer.valueOf(getIntent().getStringExtra("age"));
Boolean gender= Boolean.valueOf(getIntent().getStringExtra("gender"));
Double height= Double.valueOf(getIntent().getStringExtra("height"));
Double weight= Double.valueOf(getIntent().getStringExtra("weight"));
Integer userId= sharedPreferenceManager.getUser().getUserId();
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(height,age,gender,weight,activity_level,userId);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ActivityLevel.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(ActivityLevel.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void openBMIPage() {
Intent intent1 = new Intent(this, BMIquestions.class);
startActivity(intent1);
}
}
After Debugging
Connected to the target VM, address: 'localhost:52230', transport: 'socket'
Disconnected from the target VM, address: 'localhost:52230', transport: 'socket'
How do I fix this?

In my code the if part is working correctly however, the else part is not executing

I am trying to set up OTP verification
I have already tried many possibilities with the if and else, however, it didn't help out.
public class userLogin extends Activity {
EditText phnNum=null, veri = null;
FirebaseAuth au;
Button forgotpass, login;
PhoneAuthProvider.OnVerificationStateChangedCallbacks otp;
String verifyCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userlogin);
login = findViewById(R.id.loginButton);
phnNum = findViewById(R.id.enter_phone);
forgotpass = findViewById(R.id.forgot_pass);
au = FirebaseAuth.getInstance();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((phnNum.getText().toString()).equals("")) {
(Toast.makeText(getApplicationContext(), "Please enter the phone number and proceed to receive an OTP", Toast.LENGTH_SHORT)).show();
}
else{
otp = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verifyCode = s;
(Toast.makeText(getApplicationContext(), "The OTP Code has been send, please verify the code", Toast.LENGTH_SHORT)).show();
}
};
}
}
});
}
public void send_sms (View v){
String i = (phnNum.getText()).toString();
PhoneAuthProvider.getInstance().verifyPhoneNumber(i, 60, TimeUnit.SECONDS, this, otp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent u = new Intent(view.getContext(), otp_verify.class);
startActivity(u);
}
});
}
//SignIn Method
// We will pass value in the method with "PhoneAuthCredential" data-type.
public void SignIn(PhoneAuthCredential credential) {
//" au " is the firebase variable and call the method
au.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
(Toast.makeText(getApplicationContext(), "You have Sign-In Successfully", Toast.LENGTH_SHORT)).show();
}
else{
(Toast.makeText(getApplicationContext(), "Please try again", Toast.LENGTH_SHORT)).show();
}
}
});
}
}
When I log-in with blank EditText, the if part executes but when I enter the phone number it doesn't execute the else part. I expect the when the user enters their phone number the else part should execute.
final String i = (phnNum.getText()).toString();
if ("".equals(i)) {
(Toast.makeText(getApplicationContext(), "Please enter the phone number and proceed to receive an OTP", Toast.LENGTH_SHORT)).show();
} else {
// 1. prepare callback for async call
otp = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verifyCode = s;
(Toast.makeText(getApplicationContext(), "The OTP Code has been send, please verify the code", Toast.LENGTH_SHORT)).show();
Intent u = new Intent(userLogin.this, otp_verify.class);
startActivity(u);
}
};
// 2. execute actual call
PhoneAuthProvider.getInstance().verifyPhoneNumber(i, 60, TimeUnit.SECONDS, userLogin.this, otp);
}
The code snippet prepares callback and uses it on Firebase auth call. When the verification code is actually sent, the onCodeSent called and new activity launched.

Realm database is not updating

Hi friends please help me out i am making chating app with the conversion of text and images Whenever user changes the image in his profile it need to be update in the conversion as well but its not getting updated but whenever i sends a new message then the new image is updating and also i dont set the primary key
Here is below link i had tried nothing worked:
How to update the values in Table using Realm android?
Update mutiple rows in table using Realm in Android
public class Chat_history extends AppCompatActivity {
#BindView(R.id.chat_history_toolbar)
CustomToolbar chat_history_toolbar;
#BindView(R.id.sendmessgae)
CustomEditText sendmessgae;
#BindView(R.id.chat_history_list)
ListView chat_history_list;
Chat_history_Adapter chathisadapter;
RealmResults<Chat_history_pojo> chathistorylist;
Realm chatrealm;
BroadcastReceiver chatreceiver;
public static final String BroadCastAction = "com.parallelspace.parallelspace.Chat_history";
RealmChangeListener chatupdatelisterner = new RealmChangeListener() {
#Override
public void onChange(Object element) {
chathisadapter.addmessage(chathistorylist);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_history);
ButterKnife.bind(this);
Realm.init(getApplicationContext());
setSupportActionBar(chat_history_toolbar);
assert getSupportActionBar() != null;
**chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
RealmQuery<Chat_history_pojo> getLoginData= chatrealm.where(Chat_history_pojo.class).beginGroup().equalTo("receiverid", getIntent().getStringExtra("rid")).endGroup();
RealmResults<Chat_history_pojo> registrationRealm = getLoginData.findAll();
for (Chat_history_pojo chtapojo:registrationRealm) {
chtapojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.copyToRealm(registrationRealm);
}
chatrealm.commitTransaction();**
chathistorylist = chatrealm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
chathisadapter = new Chat_history_Adapter(Chat_history.this, chathistorylist);
chat_history_list.setStackFromBottom(true);
chat_history_list.setTranscriptMode(chat_history_list.TRANSCRIPT_MODE_NORMAL);
chat_history_list.setAdapter(chathisadapter);
/*chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Constant.l("Realm Update Called");
RealmResults<Chat_history_pojo> updatehispojo = chatrealm.where(Chat_history_pojo.class).equalTo("receiverid", getIntent().getStringExtra("rid")).findAll();
for(Chat_history_pojo updatepojo:updatehispojo){
updatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.insertOrUpdate(updatepojo);
chathisadapter.notifyDataSetChanged();
}
}
});*/
sendmessgae.setDrawableClickListener(new DrawableClickListener() {
#Override
public void onClick(DrawablePosition target) {
switch (target) {
case RIGHT:
if (sendmessgae.getText().toString().isEmpty()) {
Constant.t(getApplicationContext(), "Please Enter Message");
} else {
sendmessage();
}
break;
default:
break;
}
}
});
if (getIntent().hasExtra("mtype")) {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
} else {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
}
chat_history_toolbar.Whichonclicked("back", new View.OnClickListener() {
#Override
public void onClick(View view) {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
});
chat_history_toolbar.Whichonclicked("toolbar", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chathisintent = new Intent(getApplicationContext(), Detailed_friend.class);
chathisintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
chathisintent.putExtra("rname", getIntent().getStringExtra("rname"));
chathisintent.putExtra("rimage", getIntent().getStringExtra("rimage"));
chathisintent.putExtra("rid", getIntent().getStringExtra("rid"));
startActivity(chathisintent);
}
});
chat_history_toolbar.Whichonclicked("delete", new View.OnClickListener() {
#Override
public void onClick(View v) {
chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Chat_history_pojo> deleteresults = realm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
deleteresults.deleteAllFromRealm();
}
});
}
});
chatreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(getIntent().getStringExtra("rid"));
chatupdatepojo.setReceiverid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(intent.getStringExtra("msg").replace("$", " "));
chatupdatepojo.setType("text");
if (intent.getStringExtra("type").equals("image")) {
chatupdatepojo.setType("image");
} else if (intent.getStringExtra("type").equals("text")) {
chatupdatepojo.setType("text");
}
chatrealm.commitTransaction();
chatrealm.close();
}
};
IntentFilter intfil = new IntentFilter(BroadCastAction);
registerReceiver(chatreceiver, intfil);
}
#Override
protected void onDestroy() {
unregisterReceiver(chatreceiver);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
chatrealm.addChangeListener(chatupdatelisterner);
Session.pushnotification(getApplicationContext());
}
#Override
protected void onStop() {
super.onStop();
chatrealm.removeChangeListener(chatupdatelisterner);
Session.removepushnotification(getApplicationContext());
}
#OnClick(R.id.camera)
public void camera() {
TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(Chat_history.this)
.setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
#Override
public void onImageSelected(Uri uri) {
try {
Bitmap sendimage = MediaStore.Images.Media.getBitmap(Chat_history.this.getContentResolver(), uri);
sendimages(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("rid"), sendimage);
} catch (IOException e) {
Constant.l(e.toString());
}
}
})
.setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
.create();
bottomSheetDialogFragment.show(getSupportFragmentManager());
}
private void sendimages(String sid, String rid, Bitmap sendbitmap) {
Constant.showloader(Chat_history.this);
String sendumageurl = Constant.psurl + "chatdocument&task=send&sender_id=" + sid + "&reciever_id=" + rid;
Constant.l(sendumageurl);
AndroidNetworking.post(sendumageurl).addBodyParameter("image", Constant.getStringImage(sendbitmap)).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
Constant.l(String.valueOf(response));
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(response.getString("url"));
chatupdatepojo.setType("image");
chatrealm.commitTransaction();
chatrealm.close();
}
} catch (JSONException e) {
Constant.l(e.toString());
Constant.dismissloader();
}
Constant.dismissloader();
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
Constant.dismissloader();
}
});
}
#Override
public void onBackPressed() {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
private void sendmessage() {
String schatsendmesg = Constant.psurl + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("rid") + "&message=" + sendmessgae.getText().toString().replace(" ", "$");
Constant.l(schatsendmesg);
AndroidNetworking.get(schatsendmesg).setOkHttpClient(Constant.okClient()).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setMessage(sendmessgae.getText().toString());
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setType("text");
chatrealm.commitTransaction();
chatrealm.close();
sendmessgae.setText("");
}
} catch (JSONException e) {
Constant.l(e.toString());
}
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
}
});
}
#Override
protected void onResume() {
super.onResume();
Session.pushnotification(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
Session.removepushnotification(getApplicationContext());
}
}
Try this way of updation.
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//Here i am checking the condition
RealmQuery<RegistrationRealm> getLoginData= realm.where(RegistrationRealm.class).equalTo("id",1);
//finding the first set if matches the criteria
RegistrationRealm registrationRealm = getLoginData.findFirst();
//setting the values
registrationRealm.setFirstname(firstname);
registrationRealm.setLastname(lastname);
//Updating the same object with new values
realm.copyToRealm(registrationRealm);
//commiting the current transaction
realm.commitTransaction();
If you need to update all, then get a RealmResults object and iterate through
RealmResults<RegistrationRealm> registrationRealm = getLoginData.findAll();
NOTE:
When using realm.copyToRealm() it is important to remember that only the returned object is managed by Realm, so any further changes to the original object will not be persisted.
Realm reference

In-app Billing unlock button only one time

private Button clickButton;
private Button buyButton;
private static final String TAG =
"InAppBilling";
IabHelper mHelper;
static final String ITEM_SKU = "tips";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buyButton = (Button)findViewById(R.id.buybutton);
clickButton = (Button)findViewById(R.id.clickbutton);
clickButton.setEnabled(false);
String base64EncodedPublicKey =
" "
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " +
result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void button2 (View v)
{
Intent intent = new Intent(getApplicationContext(), vtoriFra
gment.class);
startActivity(intent);
}
public void buttonClicked (View view)
{
clickButton.setEnabled(false);
buyButton.setEnabled(true);
Intent intent = new Intent(getApplicationContext(), purviFragment.class);
startActivity(intent);
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
buyButton.setEnabled(false);
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,
IabResult result) {
if (result.isSuccess()) {
clickButton.setEnabled(true);
} else {
// handle error
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Hi, i have a trouble mit my app. The case is:
I want when the people pay in my app to unlock one button but i want to pay only one thime but when they pay they unlock the button for only one time. Sorry for my bad english. This is my source code
Your code is a bit messy, but this is your flow:
when the user clicks the button you start the purchasing flow
when when purchasing flow ends, you query for the list of purchased items
if the purchased item exists, you consume it
When you consume an item, you "delete" it, so it is no more on the purchased items list. If you want so sell something just once (for example to remove ads) you don't have to consume it.
Your flow should be this:
query for the purchased items
if the list contains the purchase item, disable the button
if the list doesn't contain che purchase item, enable the button
on click, start the purchase flow
when when purchasing flow ends, you query for the list of purchased items
if the purchased item exists, disable the button and provide the extra feature
if the purchased item doesn't exists, the purchase procedure failed
You should read carefully this page:
https://developer.android.com/training/in-app-billing/purchase-iab-products.html

How to get data from getter setter class?

I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}

Categories

Resources