Can't Edit or Update Room database entries - java

I am building an app where the user can store his/her usernames and passwords. The app has a simple UI. The Main thread has a list of entries, a FAB and a delete all icon on the action bar. My issue is that I am not able to edit and update existing entries.
I have the following code in the onCreate() of my MainActivity.java. When the user holds an entry, it launches the AddEditEntry.java activity. What happens here is that the launched activity does not have the existing entry data in its EditText fields:
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
In my AddEditEntry.java activity, I have the following code in the onClick of the save button. I am adding the new data as extras to the intent:
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
and back in my MainActivity.jav, this is my onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
Entries entry = new Entries(username, hint, password);
viewModel.insert(entry);
Toast.makeText(this, "Entry added!", Toast.LENGTH_SHORT).show();
}else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK){
int id = Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
if (id == -1){Toast.makeText(addEditEntry, "Something went wrong", Toast.LENGTH_SHORT).show();}
Entries entry = new Entries(username, hint, password);
entry.setId(id);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();}
}
When I run the app and try to edit an entry, the Toast message reads "Entry updated!" so it does run that code but the changes do not exist. I tried stopping the app and restarting it to refresh it but it still doesn't exist.
ViewModel.java:
public class EntryViewModel extends AndroidViewModel {
private EntryRepository repository;
private LiveData<List<Entries>> allEntries;
public EntryViewModel(#NonNull Application application) {
super(application);
repository = new EntryRepository(application);
allEntries = repository.getAllEntries();
}
public void insert(Entries entries){repository.insert(entries);}
public void update(Entries entries){repository.update(entries);}
public void delete(Entries entries){repository.delete(entries);}
public void deleteAll(){repository.deleteAllEntries();}
public LiveData<List<Entries>> getAllEntries() {return allEntries;}
}
EntryRepository.java:
public class EntryRepository {
private EntryDAO entryDAO;
private LiveData<List<Entries>> allEntries;
public EntryRepository(Application application){
EntryDatabase database = EntryDatabase.getInstance(application);
entryDAO = database.generateDao();
allEntries = entryDAO.getAllEntries();
}
public void insert(Entries entries){new InsertEntryAsyncTask(entryDAO).execute(entries);}
public void update(Entries entries){new UpdateEntryAsyncTask(entryDAO).execute(entries);}
public void delete(Entries entries){new DeleteEntryAsyncTask(entryDAO).execute(entries);}
public void deleteAllEntries(){new DeleteAllEntriesAsyncTask(entryDAO).execute();}
public LiveData<List<Entries>> getAllEntries(){return allEntries;}
public static class InsertEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private InsertEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.insert(entries[0]);
return null;
}
}
public static class UpdateEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private UpdateEntryAsyncTask(EntryDAO entryDAO){
this.entryDAO = entryDAO;
}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.update(entries[0]);
return null;
}
}
public static class DeleteEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private DeleteEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.delete(entries[0]);
return null;
}
}
public static class DeleteAllEntriesAsyncTask extends AsyncTask<Void, Void, Void>{
private EntryDAO entryDAO;
private DeleteAllEntriesAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Void... voids) {
entryDAO.deleteAllEntries();
return null;
}
}
}
EntryDAO.java:
#Dao
public interface EntryDAO {
#Insert
void insert(Entries entries);
#Update
void update(Entries entries);
#Delete
void delete(Entries entries);
#Query("DELETE FROM entries_table")
void deleteAllEntries();
#Query("SELECT * FROM entries_table")
LiveData<List<Entries>> getAllEntries();
}
Entries.java:
#Entity(tableName = "entries_table")
public class Entries {
#PrimaryKey(autoGenerate = true)
private int id;
private String username, hint, password;
public Entries(String username, String hint, String password){
this.username = username;
this.hint = hint;
this.password = password;
}
public Entries(){}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getHint() {return hint;}
public void setHint(String hint) {this.hint = hint;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
}
This is the onCreate() of my AddEditEntry.java class. I've added the following Toast messages to see if it was receiving the data at all and turns out it doesn't. The Toast messages were empty:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addedit_entry);
usernameEditText = findViewById(R.id.username_field);
passwordEditText = findViewById(R.id.password_field);
hintEditText = findViewById(R.id.hint_field);
passwordABCD = findViewById(R.id.upp_checkbox);
passwordabcd = findViewById(R.id.low_checkbox);
password0123 = findViewById(R.id.num_checkbox);
passwordSymbols = findViewById(R.id.sym_checkbox);
radio4 = findViewById(R.id.four);
radio8 = findViewById(R.id.eight);
radio12 = findViewById(R.id.twelve);
radio16 = findViewById(R.id.sixteen);
Button generatePassword = findViewById(R.id.btn_password_generate);
Button saveEntry = findViewById(R.id.btn_save);
Intent intent = getIntent();
if(intent.hasExtra(EXTRA_ID)){
setTitle("Edit Entry");
usernameEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME));
passwordEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD));
hintEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT));
Toast.makeText(this, "Info Received!!!", Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT), Toast.LENGTH_SHORT).show();
}
else{setTitle("Add Entry");}
generatePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {passwordEditText.setText(generatedPassword());}});
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
}

Do it like this
In your MainActivity.java
....
....
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
entry = entries; // this is very important, entry holds the current edited item
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
// no need to pass the id, it's a autogenerated field
// intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
....
...
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
...
...
} else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK) {
// in an Edit operation, id should not be modified, so, no need to pass this parameter
// int id =
// Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
// entry already exists, so, no need to create a new one
//Entries entry = new Entries(username, hint, password);
//entry.setId(id);
entry.setUsername(username);
entry.setPassword(password);
entry.setHint(hint);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Other remarks...
In your RecyclerViewAdapter.java
// This is not needed. Your list is already created in your Room query
//private List<Entries> entries = new ArrayList<>();
private List<Entries> entries;
In your MainActivity.java
// This is not needed
// AddEditEntry addEditEntry;
....
....
// addEditEntry = new AddEditEntry();

Related

My sharedprefrences not sharing correctly

I have an app where you upload images to my company server
So The user enters their login details, Email, Password and clientID(4 digit code)(in LoginActivity.java) and then this information must be passed to all the other activities, this passed information is then used to build a URL. Now the issue I am having is the Sharedprefrences doesn't share correctly...they either come up as NULL on the url or as just "email" or "password"
The Information is saved correctly in login activity but when i try to pass it to other activities it fails
Login activity here I save the prefrences
public class LoginActivity extends AppCompatActivity implements TextWatcher {
SharedPreferences MyPrefs;
Intent intent;
SharedPreferences.Editor editor;
public static final String PREF_NAME= "MYPREFS";
public static final String ID = "ClientID" ;
public static final String EMAIL = "username" ;
public static final String PASS = "password";
EditText email, password, id;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button buttonOne=findViewById(R.id.button);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent activity2Intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(activity2Intent);
}
});
MyPrefs= getSharedPreferences(PREF_NAME, 0);
editor = MyPrefs.edit();
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
email.setText(MyPrefs.getString(EMAIL,"username"));
password.setText(MyPrefs.getString(PASS,"password"));
id.setText(MyPrefs.getString(ID, "id"));
email.addTextChangedListener(this);
password.addTextChangedListener(this);
id.addTextChangedListener(this);
MyPrefs =getSharedPreferences(EMAIL,0);
MyPrefs =getSharedPreferences(ID,0);
MyPrefs =getSharedPreferences(PASS,0);
intent = new Intent(LoginActivity.this,CameraActivity.class);
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
managePrefs();
}
#Override
public void afterTextChanged(Editable editable) {
managePrefs();
}
private void managePrefs(){
SharedPreferences.Editor editor =MyPrefs.edit();
editor.putString(EMAIL, email.getText().toString().trim());
editor.putString(PASS, password.getText().toString().trim());
editor.putString(ID, id.getText().toString().trim());
editor.apply();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
Camera Activity this is where the shared prefrences must be passed to
public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
private final int PICK_IMAGE=12345;
private final int REQUEST_CAMERA=6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION=5674;
private Bitmap bitmap;
String myURL;
String email;
String clientId;
String pwd;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
My code for calling sharedprefrences
SharedPreferences sharedPreferences = getSharedPreferences(LoginActivity.PREF_NAME, 0);
email = sharedPreferences.getString(LoginActivity.EMAIL, "username");
clientId = sharedPreferences.getString(LoginActivity.ID, "id");
pwd = sharedPreferences.getString(LoginActivity.PASS, "password");
imageView=findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fromCamera:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_ACCESS_PERMISSION);
} else {
getImageFromCamera();
}
break;
case R.id.fromGallery:
getImageFromGallery();
break;
case R.id.upload:
if (bitmap != null)
uploadImageToServer();
break;
}
}
private void uploadImageToServer() {
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
final ProgressDialog pd=new ProgressDialog(CameraActivity.this);
pd.setMessage("Uploading, Please Wait....");
pd.show();
Intent intent = getIntent();
String Item= intent.getStringExtra("Spinner");
String Item2= intent.getStringExtra("Spinner2");
Uri.Builder builder=new Uri.Builder();
builder.scheme("https")
.authority("www.smartpractice.co.za")
.appendPath("files-upload-ruben.asp")
.appendQueryParameter("MyForm", "Yes")
.appendQueryParameter("ClientID",clientId)
.appendQueryParameter("Username", email)
.appendQueryParameter("Pwd", pwd)
.appendQueryParameter("category",Item )
.appendQueryParameter("client",Item2 );
myURL=builder.build().toString();
Toast toast = Toast.makeText(CameraActivity.this, myURL , Toast.LENGTH_LONG);
toast.show();
File imageFile=persistImage(bitmap,currentTimeStamp);
Ion.with(this)
.load(myURL)
.uploadProgressDialog(pd)
.setMultipartFile("SP-LOG", "image/jpeg", imageFile)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
pd.cancel();
Toast.makeText(getApplicationContext(),"Uploaded",Toast.LENGTH_SHORT).show();
}
});
}
private File persistImage(Bitmap bitmap, String name) {
File filesDir=getApplicationContext().getFilesDir();
File imageFile=new File(filesDir, name + ".jpg");
OutputStream os;
try {
os=new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
return imageFile;
}
private void getImageFromCamera() {
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void getImageFromGallery() {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
InputStream inputStream=getContentResolver().openInputStream(data.getData());
bitmap=BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras=data.getExtras();
bitmap=(Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImageFromCamera();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
To store data in shared preference do something like this:
private SharedPreferences.Editor editor = getSharedPreferences(PREF_NAME, MODE_PRIVATE).edit();
editor.putString("email", email);
editor.putString("ID", id);
editor.putString("Pass", password);
editor.apply();
so I'll give you bit of explanation, when you write editor.putString("email", email); it tells editor to put your email against key "email".
Now, if you want to read these values back do it like this:
String email = getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("email", "");
String ID= getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("ID", "");
String password= getSharedPreferences(PREF_NAME, MODE_PRIVATE).getString("Pass", "");
Leme know if you don't understand anything.
getSharedPrerencences(String name, int mode) returns a reference to a shared preferences file name. That is, after the lines
MyPrefs =getSharedPreferences(EMAIL,0);
MyPrefs =getSharedPreferences(ID,0);
MyPrefs =getSharedPreferences(PASS,0);
your variable MyPrefs points to shared preferences file named password, which is probably not what you intended, since later you read from a file named MYPREFS.
Also, you don't need to call editor = MyPrefs.edit(); if you are just reading from the preferences, like you are doing in onCreate. That is why you get the warning that you have suppressed using #SuppressLint("CommitPrefEdits")

Payment to this merchant is not allowed (invalid clientid)

I integrated Paypal in my android app in sandbox mode and everything worked perfectly fine. Now I switched to live mode and changed the client ID in my app as well.
Now this error is displayed when I tried to make a test purchase:
"Payment to this merchant is not allowed (invalid clientid)"
I don't know what to do. I changed the client id in every place from the sandbox id to the live id.
My class where Paypal is initialized when click on a button:
public class EssenActivity extends AppCompatActivity {
private static final String TAG = "Log Essen Activity";
private String kochuiD, preis, preis_ohne_euro, AnfragePortionenS, ungefahreAnkunftS, preisRe;
private EditText anzahlPortionen;
private TextView ungefähreAnkunft;
private Button essenBesätigenBtn;
private FirebaseFirestore firebaseFirestore;
private TextView preisRechner;
private FirebaseAuth mAuth;
public static final int PAYPAL_REQUEST_CODE = 7171;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
.clientId(Config.PAYPAL_CLIENT_ID);
private String amount, amountOhneEuro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_essen);
essenBesätigenBtn = findViewById(R.id.essenBestätigen);
essenBesätigenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processPayment();
}
}
}
private void processPayment() {
amount = preisRechner.getText().toString();
amountOhneEuro = amount.replace("€", "");
PayPalPayment payPalPayment = new PayPalPayment(new BigDecimal(String.valueOf(amountOhneEuro)), "EUR",
"Bezahle das Essen", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(EssenActivity.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payPalPayment);
startActivityForResult(intent, PAYPAL_REQUEST_CODE);
}
#Override
//
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == PAYPAL_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirmation != null) {
try {
String paymentDetails = confirmation.toJSONObject().toString(4);
startActivity(new Intent(EssenActivity.this, PaymentDetails.class)
.putExtra("PaymentDetails", paymentDetails)
.putExtra("PaymentAmount", amountOhneEuro)
.putExtra("Koch Uid", kochuiD)
);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "onActivityResult: wurde gecancelt");
}
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
Toast.makeText(EssenActivity.this, "Ungültig", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
EssenActivity.this.stopService(new Intent(EssenActivity.this, PayPalService.class));
super.onDestroy();
}
}
My Config class:
public class Config {
public static final String PAYPAL_CLIENT_ID ="MY CLIENT ID";
}
My Paymentdetails class:
public class PaymentDetails extends AppCompatActivity {
private static final String TAG = "PAYMENT";
private TextView txtid, txtAmount, txtStatus;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth mAuth;
private DocumentReference docIdRef;
private String kochUid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_details);
txtid = findViewById(R.id.txtId);
txtAmount = findViewById(R.id.txtAmount);
txtStatus = findViewById(R.id.txtStatus);
Intent intent = getIntent();
try {
JSONObject jsonObject = new JSONObject(intent.getStringExtra("PaymentDetails"));
showDetails(jsonObject.getJSONObject("response"), intent.getStringExtra("PaymentAmount"));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showDetails(JSONObject response, String paymentAmount) {
try {
firebaseFirestore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
String uid = mAuth.getCurrentUser().getUid();
if (response.getString("state").equals("approved")) {
DocumentReference documentReference = firebaseFirestore.collection("essen_aktiv_anfrage").document(uid);
Map<String, String> anfrageMap = new HashMap<>();
anfrageMap.put("Id", response.getString("id"));
anfrageMap.put("Status", response.getString("state"));
anfrageMap.put("Betrag", paymentAmount + "€");
//NEU
anfrageMap.put("Anfrage User", uid);
anfrageMap.put("Koch Uid", kochUid);
documentReference.set(anfrageMap, SetOptions.merge())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(PaymentDetails.this, MainActivity.class);
intent.putExtra("Bezahlung war erfolgreich", "approved");
Toast.makeText(PaymentDetails.this, "Bezahlung war erfolgreich", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
} else{
Toast.makeText(PaymentDetails.this, "Bezahlung war nicht erfolgreich", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any help is appreciated. Thank you very much.
Authorization defaults to sandbox unless explicitly set to "live". It needs to be set within the PayPalConfiguration which is used in creation of the oAuth token, and the creation of the APIContext which is used to call the PayPal service.
I had been getting the same error within a live environment, despite it working in sandbox. It is therefore likely that you have missed something.
Change ENVIRONMENT_SANDBOX to ENVIRONMENT_PRODUCTION

Passing an object from the 2nd activity back to main activity using serializable in android

The first block of code below is my main activity in which I created the intent to the second activity. On this activity I am displaying the expense in a list view which for now I have left out as it is not fully implemented. What I simple want to do is launch the second activity and let the user enter in details and press a button to add the activity to the list view.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addExpense) {
Intent intent = new Intent(this, ExpenseActivity.class);
startActivityForResult(intent, 1);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Expense expense = (Expense) data.getSerializableExtra("sampleObject");
Expenses.add(expense);
}
}
}
final Button btnAddExpense = (Button) findViewById(R.id.btnAddExpense);
btnAddExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String amountV = txtAmountVat.getText().toString();
int amountVTwo = Integer.parseInt(amountV);
String amountI = txtAmount.getText().toString();
int amountITwo = Integer.parseInt(amountI);
Expense expense = new Expense(amountITwo, amountVTwo, txtDateOfExpense.getText().toString(), txtDateAdded.getText().toString(), datePaid, paid, txtDes.getText().toString(), imageUri );
Intent intent = new Intent();
intent.putExtra("Expense", expense);
setResult(MainActivity.RESULT_OK, intent);
finish();
}
});
And this is my second activity in which the user enters in data. When i try pass back the expense object the emulator states the app has stopped working. Please could I have some help as I don't know what is causing this problem. This is what my class looks like.
public class Expense implements Serializable {
private int _amount, _amountVat;
private String _dateOfExpense, _dateAdded, _datePaid, _expenseDescription;
private Boolean _paid;
private Uri _imageUri;
public Expense(int amount, int amountVat, String dateOfExpense, String dateAdded, String datePaid, Boolean paid, String expenseDescription, Uri imageUri){
_amount = amount;
_amountVat = amountVat;
_dateOfExpense = dateOfExpense;
_dateAdded = dateAdded;
_datePaid = datePaid;
_paid = paid;
_expenseDescription = expenseDescription;
_imageUri = imageUri;
}
public int get_amount() {
return _amount;
}
public void set_amount(int _amount) {
this._amount = _amount;
}
public int get_amountVat() {
return _amountVat;
}
public void set_amountVat(int _amountVat) {
this._amountVat = _amountVat;
}
public String get_dateOfExpense() {
return _dateOfExpense;
}
public void set_dateOfExpense(String _dateOfExpense) {
this._dateOfExpense = _dateOfExpense;
}
public String get_dateAdded() {
return _dateAdded;
}
public void set_dateAdded(String _dateAdded) {
this._dateAdded = _dateAdded;
}
public String get_datePaid() {
return _datePaid;
}
public void set_datePaid(String _datePaid) {
this._datePaid = _datePaid;
}
public Boolean get_paid() {
return _paid;
}
public void set_paid(Boolean _paid) {
this._paid = _paid;
}
public Uri get_imageUri() {
return _imageUri;
}
public void set_imageUri(Uri _imageUri) {
this._imageUri = _imageUri;
}
public String get_expenseDescription() {return _expenseDescription;}
public void set_expenseDescription(String _expenseDescription) {this._expenseDescription = _expenseDescription;}
}
Much can't be said about your problem without proper log details.
But you can go through these points.
The problem with Serializable approach is that reflection is used and it is a slow process. This method create a lot of temporary objects and cause quite a bit of garbage collection. So, it might be due to this. Try running on a real device & see if it persists.
Alternatively, you can implement Parcelable to your class which is faster than Serializable.

Firebase Google Auth Error

Hello I have been working on an project of an android app so i used firebase android google authentication but when i launch app and login it works fine and after closing app and relaunching it app stucks on white screen please help im posting my file below
googleutil.java
public class GoogleUtil {
public static boolean getBooleanPreference(Context context, String key, boolean defaultValue) {
boolean value = defaultValue;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
value = preferences.getBoolean(key, defaultValue);
}
return value;
}
public static boolean setBooleanPreference(Context context, String key, boolean value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
return editor.commit();
}
return false;
}
}
google.java
public class Google {
private static final int RC_SIGN_IN = 10;
private GoogleApiClient mGoogleApiClient;
private FragmentActivity context;
private OnInfoLoginGoogleCallback mGoogleCallback;
public Google(FragmentActivity context, OnInfoLoginGoogleCallback mGoogleCallback) {
this.context = context;
this.mGoogleCallback = mGoogleCallback;
getConfigDefaultLogin();
}
private void getConfigDefaultLogin() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(context.getString(R.string.default_web_client_id))
// TODO: 25-05-2017 Check With JSON default_web_client_id !!! Important
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage(context /* FragmentActivity */, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
mGoogleCallback.connectionFailedApiClient(connectionResult);
}
}).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
mGoogleCallback.loginFailed();
}
}
}
public void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
context.startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
FirebaseAuth auth = FirebaseAuth.getInstance();
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(context, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
mGoogleCallback.loginFailed();
} else {
mGoogleCallback.getInfoLoginGoogle(acct);
}
}
});
}
public interface OnInfoLoginGoogleCallback {
void getInfoLoginGoogle(GoogleSignInAccount account);
void connectionFailedApiClient(ConnectionResult connectionResult);
void loginFailed();
}
}
and finally implement all these in main activiity
public class MainActivity extends AppCompatActivity implements View.OnClickListener, Google.OnInfoLoginGoogleCallback {
private static final String USER_ROOT = "User";
private static final String KEY_LOGIN = "Key_Login";
private Google mGoogleSign;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
setContentView(R.layout.activity_main);
TextView server_load = (TextView) findViewById(R.id.secure_key);
server_load.setText("Server Secure " + Math.random() + " Key");
firstShow();
if (GoogleUtil.getBooleanPreference(this, KEY_LOGIN, false)) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
initViews();
}
private void firstShow() {
SharedPreferences sharedPreferences = getSharedPreferences("app", MODE_PRIVATE);
if (sharedPreferences.getBoolean("isFirst", true)) {
Intent intent = new Intent(MainActivity.this, OnboardingActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isFirst", false);
editor.apply();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mGoogleSign.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_trigger:
signInGoogle();
break;
}
}
#Override
public void getInfoLoginGoogle(GoogleSignInAccount account) {
sendUserFirebase();
}
#Override
public void connectionFailedApiClient(ConnectionResult connectionResult) {
addProgressBar(false);
toast("Error Play Services COD" + connectionResult);
}
#Override
public void loginFailed() {
addProgressBar(false);
toast("Login Failed");
}
private void initViews() {
mGoogleSign = new Google(this, this);
Button mBtnGoogleplus = (Button) findViewById(R.id.sign_in_trigger);
mProgressBar = (ProgressBar) findViewById(R.id.sign_in_progress_bar);
mBtnGoogleplus.setOnClickListener(this);
}
private void signInGoogle() {
mGoogleSign.signIn();
addProgressBar(true);
}
private void toast(String mensage) {
Toast.makeText(this, mensage, Toast.LENGTH_LONG).show();
}
private void addProgressBar(boolean flag) {
mProgressBar.setVisibility(flag ? View.VISIBLE : View.GONE);
}
private void sendUserFirebase() {
DatabaseReference referenceUser = FirebaseDatabase.getInstance().getReference().child(USER_ROOT);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
User user = new User();
user.setName(firebaseUser.getDisplayName());
user.setEmail(firebaseUser.getEmail());
user.setPhotoUrl(firebaseUser.getPhotoUrl() == null ? "default_uri" : firebaseUser.getPhotoUrl().toString());
user.setuId(firebaseUser.getUid());
referenceUser.child(firebaseUser.getUid()).setValue(user).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
GoogleUtil.setBooleanPreference(MainActivity.this, KEY_LOGIN, true);
startActivity(new Intent(MainActivity.this, FeedActivity.class));
finish();
} else {
toast("Login Failed Send User, try again.");
}
addProgressBar(false);
}
});
}
}
}
and also i used User.java to send user email to database
User.java
public class User {
private String Name;
private String Email;
private String UID;
private String PhotoURL;
public User() {
}
public User(String name, String email, String uId, String photoUrl) {
this.Name = name;
this.Email = email;
this.UID = uId;
this.PhotoURL = photoUrl;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
this.Email = email;
}
public String getuId() {
return UID;
}
public void setuId(String uId) {
this.UID = uId;
}
public String getPhotoUrl() {
return PhotoURL;
}
public void setPhotoUrl(String photoUrl) {
this.PhotoURL = photoUrl;
}
}
So much code.
As I understood, you need some silent log in in background.
Here You go:
OptionalPendingResult example:
// LogIN pending result
mGoogleApiClientPendingResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (mGoogleApiClientPendingResult.isDone()) {
// There's immediate result available.
// Handle you result here
handleSignInResult(mGoogleApiClientPendingResult.get());
} else {
// There's no immediate result ready, displays some progress indicator and waits for the
// async callback.
mGoogleApiClientPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult result) {
// Handle you result here
handleSignInResult(result);
}
});
}
Main Activity example:
private static final int RC_SIGN_IN = 28;
private static final String RC_SIGN_IN_TAG = "GoogleSignIn";
private GoogleApiClient mGoogleApiClient;
private OptionalPendingResult<GoogleSignInResult> mGoogleApiClientPendingResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Google Log In
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
// Change this for Your needs
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER), new Scope(Scopes.DRIVE_FILE), new Scope(Scopes.PROFILE))
.requestEmail()
.build();
// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
//
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.addApi(Drive.API)
.addScope(Drive.SCOPE_APPFOLDER)
.addScope(Drive.SCOPE_FILE)
.build();
// LogIN pending result
mGoogleApiClientPendingResult = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (mGoogleApiClientPendingResult.isDone()) {
// There's immediate result available.
// Handle you result here
handleSignInResult(mGoogleApiClientPendingResult.get());
} else {
// There's no immediate result ready, displays some progress indicator and waits for the
// async callback.
mGoogleApiClientPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult result) {
// Handle you result here
handleSignInResult(result);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(RC_SIGN_IN_TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
if (acct != null) {
// Do your things here
nameTextView.setText(acct.getDisplayName());
emailTextView.setText(acct.getEmail());
// You can gat methods here - https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount
}
}
}

Passing Parcelable Object between Intents

I am having an issue passing an object I have created in between events. I used the website http://www.parcelabler.com/ to create the parcelable element of the code. The object class is show below: (The Item class is another simple object containing Strings and doubles and has also been made parcelable)
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class Diner implements Parcelable {
private String name;
private ArrayList<Item> itemList = new ArrayList<Item>();
public Diner(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addItem(Item foodItem) {
itemList.add(foodItem);
foodItem.incrementBuyerCount();
}
public double getPrice() {
double total = 0;
for(Item item : itemList) {
total += item.getPrice() / item.getBuyerCount();
}
return total;
}
protected Diner(Parcel in) {
name = in.readString();
if (in.readByte() == 0x01) {
itemList = new ArrayList<Item>();
in.readList(itemList, Item.class.getClassLoader());
} else {
itemList = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
if (itemList == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(itemList);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Diner> CREATOR = new Parcelable.Creator<Diner>() {
#Override
public Diner createFromParcel(Parcel in) {
return new Diner(in);
}
#Override
public Diner[] newArray(int size) {
return new Diner[size];
}
};
}
In my main activity, I have a button which opens an 'Add Diner' activity, when a button is pressed and waits for a result.
private final int SET_REQUEST = 1;
addDinerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddDinerActivity.class);
startActivityForResult(intent, SET_REQUEST);
}
});
The Add Diner activity is opened, the user enters a String in a Diner Name EditText which is used the create a new Diner object and returns to the main activity when an OK button is pressed.
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
Diner newDiner = new Diner(dinerNameEditText.getText().toString());
intent.putExtra("newDiner", newDiner);
setResult(RESULT_OK, intent);
finish();
}
});
Finally the Diner object is received and added to an array in the main activity:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode == SET_REQUEST) {
Diner newDiner = getIntent().getParcelableExtra("newDiner");
dinerList.add(newDiner);
}
}
}
Unfortunately my code is crashing when I try to save the Diner object and pass it to the main activity, can anyone see why this is?
Use data third parameter of onActivityResult method instead of getIntent() for getting data from Intent which is sent from Activity which is started using startActivityForResult :
Diner newDiner = data.getParcelableExtra("newDiner");

Categories

Resources