Imagebutton.setImageURI(uri) doesn't work - java

now my problem is that:
This is a workaround for Onclcick an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.
private ImageButton mImageSelect;
private static final int GALLERY_REQUEST =1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mImageSelect=(ImageButton) findViewById(R.id.imageselect);
mImageSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
if(requestCode== GALLERY_REQUEST && resultCode==RESULT_OK){
Uri selectedImageUri=data.getData();
if (null != selectedImageUri) {
mImageSelect.setImageURI(selectedImageUri);
Toast.makeText(PostActivity.this, "Image Selected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(PostActivity.this,"Image Not Selected",Toast.LENGTH_SHORT).show();
}
}
}

even if fileUri is ready, setImageUri() doesn't guarantee to set the image. so its a good practice to always use third party library when dealing with image.
instead of setImageUri(), use Picasso library.
Picasso.with(MainActivity.this).load(fileUri).into(mImageView)
Add as dependancy
compile 'com.squareup.picasso:picasso:2.5.2'

Try this
Uri imgUri=Uri.parse("android.resource://my.package.name/"+R.drawable.image);
mImageSelect.setImageURI(null);
mImageSelect.setImageURI(imgUri);
This is a workaround for refreshing an ImageButton, which tries to cache the previous image Uri. Passing null effectively resets it.

Imagebutton.setImageURI(uri) doesn't work
You can use Glide to load images more easily
Add this to your build.gradle
compile 'com.github.bumptech.glide:glide.3.7.0'
Load image uri using glide as follows
Glide.with(MainActivity.this).load(uri).into(imageView);

Try
mImageSelect.setImageURI(Uri.parse(data.getData());

Try creating Bitmap from uri and setting bitmap on image button.
This can be done as:
String path = getPath(this,uri);
Code for getPath():
public static String getPath(final Context context, final Uri uri) {
Utils.context = context;
Utils.uri = uri;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Now can get Bitmap as:
if(path!=null)
Bitmap bm = getBitmapFromPath(path)
Set Image on imageButton as:
ImageButton.setImageBitmap(bm);

Related

Missing file path

I would like to send the image and text that I received from the user to the server but I have problems.
void sendData(final String username) {
String url = "http://hesabdarbartar.ir/api/update";
final SharedPreferences preferences = getApplicationContext().getSharedPreferences("data_user", Context.MODE_PRIVATE);
AndroidNetworking.upload(url)
.addMultipartFile(Key.IMAGE, new File(path))
.addMultipartParameter(Key.NAME, username)
.addHeaders(Key.TOKEN, preferences.getString("api_token", ""))
.build()
.getAsObject(User.class, new ParsedRequestListener<User>() {
#Override
public void onResponse(User response) {
try {
preferences.edit().putString("name", response.getName()).apply();
preferences.edit().putString("pic", response.getPic()).apply();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "خطا در ارتباط با سرور!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(ANError anError) {
Log.i("ererer", "" + String.valueOf(anError));
}
});
}
void askReadPermission() {
Dexter.withActivity(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
pickImage();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
if (response != null && response.isPermanentlyDenied()) {
Snackbar.make(btn_confirm, "برای انتخاب فایل دسترسی ضروری است!", Snackbar.LENGTH_LONG).setAction("اجازه دادن!", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.fromParts("package", getApplicationContext().getPackageName(), null));
startActivity(i);
}
}).show();
} else {
Snackbar.make(btn_confirm, "برای انتخاب فایل دسترسی ضروری است!", Snackbar.LENGTH_LONG).show();
}
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
}).check();
}
private void pickImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data.getData() != null) {
path = data.getData().getPath();
btn_confirm.setEnabled(true);
img_prof.setImageURI(data.getData());
}
}
}
Here's a snapshot of the program's problems
What you receive in onActivityResult() is an Uri of the image, not its real path. You should convert it to the real path, then you can use it in new File(path). There is a converter:
public class RealPathUtil {
public static String getRealPath(Context context, Uri fileUri) {
String realPath;
// SDK < API11
if (Build.VERSION.SDK_INT < 11) {
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(context, fileUri);
}
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19) {
realPath = RealPathUtil.getRealPathFromURI_API11to18(context, fileUri);
}
// SDK > 19 (Android 4.4) and up
else {
realPath = RealPathUtil.getRealPathFromURI_API19(context, fileUri);
}
return realPath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
String result = null;
CursorLoader cursorLoader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
cursor.close();
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = 0;
String result = "";
if (cursor != null) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
cursor.close();
return result;
}
return result;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #author paulburke
*/
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}

File is empty after creating it using Uri - Retrofit

I'm trying to create a file using Uri. But when it is checked whether its empty, it is found empty. Below is the code where the Uri is stored in the variable "filePath".
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
So i have created a function to upload the file to server using retrofit library.
On button click the function is called. Below is the code:
private void uploadFile(Uri fileUri) {
String descriptionString = "hello";
File file = new File(fileUri.getPath());
if(file.exists())
{
Toast.makeText(MainActivity.this,file.getPath(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,file.getName(),Toast.LENGTH_SHORT).show();
}
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
MultipartBody.Part image =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Call<ImageResponse> call = RetrofitClient.getInstance().getApi().uploadImage(descriptionString,image);
call.enqueue(new Callback<ImageResponse>() {
#Override
public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
ImageResponse imageResponse = response.body();
if (imageResponse.isError())
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ImageResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
So my request is failing because the file doesn't exist. What could be the reason? I'm using emulator and have added all the required permissions. I have no idea why it shouldn't work. Please help me! I'm new to retrofit.
My Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And the final response I'm getting in toast is:
document/image:31 (no such file or directory )
The issue was that no matter you specify permissions in Manifest, you have to check the permissions at runtime from Android v6.0. So all you have to do is check permissions at run time.
Here is the code. Use the below code:
//Check Permissions on runtime
public boolean checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
(Activity) context,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialog("External storage", context,
Manifest.permission.READ_EXTERNAL_STORAGE);
} else {
ActivityCompat
.requestPermissions(
(Activity) context,
new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void showDialog(final String msg, final Context context,
final String permission) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage(msg + " permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[] { permission },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do your stuff
} else {
Toast.makeText(MainActivity.this, "GET_ACCOUNTS Denied",
Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
//End permission code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
try {
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
filePath=data.getData();
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filePath);
imageView.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadFile(Uri fileUri) {
String descriptionString = "hello";
File file=FileUtils.getFile(getApplicationContext(),fileUri);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
MultipartBody.Part image =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Call<ImageResponse> call = RetrofitClient.getInstance().getApi().uploadImage(descriptionString,image);
call.enqueue(new Callback<ImageResponse>() {
#Override
public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
ImageResponse imageResponse = response.body();
if (imageResponse.isError())
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,imageResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ImageResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
Below is the FileUtils class:
public class FileUtils {
//replace this with your authority
public static final String AUTHORITY = "com.ianhanniballake.localstorage.documents";
private FileUtils() {
} //private constructor to enforce Singleton pattern
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
/**
* #return Whether the URI is a local one.
*/
public static boolean isLocal(String url) {
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
return true;
}
return false;
}
public static boolean isLocalStorageDocument(Uri uri) {
return AUTHORITY.equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
* #author paulburke
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
* #author paulburke
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
* #author paulburke
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
* #author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* #param context The context.
* #param uri The Uri to query.
* #author paulburke
* #see #isLocal(String)
* #see #getFile(Context, Uri)
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// LocalStorageProvider
if (isLocalStorageDocument(uri)) {
// The path is the id
return DocumentsContract.getDocumentId(uri);
}
// ExternalStorageProvider
else if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Convert Uri into File, if possible.
*
* #return file A local file that the Uri was pointing to, or null if the
* Uri is unsupported or pointed to a remote resource.
* #author paulburke
* #see #getPath(Context, Uri)
*/
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
}

Photo Uploaded is inverted - Android App

So we're trying to implement an upload image feature in our Android App.
In our registration page, there is an upload button and once pressed, it should redirect to the image gallery and once an image is selected, it should be displayed in the ImageView placed.
Here's an excerpt of the code we're trying to work on.
The issue is, for some images it is correctly displayed but for some, it is either rotated 90 degrees to the right or 180 degrees.
What could be the issue?
public class Register extends AppCompatActivity {
private String mName = "";
private String mUsername = "";
private String mPassword = "";
private String mCompany = "";
private String mContact = "";
private static final int PICK_IMAGE = 100;
ImageView imageView;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Intent recvdIntent = getIntent();
mName = recvdIntent.getStringExtra("NAME");
mUsername = recvdIntent.getStringExtra("USERNAME");
mPassword = recvdIntent.getStringExtra("PASSWORD");
mCompany = recvdIntent.getStringExtra("COMPANY");
mContact = recvdIntent.getStringExtra("CONTACT");
imageView = (ImageView)findViewById(R.id.imageView);
Button btnSubmit = (Button) findViewById(R.id.btn_register);
btnSubmit.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
submitUserData();
Intent launchIntent = new Intent(Register.this, Category.class);
return;
}
}
);
Button upload = (Button) findViewById(R.id.btn_upload);
upload.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
}
});
return;
}
private void openGallery() {
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);
}
}
public static Bitmap modifyOrientation(Bitmap bitmap, String image_absolute_path) throws IOException {
ExifInterface ei = new ExifInterface(image_absolute_path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotate(bitmap, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotate(bitmap, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotate(bitmap, 270);
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
return flip(bitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
return flip(bitmap, false, true);
default:
return bitmap;
}
}
public static Bitmap rotate(Bitmap bitmap, float degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
public static Bitmap flip(Bitmap bitmap, boolean horizontal, boolean vertical) {
Matrix matrix = new Matrix();
matrix.preScale(horizontal ? -1 : 1, vertical ? -1 : 1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
private void submitUserData() {
EditText edtName = (EditText) findViewById(R.id.edt_name);
EditText edtCompany = (EditText) findViewById(R.id.edt_company);
EditText edtContact = (EditText) findViewById(R.id.edt_contact);
EditText edtUsername = (EditText) findViewById(R.id.edt_username);
EditText edtPassword = (EditText) findViewById(R.id.edt_password);
TaraApp2 app = (TaraApp2) getApplication();
app.saveUserData(edtName.getText().toString(),edtUsername.getText().toString(),
edtPassword.getText().toString(),
edtCompany.getText().toString(),
edtContact.getText().toString() );
finish();
return;
}
}
Uri selectedImageUri = data.getData();
Bitmap bitmap = scaleImage(this,selectedImageUri);
public static Bitmap scaleImage(Context context, Uri photoUri) throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
srcBitmap.getHeight(), matrix, true);
}
String type = context.getContentResolver().getType(photoUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (type.equals("image/png")) {
srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] bMapArray = baos.toByteArray();
baos.close();
return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
for getting url of the image use this
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
For accessing picture from your gallery you can use the croperino library.
https://android-arsenal.com/details/1/4374
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Croperino.prepareGallery(MainActivity.this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CroperinoConfig.REQUEST_PICK_FILE:
if (resultCode == Activity.RESULT_OK) {
CroperinoFileUtil.newGalleryFile(data, MainActivity.this);
Croperino.runCropImage(CroperinoFileUtil.getmFileTemp(),
MainActivity.this, true, 1, 1, 0, 0);
}
break;
case CroperinoConfig.REQUEST_CROP_PHOTO:
if (resultCode == Activity.RESULT_OK) {
Uri i = Uri.fromFile(CroperinoFileUtil.getmFileTemp());
ivMain.setImageURI(i);
//Do saving / uploading of photo method here.
//The image file can always be retrieved via
CroperinoFileUtil.getmFileTemp()
}
break;
default:
break;
}
}

How would I also be able to get the phone number from the contact the user picked?

I am able to get the contact name that the user chose but not the phonenumber
In the onclick :
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
PICK_CONTACT is just an int value that equals one its my requestcode
then:
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (reqCode == PICK_CONTACT) {
if (resultCode == AppCompatActivity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
contactadder.setText(name);
c.close();
}
Here is a little snippet of my work which perhaps might help you to get the right direction. Android database interaction is poorly documented and hard to find the right way/values. Just reply if you need more help to understand. I removed some business relevant data out, so it will not compile this way. Just for easy post!
public static final String[] PROJECTION ={
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.DATA1,
ContactsContract.Data.DATA2,
ContactsContract.Data.DATA3,
ContactsContract.Data.DATA4,
ContactsContract.Data.DATA5,
ContactsContract.Data.DATA6,
ContactsContract.Data.DATA7,
ContactsContract.Data.DATA8,
ContactsContract.Data.DATA9,
ContactsContract.Data.DATA10,
ContactsContract.Data.DATA11,
ContactsContract.Data.DATA12,
ContactsContract.Data.DATA13,
ContactsContract.Data.DATA14,
ContactsContract.Data.DATA15
};
private static final int MIMETYPE_COLUMN=0;
private static final int DATA_COLUMN=1;
private static final int DATATYPE_COLUMN=2;
private static final String SELECTION = ContactsContract.Data.CONTACT_ID + " = ?";
public static ContactWrapper localContact(long contactId){
Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,PROJECTION, SELECTION, new String[]{String.valueOf(contactId)}, null);
ContactWrapper wrapper = new ContactWrapper(contact);
if(cursor==null){
return wrapper;
}
while(cursor.moveToNext()){
String mime=cursor.getString(MIMETYPE_COLUMN);
if (mime.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
contact.setU8sDisplayName(cursor.getString(DATA_COLUMN));
} else if (mime.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
putPhoneNumber(contact, cursor);
} else if (mime.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
putEmail(contact, cursor);
} else if (mime.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)) {
putAddress(contact, cursor);
}else if (mime.equals(ContactsContract.CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE)) {
contact.setU8sSIPAddress(cursor.getString(DATA_COLUMN));
}else if (mime.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)) {
wrapper.setImageBinaryString(getContactPhotoBase64(contactId));
}
}
cursor.close();
return wrapper;
}
private static void putPhoneNumber(ContactWrapper contact,Cursor data){
switch (data.getInt(DATATYPE_COLUMN)){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contact.setU8sPhoneHome(data.getString(DATA_COLUMN));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
contact.setU8sPhoneMobile(data.getString(DATA_COLUMN));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contact.setU8sPhoneBusiness(data.getString(DATA_COLUMN));
break;
}
}

Android - picking file with specific extension (pdf & docx)

I used this code for video
public void pickVideo()
{
Intent pickVideoIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickVideoIntent, PICK_VIDEO_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK){
switch (requestCode){
case PICK_VIDEO_ACTIVITY_REQUEST_CODE:
Uri selectedVideo = data.getData();
videoPicked(videoUriToRealPath(selectedVideo));
break;
.
.
.
public String videoUriToRealPath(Uri videoUri){
String[] proj = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(videoUri, proj, null, null, null);
String videoPath = "";
try{
if (cursor != null){
int column_index = cursor.getColumnIndex(MediaStore.Video.Media.DATA);
if (cursor.moveToFirst()){
videoPath = cursor.getString(column_index);
}
}
}finally{
cursor.close();
}
return videoPath;
}
and it's working. I want to set PICK_FILE_ACTIVITY_REQUEST_CODE as one of cases. I've defined it:
public void pickFile()
{
Intent pickFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickFileIntent.setType("*/*");
startActivityForResult(pickFileIntent, PICK_FILE_ACTIVITY_REQUEST_CODE );
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK){
switch (requestCode){
case PICK_FILE_ACTIVITY_REQUEST_CODE:
Uri selectedFile = data.getData();
filePicked(fileUriToRealPath(selectedFile));
.
.
.
public String fileUriToRealPath(Uri fileUri){
String[] proj = {MediaStore.Files.Media.DATA};
Cursor cursor = getContentResolver().query(fileUri, proj, null, null, null);
String filePath = "";
try{
if (cursor != null){
int column_index = cursor.getColumnIndex(MediaStore.Files.Media.DATA);
if (cursor.moveToFirst()){
filePath = cursor.getString(column_index);
}
}
}finally{
cursor.close();
}
return filePath;
}
Actually it's not working. extension .PDF and .DOCX in my files. how to fix it?
I think you need to search on the whole sdcard.
searchDir(Environment.getExternalStorageDirectory());
public void searchDir(File dir){
String docExt = ".doc";
String pdfExt = ".pdf";
File listFile[] = dir.listFiles();
if (listFile != null){
for (int i = 0; i < listFile.length; i++){
if (listFile[i].isDirectory()){
searchDir(listFile[i]);
}else{
if(listFile[i].getName().endsWith(docExt)){
//Do what ever u want
}else if(listFile[i].getName().endsWith(pdfExt)){
//Do what ever u want
}
}
}
}
}

Categories