How to crop image in java for android with OS Lollipop - java

I have the following code for cropping images. It's working perfectly in android version 4 or OS Kitkat, but its not working on Android version 5 or OS Lollipop.
I've already searched the whole world but couldn't find the answer...
Here's my code:
In OS Kitkat: this list variable return a value. but,
In OS Lollipop: this list variable return a empty arraylist.
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
PackageManager test = getPackageManager();
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mCapturedImageURI);
intent.putExtra("outputX", 110);
intent.putExtra("outputY", 110);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mCapturedImageURI != null ) {
getContentResolver().delete(mCapturedImageURI, null, null );
mCapturedImageURI = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}

I had already given android.permission.MANAGE_DOCUMENTS permission. But facing the same issue. After searching a lot, i found the solution.
Here's a workaround, for the time being:
Intent mIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(mIntent, CHOOSE_IMAGE);
This forces the older image gallery to open instead of the new Kitkat documents view.
Now, you can get the Uri by calling the following in your onActivityResult:
Uri selectedImageURI = data.getData();
Hope this help to solve your problem.

Related

App crashes when starting a activity

I have a webview app and wanted to updated app from inside when a certain text is present in the url.
I am calling these in shouldOverrideUrlLoading function of webview:
Intent intent = new Intent(getApplicationContext(), Update.class);
startActivity(intent);
return true;
And here is the Update.class
public class Update extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = "app-file.apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);
File file = new File(destination);
if (file.exists())
file.delete();
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(getIntent().getStringExtra("http://example.com/app-file.apk")));
request.setDestinationUri(uri);
dm.enqueue(request);
final String finalDestination = destination;
final BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(ctxt, BuildConfig.APPLICATION_ID + ".provider", new File(finalDestination));
Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
openFileIntent.setData(contentUri);
startActivity(openFileIntent);
unregisterReceiver(this);
finish();
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(install);
unregisterReceiver(this);
finish();
}
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
When I go to the certain url to start the activity, the app crashes. I would love to see any solution. Thanks!!
I SOLVED IT, it was permission error.
I would suggest you to look into ADB Logcat, which will help you to fix the issue.
Otherwise, check into crash log or make sure that you have declared your Update Activity in manifest.xml
Make sure you declare the new activity in your Android Manifest.xml
try changing this
Intent intent = new Intent(getApplicationContext(), Update.class);
startActivity(intent);
return true;
to this
Intent intent = new Intent(getApplicationContext(), Update.class);
startActivity(intent);
finish();
return true;
Let me know how that went.

How can I add my application's shortcut to the homescreen like the one of 360 security

I want to create my app's shortcut/launcher icon on the homescreen like the one of 360 security and release an activity when user click's on the icon without entering in the app
private void addShortcut() {
//Adding shortcut for MainActivity
//on Home screen
Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
shortcutIntent.putExtra(Constants.DEVICE_NO, mDevice.getFDeviceNo());
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mDevice.getFName());
int defaultImageRes = Utils.getDeviceImage(mDevice.getFViewType());
int color = Color.RED;
Bitmap defaultBitmap = overlay(BitmapFactory.decodeResource(getResources(), defaultImageRes), color);
if (mDevice.isCustomImage() && !mDevice.getFImage().isEmpty()) {
File file = MyApplication.getImageLoader(this).getDiskCache().get(ImageUtils.getImageUrl(mDevice.getFImageName()));
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
if (bitmap != null) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 128, 128, true);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, scaledBitmap);
} else {
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, defaultBitmap);
}
} else {
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, defaultBitmap);
}
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
Toast.makeText(this, R.string.added_to_home_screen, Toast.LENGTH_SHORT).show();
}

Capturing, saving and displaying pictures in activity

I have 3 buttons and a toggle in my activity. When toggled, the buttons should open the camera to capture an image or prompt to select one from gallery and 'save' it. When not-toggled, the buttons should display the image it was used to take in a main ImageView.
Three buttons:
//buttons 1,2,3 are the same
Button button1 = (Button) findViewById(R.id.some_button);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(toggled == true){
takePictureIntent();
}
else {
//display the picture
}
}
});
My camera/gallery code is from a tutorial/forum online:
private void takePictureIntent() {
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, 1);
//}
}
Can somebody please guide me towards how to have the button "remember" the picture taken through it so that, when the toggle is off, it will display it?
I've been trying to figure this out for hours, any help is appreciated.

User select image from gallery or from custom Camera and not Camera app for image

I would like the user to be able to click on a button and have the option of selecting the gallery or similar apps or a camera activity I have in my app not the build-in one . I read the related answers here and here . However, I don't want to include the build-in camera app, but I want to include my Camera Activity.
I have the following set up so far, taken from the two links I posted:
Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
Intent gallIntent = new Intent(Intent.ACTION_GET_CONTENT);
gallIntent.setType("image/*");
Intent camIntent = new Intent(UserEventsActivity.this,CameraActivity.class);
camIntent.setComponent(new ComponentName("MCamera", "Camera"));
List<Intent> yourIntentsList = new ArrayList<Intent>();
yourIntentsList.add(camIntent);
List<ResolveInfo> listGall = getApplicationContext().getPackageManager().queryIntentActivities(gallIntent, 0);
for (ResolveInfo res : listGall) {
final Intent finalIntent = new Intent(gallIntent);
finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
yourIntentsList.add(finalIntent);
}
pickIntent.putExtra(Intent.EXTRA_INTENT, yourIntentsList.toArray(new Parcelable[]{}));
pickIntent.putExtra(Intent.EXTRA_TITLE, "Select Source");
startActivityForResult(pickIntent, 1);
What results from this, is a large list of unrelated apps and services, most of which are actually repeated several times in the list. In addition, my camera activity is not among them. When I just do pickIntent.putExtra(Intent.EXTRA_INTENT,gallIntent) I do get the related gallery apps I want, but I can't add my activity.
Any ideas as to what I am doing wrong?
In addition, no service opens when I click on it. However, this may be related to the '1' arg in startActivityOnResult as I'm not exactly sure what to put for that arg.
I came up with a possible solution, that seemed to work for me. I used a custom Dialog:
final Dialog choosePicContent = new Dialog(UserEventsActivity.this);
ScrollView scrollContent = new ScrollView(UserEventsActivity.this);
choosePicContent.addContentView(scrollContent, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
LinearLayout scrollLayout = new LinearLayout(UserEventsActivity.this);
scrollContent.addView(scrollLayout);
scrollLayout.setOrientation(LinearLayout.VERTICAL);
TextView title = new TextView(UserEventsActivity.this);
title.setText(R.string.selectsource);
scrollLayout.addView(title);
Intent gallIntent = new Intent(Intent.ACTION_GET_CONTENT);
gallIntent.setType("image/*");
final Intent camIntent = new Intent(UserEventsActivity.this,CameraActivity.class);
ImageButton camButton = new ImageButton(UserEventsActivity.this);
camButton.setImageDrawable(getApplicationContext().getDrawable(R.drawable.ic_menu_camera));
camButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
camIntent.putExtra("User",current_user);
startActivity(camIntent);
}
});
scrollLayout.addView(camButton);
List<ResolveInfo> listGall = getApplicationContext().getPackageManager().queryIntentActivities(gallIntent, 0);
for (ResolveInfo res : listGall) {
final Intent finalIntent = new Intent(gallIntent);
finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
ImageButton iconButton = new ImageButton(UserEventsActivity.this);
iconButton.setImageDrawable(res.activityInfo.loadIcon(getPackageManager()));
iconButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(finalIntent,1);
}
});
scrollLayout.addView(iconButton);
}
choosePicContent.show();

How to implement a "share on whatsapp" feature in a custom Android app?

i have read several already answered article on this site and used this
Sending message through WhatsApp
i am able to share from chrome but not from app.
my code is
public void onClickWhatsApp(View view) {
PackageManager pm=getPackageManager();
try {
Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");
String text = "YOUR TEXT HERE";
PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
//Check if package exists or not. If not then code
//in catch block will be called
waIntent.setPackage("com.whatsapp");
waIntent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(waIntent, "Share with"));
} catch (NameNotFoundException e) {
Toast.makeText(MainActivity.this, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
}
}
when i click on share button in my android app whatsapp icon it gives error page not found but when same thing is shared from chrome it just works fine.
my url is http://way2enjoy.com/app/jokes.php
if anyone can guide where the mistake is i will be thankful
you can use my code which works for me
void openWhatsappContact(String number) {
Uri uri = Uri.parse("smsto:" + number);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.setPackage("com.whatsapp");
startActivity(Intent.createChooser(i, ""));}
enjoy your code time:)
you can use this code also
//method used to show IMs
private void show_custom_chooser(String value) {
List<ResolveInfo> list = null;
final Intent email = new Intent(Intent.ACTION_SEND);
email.setData(Uri.parse("sms:"));
email.putExtra(Intent.EXTRA_TEXT, "" + value);
email.setType("text/plain"); // vnd.android-dir/mms-sms
WindowManager.LayoutParams WMLP = dialogCustomChooser.getWindow()
.getAttributes();
WMLP.gravity = Gravity.CENTER;
dialogCustomChooser.getWindow().setAttributes(WMLP);
dialogCustomChooser.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialogCustomChooser.setCanceledOnTouchOutside(true);
dialogCustomChooser.setContentView(R.layout.about_dialog);
dialogCustomChooser.setCancelable(true);
ListView lvOfIms = (ListView) dialogCustomChooser
.findViewById(R.id.listView1);
PackageManager pm = getPackageManager();
List<ResolveInfo> launchables = pm.queryIntentActivities(email, 0);
// ////////////new
list = new ArrayList<ResolveInfo>();
for (int i = 0; i < launchables.size(); i++) {
String string = launchables.get(i).toString();
Log.d("heh", string);
//check only messangers
if (string.contains("whatsapp")) {
list.add(launchables.get(i));
}
}
Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
int size = launchables.size();
adapter = new AppAdapter(pm, list, MainActivity.this);
lvOfIms.setAdapter(adapter);
lvOfIms.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
ResolveInfo launchable = adapter.getItem(position);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(
activity.applicationInfo.packageName, activity.name);
email.addCategory(Intent.CATEGORY_LAUNCHER);
email.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
email.setComponent(name);
startActivity(email);
dialogCustomChooser.dismiss();
}
});
dialogCustomChooser.show();
}

Categories

Resources