'startActivityForResult(android.content.Intent, int)' is deprecated - java

I'm developing an intern project about a college app, while running this part of the app suddenly get close. this is the part where I can upload the photos to the gallery. I am not getting any error but here startActivityForResult(pickImage,REQ); it is saying like 'startActivityForResult(android.content.Intent, int)' is deprecated as a warning.
private String category;
private final int REQ= 1;
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
selectImage = findViewById(R.id.addGalleryImage);
imageCategory = findViewById(R.id.image_category);
uploadImage = findViewById(R.id.uploadImageBtn);
galleryImageView = findViewById(R.id.galleryImageView);
String[] items = new String[]{"Select Category", "Convovation", "INdependence Day","Other Events"};
imageCategory.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items));
imageCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
category = imageCategory.getSelectedItem().toString();
}
});
selectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openGallery(){
Intent pickImage = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImage,REQ);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
galleryImageView.setImageBitmap(bitmap);
}
}
}

If you want to pick image from the device then go for a newer alternative of startActiityForResult(), it's - ActivityResultLauncher
Just follow these steps :-
First create the ActivityResultLauncher like this :
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new
GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
// Handle the returned Uri
}
});
Then, launch system image picker on button click or however you want.
#Override
public void onCreate(#Nullable savedInstanceState: Bundle) {
Button selectButton = findViewById(R.id.select_button);
selectButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Pass in the mime type you'd like to allow the user to select
// as the input
mGetContent.launch("image/*");
}
});
}
As you can see, you are not seeing the REQUEST_CODE anywhere. So with ActivityResultLauncher, you don't have to worry about checking different requestcodes for different tasks. ActivityResultLauncher gives you the final result if everything is ok.
You can find more about it here :- https://developer.android.com/training/basics/intents/result

Finally I found the answer on google official website.
If you need requestCode todo something , just put the requestCode into the intent.
Good luck!
ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent intent = result.getData();
// Handle the Intent
}
}
});
#Override
public void onCreate(#Nullable savedInstanceState: Bundle) {
// ...
Button startButton = findViewById(R.id.start_button);
startButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// The launcher with the Intent you want to start
mStartForResult.launch(new Intent(this, ResultProducingActivity.class));
}
});
}

Related

Issue swapping image

I have a ProfileActivity:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final ImageView exampleImage = (ImageView) this.findViewById(R.id.exampleImageView);
exampleImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// [TODO] Implement application behavior when the user clicks the profile picture
//Toast.makeText(ProfileActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ProfileActivity.this, GalleryActivity.class));
}
});
}
and I have a second activity called 'GalleryActivity'. the concept is to let the user choose a image from the gallery and then use it to replace the original Profile image.
public class GalleryActivity extends AppCompatActivity {
ImageView imageView;
private static final int PICK_IMAGE = 100;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
}
however, when I click on a image of the gallery, instead of taking it as new profile image, it take me back to the original image.
what is happening and how I can solve it?
You can use Github Library it will help you.
Here is the Link.
ImagePicker.Companion.with(this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080)
.start();//Final image resolution will be less than 1080 x 1080(Optional)
On Activity Result.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
selectedFileURI = data.getData();
if (selectedFileURI != null && !Objects.requireNonNull(selectedFileURI.getPath()).isEmpty()) {
btnUpdate.setVisibility(View.GONE);
civUser.setImageURI(selectedFileURI);
Glide.with(context).load(selectedFileURI).into(civUser);
btnUploadDp.setVisibility(View.VISIBLE);
} else {
Functions.showSnackBar(context, "Cannot Get this Image");
}
}
}
}
Refernce Link.

How to check what the user clicked on uninstall dialog box created using intent in android?

i am trying create an app that is capable of uninstalling the other installed apps . So when i am using uninstall intent the dialog box opened ask for Ok or cancel. so how can i get informed whether the user selected ok or cancel as i need to hide the the uninstall button that is pressed. Assigned as button present in public class viewholder at end of the code
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
MainActivity mainActivity=new MainActivity();
private Context mContext;
List<Drawable> images;
List<String> titles;
List<String> apps;
LayoutInflater inflater;
public void uninstallAPK(String apkPackageName) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + apkPackageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivity(intent);
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
launchBrowser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchBrowser.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivity(launchBrowser);
mainActivity.finish();
}
public Adapter(Context ctx, List<String> titles, List<Drawable>
images,List<String> apps){
this.titles =titles;
this.images = images;
this.apps = apps;
this.inflater =LayoutInflater.from(ctx);
mContext = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
View view = inflater.inflate(R.layout.custom_grid_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int
position) {
holder.title.setText(titles.get(position));
holder.gridIcon.setImageDrawable(images.get(position));
}
#Override
public int getItemCount() {
return titles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView gridIcon;
TextView title;
Button button;
Button button3;
public ViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.textView);
gridIcon = itemView.findViewById(R.id.imageView2);
button = itemView.findViewById(R.id.button);
button3 = itemView.findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uninstallAPK(apps.get(getAdapterPosition()));
//want to hide the button if ok is pressed otherwise want
to show the button
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ParseQuery<ParseObject> linkwa = new
ParseQuery<ParseObject>("package");
linkwa.whereEqualTo("packid",
apps.get(getAdapterPosition()));
linkwa.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects,
ParseException e) {
if(e==null && objects.size()>0){
for (ParseObject object:objects){
goToUrl(object.getString("link"));
}
}
}
});
}
});
}
}
}
There is actually workaround that you can give a try
StartActivityFotResult which will ensure you will get the callback inside onActivityResult
public void uninstallAPK(String apkPackageName) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + apkPackageName));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
mContext.startActivityForResult(intent, 12345);
}
Now you can check the Result-Code whether it is a success or not RESULT_OK or RESULT_CANCELLED
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1234) {
if(resultCode == Activity.RESULT_OK){
//Deleted
}
if (resultCode == Activity.RESULT_CANCELED) {
//Dismissed
}
}
}//onActivityResult
2.1. If the above-mentioned solution did not work then
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1234) {
if (appInstalledOrNot("required_app_package_name")){
// Dismissed
}else {
//Deleted
}
}
}//onActivityResult
private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
PS. Checking if an app is installed or not is taken from here
Don't really know how is your implementation, but ideally I would have two button. One for cancel another for uninstall. And I would have set clicklistener on both of the button. So, whenever, the onclickListener is executed, means user pressed the button of the dialog box. So, first thing, I would dissmiss the dialog, second thing based on the button user clicked
public void onClick(View v){
if(v.getId == R.id.btn_dialog_uninstall){
uninstallPackage("package_name");
dialog.dissmiss();
}else{
dialog.dissmiss(); // user pressed cancelled;
}
hope that helps.

Start activity from fragment, then get callback

I am trying to get a callback from an activity that I am starting with an intent in my fragment.
I thought I could do this with onActivityResult but it doesn't seem to get called when I finish(); on the activity. Is this possible in a fragment?
Fragment.java
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Waiver");
myView = inflater.inflate(R.layout.waiver_layout, container, false);
signBtn = myView.findViewById(R.id.signBtn);
signBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SignatureActivity.class);
intent.putExtra("signatureAbleId", device.id);
intent.putExtra("signatureAbleType", "App\\Models\\Device");
startActivity(intent);
}
});
return myView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
Log.v("Activity", "The activity has finished");
if(resultCode == 200){
saveWaiver();
}
}
private void saveWaiver(){
Log.v("Save Waiver", "Saving waiver for you.");
}
SignatureActivity.java
public class SignatureActivity extends AppCompatActivity {
private Button btnClear;
private Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_signature);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
signatureAbleId = bundle.getInt("signatureAbleId");
signatureAbleType = bundle.getString("signatureAbleType");
}
btnClear = findViewById(R.id.btnClear);
btnSave = findViewById(R.id.btnSave);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSignaturePad.clear();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
setResult(200);
finish();
});
}
}
Use this. It will help you
Intent intent = new Intent(getContext(), SignatureActivity.class);
Instead of
Intent intent = new Intent(getActivity(), SignatureActivity.class);
And Yes need to change :
startActivity to startActivityForResult
Use startActivityForResult instead of startActivity
startActivityForResult(intent, 11);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 11){
if(resultCode == 200){
saveWaiver();
}
}else{
super.onActivityResult(requestCode, resultCode, data)
}
}

Sending Zxing scanResult to another activity

I have tried everything and whatever I could to solve this problem. At last I am posting it here to get a solution (New to Android).
I have made an android scanner app and I am using ZXing open source code. The problem is after scan I am trying to send the scan result to another activity but unable to do.
Here is my code:
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler, NavigationView.OnNavigationItemSelectedListener {
private ZXingScannerView mScannerView;
private int CALL_SCANNER_APP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Scan Button code
public void onClick(View v) {
ZXingScannerView mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
//startActivityForResult(mScannerView1, CALL_SCANNER_APP);
}
#Override
protected void onPause (){
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
ResultActivity.tvresult.setText(result.getText());
/*Log.w("handleReuslt", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
//alertDialog.show();
builder.setPositiveButton("Result", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("OK", null).show();*/
//Resume Scanning
//mScannerView.resumeCameraPreview(this);
}
There is one method which send results from One activity to other activity is scanActivityForResult() but in my case I am not using intent on public void onClick(View v)
So how do I achieve this.
Thanks!
Use Below code into the button click.
Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class);
intent.putExtra("SCAN_MODE", "ONE_D_MODE");
intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE");
intent.setAction(Intents.Scan.ACTION);
startActivityForResult(intent, 1);
And override this method to get result of scanning.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final String contents = intent.getStringExtra(Intents.Scan.RESULT);
final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT);
}
}
in handleDecodeInternally you directly intent the Capture Activity to desired Activity
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
maybeSetClipboard(resultHandler);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (resultHandler.getDefaultButtonID() != null && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) {
resultHandler.handleButtonPress(resultHandler.getDefaultButtonID());
return;
}
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.GONE);
Intent intent = new Intent(CaptureActivity.this, AfterCaptureActivity.class);
startActivity(intent);
finish();

Choose file from directory

How i can choose image from gallery and them put it on parse.com ?
There i open GALLERY:
#Override
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
i.setType("image/*");
i.setAction(Intent.ACTION_VIEW);
///// - here must be code tat can choose file that i must upload to parse
////
There is code that can upload image to parse.com :
I think it will be something like this
ParseObject image = new ParseObject("guestList");
image.put("photo", image);
image.saveInBackground();
UPD
public class SendGuestPhoto extends Activity {
ImageView imageView;
private static final int PICK_IMAGE = 100;
String path;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_guest_photo);
imageView = (ImageView) findViewById(R.id.image_view);
Button button_choose_guest_photo = (Button)findViewById(R.id.button_choose_guest_photo);
button_choose_guest_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
}
private void openGallery() {
Intent gallery =
new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
Uri imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
public void SendPhoto(){
Button button_send_guest_photo = (Button)findViewById(R.id.button_send_guest_photo);
button_send_guest_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject photos = new ParseObject("guestsImages");
photos.put("photos", ????????????????);
photos.saveInBackground();
}
});
}
}

Categories

Resources