How to pass data from a alertDialog to ActivityResultLauncher - java

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

Related

what to use insead of requestCode

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

How can I get the URI to the file with 3 different file choosers?

I have 3 different buttons: Upload Profile Picture, Upload Photo ID and Upload Criminal Record Photo, but after I call the openFileChooser() method which I created, I don't know how exactly I have to handle that to get 3 different URls.
I mean I did this
public class SignupCarrier extends AppCompatActivity {
EditText editfullname, editemail, editpassword, editconfirmpassword, editaddress, editcity, editstate, editzipcode, editcountry, editphone, editcardnumber, editexpiredate, editcvc;
Button upProfile, upIDPhoto, upCriminalRecord;
private Uri mProfilePic, mIdPhoto,mCriminalRecord;
FirebaseAuth mFirebaseAuth;
private StorageReference mStorageRef;
private StorageTask mUploadTask;
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_carrier);
mFirebaseAuth = FirebaseAuth.getInstance();
upProfile = (Button) findViewById(R.id.profilePic);
upIDPhoto = (Button) findViewById(R.id.idphotoPic);
upCriminalRecord = (Button) findViewById(R.id.criminalRecord);
mStorageRef = FirebaseStorage.getInstance().getReference("carriersPictures");
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upIDPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upCriminalRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
mProfilePic = data.getData();
}
}
}
But this would probably work only for upProfile Button, how can I modify the onActivityResult to get for each buttons the URLs?
Thank you! I'm new to Android.
Add Uri as parameter to your openFileChooser() method.
private void openFileChooser(Uri uri)
and call it like this:
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser(mProfilePic);
}
});
Update your openFileChooser() method to this:
private void openFileChooser(Uri uri) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (uri == mProfilePic) {
startActivityForResult(intent, PICK_IMAGE_REQUEST);
} else if (uri == mIdPhoto) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_ID);
} else if (uri == mCriminalRecord) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_CR);
}
}
You need to declare these constants: PICK_IMAGE_REQUEST_ID, PICK_IMAGE_REQUEST_CR
And in your onActivityResult() method check the requestCode to handle each case

shared preference to save profile image

In my app I want to make a profile page with default image profile and allow to user to change it by take a picture from camera or choose image from gallery, I did that successfully and here's my code:
public class MainActivity extends AppCompatActivity {
private static final int pick = 1, capture = 2;
Uri imgeUri, touri;
ImageView imp;
SharedPreferences sh;
SharedPreferences.Editor editor;
String S;
boolean d=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("eee","in resume");
setContentView(R.layout.activity_main);
sh = getSharedPreferences("my" ,Context.MODE_PRIVATE);
editor=sh.edit();
imp = (ImageView) findViewById(R.id.profile_image);
if(d==false) {
imp.setImageResource(R.drawable.photo);
}
else{
imp.setImageURI(Uri.parse(sh.getString("link", null)));
}
}
public void changepic(View V) {
final String[] items = {"Take picture", "Choose Picture",
"cancle"};
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setTitle("Add Photo");
build.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (items[which].equals("Choose Picture")) {
Log.d("test","bh");
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, pick);
} else if (items[which].equals("Take picture")) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, capture);
}
}
}).create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == pick && resultCode == RESULT_OK) {
imgeUri = data.getData();
Log.d("test","pick");
imp.setImageURI(imgeUri);
editor.putString("link",String.valueOf(imgeUri));
//Log.d("test",f);
editor.commit();
d=true;
} else if (requestCode == capture && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imp.setImageBitmap(imageBitmap);
}
}
But the problem is when selecting an image I save it in shared preference the image appears just fine when I'am in activity when go to another and return back this disappear and the activity show the default image, i know the reason it because every time i return to profile activity this was created again and the boolean variable d was false again.
How can i fix that when i must call the get preference.?
In the "onActivityResult()" method, save the imageUri (or imagePath) obtained to sharedPreferences.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor edit = preferences.edit();
edit.putString(key, value);
edit.apply();
Instead of using boolean, check if sharedPreference value is not a null string.If the sharedPreference value is not a null string, update the imageview with imageUri (or imagePath) from sharedPreference.
For loading image in imageView, i recommend you to use photo loading libraries like Picasso or Glide.

How do I set the Camera Intent as the Main Activity

I want to launch the camera once a user opens up my application.
Right now I have this, and it works fine. When the user launches my application, it automatically opens up the camera. However, then the user hits the "back" button after taking an image, it opens up a blank activity.
How do I get it to go back to the camera?
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_TAKE_PHOTO = 0;
// The URI of photo taken with camera
private Uri mUriPhotoTaken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
takePhoto();
}
// Deal with the result of selection of the photos and faces.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri imageUri;
if (data == null || data.getData() == null) {
imageUri = mUriPhotoTaken;
} else {
imageUri = data.getData();
}
Intent intent = new Intent(MainActivity.this, Result.class);
intent.setData(imageUri);
startActivity(intent);
}
}
// Launch the camera to allow the user to take a photo
public void takePhoto(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null) {
// Save the photo taken to a temporary file.
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File file = File.createTempFile("IMG_", ".jpg", storageDir);
mUriPhotoTaken = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken);
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
} catch (IOException e) {
Log.d("ERROR", e.getMessage());
}
}
}
}
Try to call takePhoto() method in the onStart() instead of onCreate() and then call the finish() method into the onStop().
Try it.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, ActivityYouWantToOpen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
}

Activity not waiting for result

I have an activity called CForm. I would like to call CGForm for result. After i get the result start another activity. The problem is that when i start the details_click method , it executes the CGFORM, but doesn't waits for setting the result in the form, it jumps to the CDFORM.
here is the code for CFORM:
////////////////////////////CForm/////////////////////////
public boolean details_click()
{
if(listview.getCheckedItemPosition()>=0)
{
ArrayList<ComandaClass> listcompos = CClass.C();
int gestiuneId = 0;
if ((configurare.bAlCom) && (listcompos.size() == 0))
{
StocClass.setComandaContextForDB(this);
listGest = StocClass.Gestiuni_Get();
if (listGest.size() > 1)
{
Intent intent = new Intent();
intent.setClass(CForm.this,CGForm.class);
startActivityForResult(intent,GET_CODE);//here i would like to get back the result from CGForm
dGeid=getGIdResult;
}
}
boolean tof = true;
if ((configurare.bGCom) && (gestiuneId == -1))
tof = false;
if (tof)
{
dCid=listCom.get(listview.getCheckedItemPosition()).getCId();
dClid=listCom.get(listview.getCheckedItemPosition()).getClId();
dF=listCom.get(listview.getCheckedItemPosition()).getF();
Intent intent = new Intent();
intent.setClass(CForm.this,CDForm.class);
startActivity(intent);
}
return true;
}
else
{
Toast.makeText(this, "X", 5000).show();
return false;
}
}
public static int getGIdResult=-1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == GET_CODE)
{
if (resultCode == RESULT_OK)
{
getGIdResult=data.getIntExtra("GIdResult",-1);
}
else
{
getGIdResult=-1;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
CGFORM code:
////////////////////CGForm//////////////////
public class CGForm extends Activity
{
public static ArrayList<StocClass> listG=null;
public static int gid;
ListView listview=null;
Button btnOK=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.comenzigestiuni);
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
listview=(ListView)findViewById(R.id.listViewDG);
listG = CForm.listGest;
CG_Load();
}//oncreate
private void CG_Load()
{
//..adding data to listview
btnOK=(Button)findViewById(R.id.menuItemOk);
btnOK.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (listview.getCheckedItemPosition() >= 0)
{
gestiuneid = listG.get(listview.getCheckedItemPosition()).getGId();
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
finish();
}
}
});
}//CG_Load
#Override
protected void onStop()
{
gestiuneid=-1;
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
super.onStop();
}
}
thanks advanced !
Neither startActivity() nor startActivityForResult() are blocking calls. Anything that is supposed to be done after you receive the result needs to move to your onActivityResult() method.

Categories

Resources