what to use insead of requestCode - java

hello i am trying to make a todo list and i have 2 activities ,i want to open the new activity in two ways
one way is to press the button and the other the recyclerView and they open the same activity but in the first you just add and in the second you update
before you could just insert the requestCode together with the intent like this :
Intent i = new Intent(this, ActivityTwo.class);
startActivityForResult(i, REQUEST_CODE);
but now that startActivityForResult is deprecated i dont't know how to do it
and i searched a lot
Hre is my code until now :
eActivityResultLauncher<Intent> mGetContent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
int id=data.getIntExtra(AddEditNoteActivity.EXTRA_ID,-1);
if(id == -1){
Toast.makeText(MainActivity.this, "Note can't be updated", Toast.LENGTH_SHORT).show();
return;
}
String title=data.getStringExtra(AddEditNoteActivity.EXTRA_TITLE);
String description = data.getStringExtra(AddEditNoteActivity.EXTRA_DESCRIPTION);
int priority = data.getIntExtra(AddEditNoteActivity.EXTRA_PRIORITY, 1);
Note note = new Note(title, description, priority);
noteViewModel.insert(note);
Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "Note not saved", Toast.LENGTH_SHORT).show();
}
}
}
);
and here is what i want to do
ActivityResultLauncher<Intent> mGetContent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// action if button is clicked
}else if() {
//action if recycledView is clicked
}
}
}
);

Related

call by phone number on button click (java)

I have a call method on button click
button_call=(Button) findViewById(R.id.button_call);
button_call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+79142214017"));
startActivity(intent);
}
});
And the data transfer method in Firebase
private void validateClientInfo() {
if (TextUtils.isEmpty(client_edit.getText().toString())) {
Toast.makeText(this, "Введите имя", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(client_number.getText().toString())){
Toast.makeText(this, "Введите номер", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> userMap = new HashMap<>();
userMap.put("uid", mAuth.getCurrentUser().getUid());
userMap.put("numberphone_client",client_number.getText().toString());
clientRef.child(mAuth.getCurrentUser().getUid()).updateChildren(userMap);
startActivity(new Intent(ClientName.this,HomeActivity.class));
}
}
transcripts
client_number=(EditText) findViewById(R.id.client_number);
mAuth=FirebaseAuth.getInstance();
how to make it so that when the call button is pressed, the number is received and called?
I want that when the button _call button is pressed, the data transmitted by the transfer method is received and a call is made on them.
Request permission android.permission.CALL_PHONE before calling.
Add into AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
Request permission before calling:
boolean isPermissionGranted = (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED);
if (isPermissionGranted) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + mNumber));
startActivity(intent);
} else {
Toast.makeText(this, "Отсутствует разрешение на звонок с устройства", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CALL_PHONE }, 0);
}
Add request result:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull #NotNull String[] permissions, #NonNull #NotNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 0) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
//RETURN, PERMISSION NOT GRANTED
Toast.makeText(this, "Вы не выдали разрешение, приложение может работать неккоректно!", Toast.LENGTH_SHORT).show();
return;
}
}
//PERMISSIONS GRANTED
Toast.makeText(this, "Спасибо за выданное разрешение!", Toast.LENGTH_SHORT).show();
}
}
If your are looking to call the selected number then just use the following code.
Intent intentCallForward = new Intent(Intent.ACTION_DIAL); // ACTION_CALL
Uri uri2 = Uri.fromParts("tel", "79142214017, "#");
intentCallForward.setData(uri2);
startActivityForResult(intentCallForward, 101);

How to pass data from a alertDialog to ActivityResultLauncher

I am creating an android app with a activity of showing an alertDialog to let user take a photo of a item.
// Inside AlertDialog on a Button Onclick function:
Intent camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camIntent.putExtra("GET_PRODUCT_ID", product_id);
activityResultLauncherStartCamera.launch(camIntent);
On activityResultLauncher, how can i get the "product_id" ?
ActivityResultLauncher<Intent> activityResultLauncherStartCamera = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>(){
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK){
Intent data = result.getData();
// Both Return a null
String product_id = data.getStringExtra("GET_PRODUCT_ID")
String product_id = getIntent().getStringExtra("GET_PRODUCT_ID")
// Check if old image file exist...
}
}
}
);
I need to check if there is a same image file created before and delete it after the user complete to take a new images.
Can you try like following reference?
https://developer.android.com/training/basics/intents/result#custom
https://developer.android.com/reference/androidx/activity/result/contract/ActivityResultContracts.TakePicture
public class PickRingtone extends ActivityResultContract<Integer, Uri> {
#NonNull
#Override
public Intent createIntent(#NonNull Context context, #NonNull Integer ringtoneType) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, ringtoneType.intValue());
return intent;
}
#Override
public Uri parseResult(int resultCode, #Nullable Intent result) {
if (resultCode != Activity.RESULT_OK || result == null) {
return null;
}
return result.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
}
}

Firebase AuthUI - Uknown Error Code

I am using the Firebase AuthUI to sign in to my application, specifically with Facebook. I have verified within my console that my sign in was successful, as I see the user added.
However, my callback method is not triggering, I have toasts implemented and I do not know why the success method is not being called. I have logged the error code and do not know what issue it signifies. Am I capturing the error correctly? It is generating -1, which I do not see in the Firebase AuthUI docs:
public class LoginActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 123;
private static final String USERS = "Users";
private FirebaseAuth mAuth;
FirebaseDatabase mBaseRef;
DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
mBaseRef = FirebaseDatabase.getInstance();
mUserRef = mBaseRef.getReference(USERS);
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.FacebookBuilder().build()))
.build(), RC_SIGN_IN);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// RC_SIGN_IN is the request code you passed into startActivityForResult(...) when starting the sign in flow.
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
Log.v("RESPONSE", String.valueOf(response.getErrorCode()));
// Successfully signed in
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "SIGNED IN SUCCESSFULLY", Toast.LENGTH_LONG).show();
if (mAuth.getCurrentUser() != null) {
HashMap<String, Object> map = new HashMap<>();
map.put("TEST USER ", mAuth.getCurrentUser());
mUserRef.push().updateChildren(map);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
} else {
//not signed in
Toast.makeText(getApplicationContext(), "SIGN IN FAILED", Toast.LENGTH_LONG).show();
return;
}
} else {
// Sign in failed
if (response == null) {
// User pressed back button
Toast.makeText(getApplicationContext(), "SIGN IN CANCELLED", Toast.LENGTH_LONG).show();
return;
}
if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
Toast.makeText(getApplicationContext(), "NO INTERNET CONNECTION", Toast.LENGTH_LONG).show();
return;
}
if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
Toast.makeText(getApplicationContext(), "UNKNOWN ERROR", Toast.LENGTH_LONG).show();
return;
}
}
}
}
}
EDIT: I have added the complete activity
EDIT: My log is running very quickly and then the error is automatically deleting before I can read it, it might actually be a StackOverflow.
The error code is only valid if an error actually occurred by checking the onActivityResult result code, otherwise it just returns -1 (Activity.RESULT_OK) as you've noticed. Here's an example from the sample:
private void handleSignInResponse(int resultCode, Intent data) {
IdpResponse response = IdpResponse.fromResultIntent(data);
// Successfully signed in
if (resultCode == RESULT_OK) {
startSignedInActivity(response);
finish();
} else {
// Sign in failed
if (response == null) {
// User pressed back button
showSnackbar(R.string.sign_in_cancelled);
return;
}
if (response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) {
showSnackbar(R.string.no_internet_connection);
return;
}
showSnackbar(R.string.unknown_error);
Log.e(TAG, "Sign-in error: ", response.getError());
}
}

android - Google places opens the map on closes after 1 sec

Im creating an intent to an activity by clicking on a button which should open google places, but it closes again really fast and says no location selected, and returns to the main activity, and then nothing happens if i click again.
My api should be fine, I have checked that it's the correct SHA1-fingerprint thats connected to the api key.
The result code is 2
It worked earlier in the activity before this one, but I needed it to open when i click on a button instead, and now when I try to open this new activity as an intent it wont work.
public class MapActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
GooglePlayServicesUtil.getErrorDialog(status, this,
100).show();
}
}
if (status == ConnectionResult.SUCCESS) {
int PLACE_PICKER_REQUEST = 199;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Context context = this;
try {
startActivityForResult(builder.build(context), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Result code: " + resultCode);
System.out.println("Request code: " + requestCode);
if (requestCode == 100) {
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
}
if (requestCode == 199) {
//process Intent......
if (data != null) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
} else {
String toastMsg = ("No location selected.");
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
}
This is from the intent which create the new intent to maps
public void onClick(View view) {
Intent i = new Intent(this, MapActivity.class);
startActivity(i);
}
I think its happening because of you are using old method of getPlace
try to swap the arguments, by changing it from:
Place place = PlacePicker.getPlace(data, this);
to
Place place = PlacePicker.getPlace(getContext(), data);
Update #2
Enable Google places API in the developer console and add these lines to AndroidManifest
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="ADD_YOUR_API_KEY_HERE" />
Update #3
after some search, it looks like there is others having same issue. Look at these links:
https://github.com/zhangtaii/react-native-google-place-picker/issues/21
https://stackoverflow.com/a/32751164/
https://github.com/googlesamples/android-play-places/issues/13

INVALID_RESOURCE_ID in paypal

I have make payments through PayPal native android mobile sdk. Below is the success response
{"response":{"state":"approved","id":"PAY-someID","create_time":"2017-06-21T18:01:33Z","intent":"sale"},"client":{"platform":"Android","paypal_sdk_version":"2.15.3","product_name":"PayPal-Android-SDK","environment":"sandbox"},"response_type":"payment"}
But when back-end wants to verify with the payment id i.e PAY-someID, it is throwing error json like below every time
[debug] application - verifyPayment mitemreqCppverifpmtrequest(PAY-someID)
[debug] application - verifpmtrequest case mendpointt https://api.sandbox.paypal.com/v1/payments/payment/PAY-someID
[debug] application - tx.get.body{"name":"INVALID_RESOURCE_ID","message":"Requested resource ID was not found.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#INVALID_RESOURCE_ID","debug_id":"someID"}
Below is the android code
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Example Merchant")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(SampleActivity.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
return new PayPalPayment(new BigDecimal("0.01"), "USD", "sample item",
paymentIntent);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm =
data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
}
}
}
The problem is similar to the below
https://github.com/paypal/PayPal-Android-SDK/issues/330
No idea how to solve this.
Try this one this is working code of my Google PlayStore application.
PayPalConfiguration config = new PayPalConfiguration().environment(PayPalConfiguration.ENVIRONMENT_SANDBOX).clientId("Your id");
Intent intent = new Intent(context, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
PayPalPayment payment = new PayPalPayment(new BigDecimal(charge), "USD", eventName, PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(activity, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
startActivityForResult(intent, 1089);
Don't Forget to stop service in OnDestroy().
#Override
protected void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
Also stop service inside OnActivityResult When you perform all your task.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 1089) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null)
{
try
{
// Your code after successful response.
} catch (JSONException e) {
Log.error(getClass().getName(), e);
}
}
stopService(new Intent(this, PayPalService.class));
} else if (resultCode == Activity.RESULT_CANCELED) {
//
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
//
}
}

Categories

Resources