I am trying to make a app that takes high quality photo and the upload them but one of the most important part won't work, the camera. Intent data is null so no image a being display. I took the infor from https://developer.android.com/training/camera/photobasics#TaskPath.
I have tried different way but nothing is working from me.
package com.example.gn.nextcamtest;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView txt_Test;
Button btn_Cam;
ImageView iv_image;
static final int REQUEST_IMAGE_CAPTURE = 1;
String mCurrentPhotoPath;
public static final int RequestPermissionCode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_Cam = (Button) findViewById(R.id.btn_Cam);
iv_image = (ImageView) findViewById(R.id.iv_Test);
txt_Test = (TextView) findViewById(R.id.txt_test);
EnableRuntimePermissionToAccessCamera();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
txt_Test.setText(" " + bundle.getString("test"));
}
btn_Cam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
if (data.getExtras() != null && data.getExtras().get("data") instanceof Bitmap) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv_image.setImageBitmap(imageBitmap);
// iv_image.setImageBitmap((Bitmap)data.getExtras().get("data"));
} else {
iv_image.setImageResource(R.drawable.ic_launcher_background);
Toast.makeText(this, "Fail to load image", Toast.LENGTH_LONG).show();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ );
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "com.example.gn.nextcamtest.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
// Requesting runtime permission to access camera.
public void EnableRuntimePermissionToAccessCamera() {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION
}, 101);
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
// Printing toast message after enabling runtime permission.
Toast.makeText(this, "CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.CAMERA
}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
}
I tried this too a couple of days ago and had to struggle a lot. Then I figured it myself.
Here is how my code looks :
1) In onCreate :
capture.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, storagePermissionCode);
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, cameraPermissionCode);
} else {
ContentValues values = new ContentValues();
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, cameraRequestCode);
}
}
});
2) In onActivityResult :
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode == cameraRequestCode) {
if (resultCode == Activity.RESULT_OK) {
FileOutputStream stream = null;
try {
Bitmap photo = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
String saveFilePath = getRealPathFromURI(imageUri);
stream = new FileOutputStream(saveFilePath);
photo.compress(Bitmap.CompressFormat.JPEG, 25, stream);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Can't save image !", Toast.LENGTH_SHORT).show();
} finally {
try {
if (stream != null) {
stream.close();
Toast.makeText(getApplicationContext(), "Image saved successfully !", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Can't save image, try again !", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Can't capture image !", Toast.LENGTH_SHORT).show();
}
}
}
3) getRealPathFromURI function :
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Related
Android version 12 camera and gallery not working solution
I am working on a camera application with camera API. I am able to save the image to the picture directory and set it to the image view till android version 11 but on android 12, the image is getting saved to the picture directory but not getting set to the image view I am getting an error
My Code is
Profile.java
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.cocosw.bottomsheet.BottomSheet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xxx.xx.view.MainFragment;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Profile extends AppCompatActivity implements View.OnClickListener {
private ActivityProfileBinding binding;
private String TAG = Profile.class.getSimpleName();
private Context mContext;
private ArrayList<ImageDTO> imageDatalist = new ArrayList<>();
private SharedPrefrence prefrence;
private LoginDTO loginDTO;
private HashMap<String, String> parms = new HashMap<>();
String dob = "";
String[] arrOfStr;
BottomSheet.Builder builder;
Uri picUri;
int PICK_FROM_CAMERA = 1, PICK_FROM_GALLERY = 2;
int CROP_CAMERA_IMAGE = 3, CROP_GALLERY_IMAGE = 4;
String imageName;
String pathOfImage;
Bitmap bm;
int flag = 1;
ImageCompression imageCompression;
byte[] resultByteArray;
File file;
Bitmap bitmap = null;
private HashMap<String, File> paramsFile = new HashMap<>();
HashMap<String, String> values = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
mContext = Profile.this;
prefrence = SharedPrefrence.getInstance(mContext);
loginDTO = prefrence.getLoginResponse(Consts.LOGIN_DTO);
parms.put(Consts.USER_ID, loginDTO.getUser_id());
values.put(Consts.USER_ID, loginDTO.getUser_id());
setUiaction();
}
public void setUiaction() {
binding.collapsingToolbar.setExpandedTitleColor(Color.TRANSPARENT);
binding.collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
binding.collapsingToolbar.setTitle("Profile");
binding.rlBio.setOnClickListener(this);
binding.ivCamera.setOnClickListener(this);
binding.rlGallaryClick.setOnClickListener(this);
binding.back.setOnClickListener(this);
binding.ivEditSelf.setOnClickListener(this);
binding.ivEditAbout.setOnClickListener(this);
binding.ivEditAppearance.setOnClickListener(this);
binding.ivEditImportant.setOnClickListener(this);
binding.ivEditCritical.setOnClickListener(this);
binding.ivEditLifestyle.setOnClickListener(this);
binding.ivEditFamily.setOnClickListener(this);
builder = new BottomSheet.Builder(Profile.this).sheet(R.menu.menu_cards);
builder.title(getResources().getString(R.string.select_img));
builder.listener(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case R.id.camera_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
ProjectUtils.pauseProgressDialog();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile);
picUri = FileProvider.getUriForFile(Profile.this.getApplicationContext(), Profile.this.getApplicationContext().getPackageName() + ".fileprovider", file);
} else {
picUri = Uri.fromFile(file); // create
}
prefrence.setValue(Consts.IMAGE_URI_CAMERA, picUri.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri); // set the image file
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case R.id.gallery_cards:
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
if (ProjectUtils.hasPermissionInManifest(Profile.this, PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
File file = getOutputMediaFile(1);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
picUri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_pic)), PICK_FROM_GALLERY);
}
}
break;
case R.id.cancel_cards:
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
}
});
break;
}
}
});
}
private File getOutputMediaFile(int type) {
String root = Environment.getExternalStorageDirectory().toString();
File mediaStorageDir = new File(root, Consts.APP_NAME);
/**Create the storage directory if it does not exist*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
Consts.APP_NAME + timeStamp + ".png");
imageName = Consts.APP_NAME + timeStamp + ".png";
} else {
return null;
}
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CROP_CAMERA_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
//bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
// bitmap = MediaStore.Images.Media.getBitmap(SaveDetailsActivityNew.this.getContentResolver(), resultUri);
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
Log.e("image", imagePath);
changeImage();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == CROP_GALLERY_IMAGE) {
if (data != null) {
picUri = Uri.parse(data.getExtras().getString("resultUri"));
try {
bm = MediaStore.Images.Media.getBitmap(Profile.this.getContentResolver(), picUri);
pathOfImage = picUri.getPath();
imageCompression = new ImageCompression(Profile.this);
imageCompression.execute(pathOfImage);
imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
#Override
public void processFinish(String imagePath) {
Glide.with(Profile.this).load("file://" + imagePath)
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(binding.ivProfileImage);
try {
file = new File(imagePath);
paramsFile.put(Consts.USER_AVTAR, file);
changeImage();
Log.e("image", imagePath);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (requestCode == PICK_FROM_CAMERA && resultCode == RESULT_OK) {
if (picUri != null) {
picUri = Uri.parse(prefrence.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
} else {
picUri = Uri.parse(prefrence
.getValue(Consts.IMAGE_URI_CAMERA));
startCropping(picUri, CROP_CAMERA_IMAGE);
}
}
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
try {
Uri tempUri = data.getData();
Log.e("front tempUri", "" + tempUri);
if (tempUri != null) {
startCropping(tempUri, CROP_GALLERY_IMAGE);
} else {
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public void startCropping(Uri uri, int requestCode) {
Intent intent = new Intent(Profile.this, MainFragment.class);
intent.putExtra("imageUri", uri.toString());
intent.putExtra("requestCode", requestCode);
startActivityForResult(intent, requestCode);
}
#Override
protected void onResume() {
super.onResume();
if (NetworkManager.isConnectToInternet(mContext)) {
getImages();
} else {
ProjectUtils.showToast(mContext, getResources().getString(R.string.internet_concation));
}
}
public void getImages() {
new HttpsRequest(Consts.GET_GALLARY_API, parms, mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
getMyProfile();
if (flag) {
try {
imageDatalist = new ArrayList<>();
Type getpetDTO = new TypeToken<List<ImageDTO>>() {
}.getType();
imageDatalist = (ArrayList<ImageDTO>) new Gson().fromJson(response.getJSONArray("data").toString(), getpetDTO);
if (imageDatalist.size() > 0) {
} else {
imageDatalist = new ArrayList<>();
}
} catch (JSONException e) {
e.printStackTrace();
imageDatalist = new ArrayList<>();
}
} else {
imageDatalist = new ArrayList<>();
}
}
});
}
#Override
public void onBackPressed() {
//super.onBackPressed();
finish();
overridePendingTransition(R.anim.anim_slide_in_right,
R.anim.anim_slide_out_right);
}
public void getMyProfile() {
ProjectUtils.showProgressDialog(mContext, true, getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.MY_PROFILE_API, getparmProfile(), mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
try {
loginDTO = new Gson().fromJson(response.getJSONObject("data").toString(), LoginDTO.class);
prefrence.setLoginResponse(loginDTO, Consts.LOGIN_DTO);
showData();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ProjectUtils.showToast(mContext, msg);
}
}
});
}
public HashMap<String, String> getparmProfile() {
HashMap<String, String> parms = new HashMap<>();
parms.put(Consts.USER_ID, loginDTO.getUser_id());
Log.e(TAG + " My Profile", parms.toString());
return parms;
}
public void changeImage() {
new HttpsRequest(Consts.SET_PROFILE_IMAGE_API, values,paramsFile, mContext).imagePost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
if (flag) {
getMyProfile();
} else {
}
}
});
}
}
MainFragment.java
import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import com.xxx.xx.R;
import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.callback.CropCallback;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.isseiaoki.simplecropview.callback.SaveCallback;
import com.isseiaoki.simplecropview.util.Utils;
import java.io.File;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
#RuntimePermissions
public class MainFragment extends FragmentActivity {
private static final int REQUEST_PICK_IMAGE = 10011;
private static final int REQUEST_SAF_PICK_IMAGE = 10012;
private static final String PROGRESS_DIALOG = "ProgressDialog";
Uri myUri;
int requestCode;
private CropImageView mCropView;
private LinearLayout mRootLayout;
public MainFragment() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
myUri = Uri.parse(getIntent().getExtras().getString("imageUri"));
requestCode = getIntent().getExtras().getInt("requestCode");
bindViews();
FontUtils.setFont(mRootLayout);
mCropView.startLoad(myUri, mLoadCallback);
mCropView.setCropMode(CropImageView.CropMode.FREE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
if (requestCode == REQUEST_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = result.getData().toString();
mCropView.startLoad(result.getData(), mLoadCallback);
} else if (requestCode == REQUEST_SAF_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
showProgress();
String uri = Utils.ensureUriPermission(this, result).toString();
mCropView.startLoad(Utils.ensureUriPermission(this, result), mLoadCallback);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
MainFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
private void bindViews() {
mCropView = (CropImageView) findViewById(R.id.cropImageView);
findViewById(R.id.buttonDone).setOnClickListener(btnListener);
findViewById(R.id.buttonFitImage).setOnClickListener(btnListener);
findViewById(R.id.button1_1).setOnClickListener(btnListener);
findViewById(R.id.button3_4).setOnClickListener(btnListener);
findViewById(R.id.button4_3).setOnClickListener(btnListener);
findViewById(R.id.button9_16).setOnClickListener(btnListener);
findViewById(R.id.button16_9).setOnClickListener(btnListener);
findViewById(R.id.buttonFree).setOnClickListener(btnListener);
findViewById(R.id.buttonPickImage).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateLeft).setOnClickListener(btnListener);
findViewById(R.id.buttonRotateRight).setOnClickListener(btnListener);
findViewById(R.id.buttonCustom).setOnClickListener(btnListener);
findViewById(R.id.buttonCircle).setOnClickListener(btnListener);
findViewById(R.id.buttonShowCircleButCropAsSquare).setOnClickListener(btnListener);
mRootLayout = (LinearLayout) findViewById(R.id.layout_root);
}
#NeedsPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
public void pickImage() {
if (Build.VERSION.SDK_INT >= 33) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), REQUEST_PICK_IMAGE);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_SAF_PICK_IMAGE);
}
}
#NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void cropImage() {
showProgress();
Log.e("cropImage", "called");
mCropView.startCrop(createSaveUri(), mCropCallback, mSaveCallback);
}
#OnShowRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
public void showRationaleForPick(PermissionRequest request) {
showRationaleDialog(R.string.permission_pick_rationale, request);
}
#OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void showRationaleForCrop(PermissionRequest request) {
showRationaleDialog(R.string.permission_crop_rationale, request);
}
public void showProgress() {
ProgressDialogFragment f = ProgressDialogFragment.getInstance();
getSupportFragmentManager()
.beginTransaction()
.add(f, PROGRESS_DIALOG)
.commitAllowingStateLoss();
}
public void dismissProgress() {
// if (!isAdded()) return;
FragmentManager manager = getSupportFragmentManager();
if (manager == null) return;
ProgressDialogFragment f = (ProgressDialogFragment) manager.findFragmentByTag(PROGRESS_DIALOG);
if (f != null) {
getSupportFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
}
}
public Uri createSaveUri() {
return Uri.fromFile(new File(this.getCacheDir(), "cropped"));
}
private void showRationaleDialog(#StringRes int messageResId, final PermissionRequest request) {
new AlertDialog.Builder(this)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.proceed();
}
})
.setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.cancel();
}
})
.setCancelable(false)
.setMessage(messageResId)
.show();
}
// Handle button event /////////////////////////////////////////////////////////////////////////
private final View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonDone:
MainFragmentPermissionsDispatcher.cropImageWithCheck(MainFragment.this);
break;
case R.id.buttonFitImage:
mCropView.setCropMode(CropImageView.CropMode.FIT_IMAGE);
break;
case R.id.button1_1:
mCropView.setCropMode(CropImageView.CropMode.SQUARE);
break;
case R.id.button3_4:
mCropView.setCropMode(CropImageView.CropMode.RATIO_3_4);
break;
case R.id.button4_3:
mCropView.setCropMode(CropImageView.CropMode.RATIO_4_3);
break;
case R.id.button9_16:
mCropView.setCropMode(CropImageView.CropMode.RATIO_9_16);
break;
case R.id.button16_9:
mCropView.setCropMode(CropImageView.CropMode.RATIO_16_9);
break;
case R.id.buttonCustom:
mCropView.setCustomRatio(7, 5);
break;
case R.id.buttonFree:
mCropView.setCropMode(CropImageView.CropMode.FREE);
break;
case R.id.buttonCircle:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE);
break;
case R.id.buttonShowCircleButCropAsSquare:
mCropView.setCropMode(CropImageView.CropMode.CIRCLE_SQUARE);
break;
case R.id.buttonRotateLeft:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
break;
case R.id.buttonRotateRight:
mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
break;
case R.id.buttonPickImage:
MainFragmentPermissionsDispatcher.pickImageWithCheck(MainFragment.this);
break;
}
}
};
// Callbacks ///////////////////////////////////////////////////////////////////////////////////
private final LoadCallback mLoadCallback = new LoadCallback() {
#Override
public void onSuccess() {
dismissProgress();
Log.e("", "success");
}
#Override
public void onError() {
dismissProgress();
Log.e("", "error");
}
};
private final CropCallback mCropCallback = new CropCallback() {
#Override
public void onSuccess(Bitmap cropped) {
}
#Override
public void onError() {
}
};
private final SaveCallback mSaveCallback = new SaveCallback() {
#Override
public void onSuccess(Uri outputUri) {
dismissProgress();
//addPicture.startResultActivity(outputUri);
Intent i = getIntent();
i.putExtra("resultUri", outputUri.toString());
setResult(requestCode, i);
finish();
}
#Override
public void onError() {
dismissProgress();
}
};
}
ProjectUtils.java
public static boolean hasPermissionInManifest(Context context, int requestCode, String permissionName) {
if (Build.VERSION.SDK_INT >= 29) {
Log.w(TAG, "hasPermissions: API version >= 29, returning true by default");
// DANGER ZONE!!! Changing this will break the library.
return true;
}
if (context == null) {
throw new IllegalArgumentException("Can't check permissions for null context");
}
if (ContextCompat.checkSelfPermission(context,
permissionName)
!= PackageManager.PERMISSION_GRANTED) {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions((Activity) context,
new String[]{permissionName},
requestCode);
} else {
return true;
}
return false;
}
AndroidManifest.java
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"
tools:ignore="ScopedStorage" />
<!--Permission for the Android 11 and above-->
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
android:requestLegacyExternalStorage="true"
've also added requestLegacyExternalStorage="true" to the application tag in the manifest to get it to work for the APIs below Android 12. Stuck with this issue since yesterday, Please help.
Android version 12 camera and gallery not working solution
Everytime I try to go between activities, I save the editText texts because user experience and all that, but for some reason, while intents get through no problem, the savedinstanceState just won't ever be not null. I've added the onSave and onRestore methods, overrided them, did what had to be done inside, yet it is always null. What am I missing here?
package com.gmproxy.pastilarma;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import com.gmproxy.DAO.PathologyUserRepository;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import com.gmproxy.Util.ImageConverter;
import com.gmproxy.ViewModels.UserViewModel;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserAddScreen extends AppCompatActivity {
Button gotoBack, addObservation, saveUser, addPathologies;
EditText addUsername, addSurname, addAge, addRoomNumber;
Spinner addGender;
ImageView selectImage;
String obs;
Pathology paths;
Context context;
UserViewModel userViewModel;
int pathAct = 0;
int obsAct = 0;
PathologyUserRepository paUsRe;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
context = this.getApplicationContext();
pathAct = getIntent().getIntExtra("path-record", 0);
obsAct = getIntent().getIntExtra("obs-record", 0);
paUsRe = new PathologyUserRepository(this.getApplication());
setContentView(R.layout.activity_user_add_screen);
gotoBack = findViewById(R.id.GotoBack);
addObservation = findViewById(R.id.AddObservation);
saveUser = findViewById(R.id.SaveUser);
addPathologies = findViewById(R.id.AddPathologies);
addUsername = findViewById(R.id.AddUsername);
addSurname = findViewById(R.id.AddSurname);
addAge = findViewById(R.id.AddAge);
addRoomNumber = findViewById(R.id.AddRoomNumber);
addGender = findViewById(R.id.AddGender);
selectImage = findViewById(R.id.SelectImage);
if (pathAct == 1 || obsAct == 1 && savedInstanceState!=null) {
onRestoreInstanceState(savedInstanceState);
}
if (savedInstanceState == null){
Log.println(Log.INFO,"Test","El bundle está vacio");
}
userViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(UserViewModel.class);
/*
From this line to 94, we create the spinner, since there's only two options there really is no need of poblating the list from the database.
*/
List<String> genderList = new ArrayList<>();
genderList.add("M");
genderList.add("F");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner, genderList);
adapter.setDropDownViewResource(R.layout.spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addGender.setAdapter(adapter);
addGender.setSelection(0);
if (savedInstanceState == null){
obs = intent.getStringExtra("observation");
} else {
obs = savedInstanceState.getString("Observacion-usuario");
}
if (obs != null){
Log.println(Log.INFO,"test obs", obs);
}
paths = (Pathology) intent.getSerializableExtra("paths");
}
public void gotoBack(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
}
public void addObservation(View view) {
Intent mainAct = new Intent(UserAddScreen.this, UserObservationScreen.class);
startActivity(mainAct);
finish();
}
public void addPathology(View view) {
Intent mainAct = new Intent(UserAddScreen.this, PathologiesSearchScreen.class);
startActivity(mainAct);
finish();
}
/**
* This saves all recorded data for when we come back to the activity
* #param savedInstanceState
*/
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
if (!addUsername.getText().toString().equals("")) {
savedInstanceState.putString("Nombre_usuario", addUsername.getText().toString());
}
if (!addSurname.getText().toString().equals("")) {
savedInstanceState.putString("Apellido_usuario", addSurname.getText().toString());
}
if (!addAge.getText().toString().equals("")) {
savedInstanceState.putString("Edad_usuario", addAge.getText().toString());
}
if (!addRoomNumber.getText().toString().equals("")) {
savedInstanceState.putString("Habitacion_usuario", addRoomNumber.getText().toString());
}
savedInstanceState.putInt("Sexo_usuario", addGender.getSelectedItemPosition());
if (obs != null){
savedInstanceState.putString("Observacion-usuario", obs);
}
if (paths != null){
savedInstanceState.putSerializable("Patologia-usuario", paths);
}
super.onSaveInstanceState(savedInstanceState);
Log.println(Log.INFO,"Guardado","guardado");
}
/**
* This loads up all recorded things in the view
* #param savedInstanceState
*/
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
addUsername.setText(savedInstanceState.getString("Nombre_usuario"));
addSurname.setText(savedInstanceState.getString("Apellido_usuario"));
addAge.setText(savedInstanceState.getString("Edad_usuario"));
addRoomNumber.setText(savedInstanceState.getString("Habitacion_usuario"));
addGender.setSelection(savedInstanceState.getInt("Sexo_usuario"));
obs = savedInstanceState.getString("Observacion-usuario");
paths = (Pathology) savedInstanceState.getSerializable("Patologia-usuario");
}
/*
The next two methods are for
A: Opening either the camera, gallery, or getting a picture from assets
B: Actually selecting the image and making it show in the imageButton
*/
public void selectImageAction(View view) {
final CharSequence[] options = {"Hacer una foto", "Elegir de la galería", "Usar una genérica", "Cancelar"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserAddScreen.this);
builder.setTitle("¡Añade una foto!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Hacer una foto")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivity(intent);
finish();
} else if (options[item].equals("Elegir de la galería")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivity(intent);
finish();
} else if (options[item].equals("Cancelar")) {
dialog.dismiss();
} else if (options[item].equals("Usar una genérica")) {
selectImage.setImageResource(R.drawable.ic_user_generic_foreground);
selectImage.setBackgroundResource(R.drawable.ic_user_generic_foreground);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
selectImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, System.currentTimeMillis() + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("..******************...", picturePath + "");
ImageView viewImage;
selectImage.setImageBitmap(thumbnail);
}
}
}
/**
* Actually creates the user in the database
* #param view
*/
public void saveUser(View view) {
//Just this to turn the image into a blob
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.id.SelectImage);
ImageConverter imgCon = new ImageConverter();
byte[] bytearray = imgCon.bitmapToBiteArray(bitmap);
if (addUsername.getText().toString() != null || addSurname.getText().toString() != null
|| addAge.getText().toString() != null || addRoomNumber.getText().toString() != null){
Toast.makeText(this, "Usuario creado.", Toast.LENGTH_SHORT).show();
User user = new User(addUsername.getText().toString(), addSurname.getText().toString(), addAge.getText().toString(),
Integer.parseInt(addRoomNumber.getText().toString()), addGender.getSelectedItem().toString(), obs, bytearray);
userViewModel.insert(user);
paUsRe.insertObject(userViewModel.getIdByNameAndSurname(user.getUser_name(), user.getUser_surname()), paths.getId_pathology());
Toast.makeText(this, "Patología " + paths.getPathologyName() + " añadida", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
startActivity(mainAct);
finish();
} else {
Toast.makeText(this, "Por favor, introduce todos los parámetros necesarios.", Toast.LENGTH_SHORT).show();
}
}
}
onSaveInstanceState() is called right before your activity is about to be killed or restarted because of memory pressure or screen orientation change. Since you are just switching between activities, onSaveInstance() is not called thus the null instance. Wound suggest SharedPreference instead
I m trying to make a web view app of a web page where user can upload a file (image) to a form and submit.
however, the web app works just fine, but couldn't able to select any file through input type="file" field and submit.
I did gone through other stack queries over this issues like but unfortunately I still need help on this particular issue.
My code goes as :
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_SELECT_FILE = 100;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> uploadMessage;
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webviewid);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("website url");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
uploadMessage = null;
Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
}
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
if(webView.canGoBack()){
webView.goBack();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
The file can't be uploaded since its not returning with file path in the input field upon selecting.
Any help is greatly appreciated..
So, after hours of articles in androdi studio.. i finally found the solution.
Hope this helps some one like me.,
AndoridManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.suman.demo">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.Java
package com.package.name;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private final static int FCR = 1;
WebView webView;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview_sample);
if (Build.VERSION.SDK_INT >= 23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new Callback());
webView.loadUrl("website name goes here");
webView.setWebChromeClient(new WebChromeClient() {
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
});
}
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater myMenuInflater = getMenuInflater();
myMenuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myMenuOne:
onBackPressed();
break;
case R.id.myMenuTwo:
GoForward();
break;
}
return true;
}
private void GoForward() {
if (webView.canGoForward()) {
webView.goForward();
} else {
Toast.makeText(this, "Can't go further!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
}
}
}
Super_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.filechooser.file.MainActivity">
<item
android:id="#+id/myMenuOne"
android:icon="#drawable/ic_arrow_back_black_24dp"
android:title="Item"
app:showAsAction="always" />
<item
android:id="#+id/myMenuTwo"
android:icon="#drawable/ic_arrow_forward_black_24dp"
android:title="Item"
app:showAsAction="always" />
</menu>
Thanks to those who took the time on checking my query.
Happy to Help.
I am using a "ACTION_OPEN_DOCUMENT" intent to choose a file and open it.
This works just fine when I go to read the file.
However, when the file resides on EXTERNAL storage, and I run a query to obtain the file name, my program crashes. If the file resides on INTERNAL storage, I have no issues.
I DO have (and check for) external storage access permissions.
I have the query enclosed in a try{}, but the exception is not caught. I am developing on a Chrome book, so I am unable to run the debugger on it. But I have isolated the issue to the result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); statement.
I know that access to files on external storage has been limited, but I would think that if I can read a file that I should also be able to query it as well.
Here is my code:
package com.muddco.demo3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
Activity mAct;
TextView rvalue, fnamevalue;
Button btn1, btn2;
Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
rvalue = findViewById(R.id.readResult);
fnamevalue = findViewById(R.id.textView2);
mAct = this;
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Launch a file picker
*/
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select a GPX file"), 1);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Get and display file name
*/
String fname = getFileName(fileUri);
fnamevalue.setText(fname);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted and now can proceed
Toast.makeText(MainActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// add other cases for more permissions
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream inputStream = null;
Uri uri = null;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
// Process GPX file
uri = data.getData();
try {
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
rvalue.setText(readFile(inputStream));
} catch (FileNotFoundException e) {
Toast.makeText(this, "File not found: " + uri.toString(), Toast.LENGTH_SHORT).show();
}
//String fName = getFileName(uri);
//Toast.makeText(mAct, "Filename: "+fName, Toast.LENGTH_LONG).show();
fileUri = uri;
btn2.setVisibility(View.VISIBLE);
}
}
}
/*
* Read a FileStream
*
*/
String readFile(InputStream is) {
String ret = "";
String line = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
ret += line + "\n";
}
br.close();
} catch (Exception e) {
// if any I/O error occurs
e.printStackTrace();
ret = "Exception!";
}
return ret;
}
/*
* Obtain the filename from a URI
*/
public String getFileName(Uri uri) {
String result = "<empty>";
Cursor cursor;
if (uri.getScheme().equals("content")) {
ContentResolver cr = getContentResolver();
try {
cursor = cr.query(uri, null, null, null, null);
} catch (Exception e) {
Toast.makeText(this, "Cursor exception: " + e.toString(), Toast.LENGTH_LONG).show();
return null;
}
try {
if (cursor != null && cursor.moveToFirst()) {
//
// THE NEXT STATEMENT CRASHES WHEN FILE RESIDES ON EXTERNAL STORAGE
//
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
else {
Toast.makeText(mAct, "Bad cursor", Toast.LENGTH_SHORT).show();
return "Bad Cursor";
}
} catch (Exception e) {
Toast.makeText(this, "Cursor exception: " + e.toString(), Toast.LENGTH_LONG).show();
return "Cursoe Exception";
} finally {
cursor.close();
}
}
else
result="Non content URI";
return result;
}
}
When I press the first button, the file requestor pops up and I select my test text file. The contents of the file are listed in a textbox, then a second button is made visible. When that second button is pressed, I query the file and place the filename in a second textbox.
The entire project, along with the test.txt file I am using to test, can be found here
why when i trying to upload image with size 1.5 mb it's said error while uploading, but actually the image is successfully upload? and if i trying to upload with size 100 kb it's said Image Uploaded Successfully
WC_Activity.java
package com.emergency.e_place;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.kosalgeek.android.photoutil.CameraPhoto;
import com.kosalgeek.android.photoutil.GalleryPhoto;
import com.kosalgeek.android.photoutil.ImageBase64;
import com.kosalgeek.android.photoutil.ImageLoader;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.EachExceptionsHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.HashMap;
/**
* Created by Eggy on 5/3/2016.
*/
public class WC_Activity extends AppCompatActivity {
final String TAGS = "DEBUG";
String Latitude;
String Longitude;
private final String TAG = this.getClass().getName();
ImageView ivCamera, ivGallery, ivUpload, ivImage;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;
final int CAMERA_REQUEST = 13323;
final int GALLERY_REQUEST = 22131;
String selectedPhoto;
EditText etIpAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbarWC);
setSupportActionBar(toolbar);
//ambil lokasi dari MainActivity
Intent myIntent = getIntent(); // gets the previously created intent
Latitude = myIntent.getStringExtra("Latitude"); // will return "FirstKeyValue"
Longitude= myIntent.getStringExtra("Longitude"); // will return "SecondKeyValue"
Log.d(TAGS, "onLocationChanged: " + Longitude);
etIpAddress = (EditText)findViewById(R.id.etIpAddress);
cameraPhoto = new CameraPhoto(getApplicationContext());
galleryPhoto = new GalleryPhoto(getApplicationContext());
ivImage = (ImageView)findViewById(R.id.ivImage);
ivCamera = (ImageView)findViewById(R.id.ivCamera);
ivGallery = (ImageView)findViewById(R.id.ivGallery);
ivUpload = (ImageView)findViewById(R.id.ivUpload);
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startActivityForResult(cameraPhoto.takePhotoIntent(), CAMERA_REQUEST);
cameraPhoto.addToGallery();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while taking photos", Toast.LENGTH_SHORT).show();
}
}
});
ivGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(galleryPhoto.openGalleryIntent(), GALLERY_REQUEST);
}
});
ivUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedPhoto == null || selectedPhoto.equals("")){
Toast.makeText(getApplicationContext(), "No Image Selected.", Toast.LENGTH_SHORT).show();
return;
}
try {
Bitmap bitmap = ImageLoader.init().from(selectedPhoto).requestSize(1024, 1024).getBitmap();
String encodedImage = ImageBase64.encode(bitmap);
Log.d(TAG, encodedImage);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("image", encodedImage);
PostResponseAsyncTask task = new PostResponseAsyncTask(WC_Activity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if(s.contains("uploaded_success")){
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully.",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Error while uploading.",
Toast.LENGTH_SHORT).show();
}
}
});
String ip = etIpAddress.getText().toString();
task.execute("http://" +ip + "/AndroidUpload/upload.php");
task.setEachExceptionsHandler(new EachExceptionsHandler() {
#Override
public void handleIOException(IOException e) {
Toast.makeText(getApplicationContext(), "Cannot Connect to Server.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleMalformedURLException(MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleProtocolException(ProtocolException e) {
Toast.makeText(getApplicationContext(), "Protocol Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(), "Encoding Error.",
Toast.LENGTH_SHORT).show();
}
});
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while encoding photos", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST){
String photoPath = cameraPhoto.getPhotoPath();
selectedPhoto = photoPath;
Bitmap bitmap = null;
try {
bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(getRotatedBitmap(bitmap, 90));
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while loading photos", Toast.LENGTH_SHORT).show();
}
}
else if(requestCode == GALLERY_REQUEST){
Uri uri = data.getData();
galleryPhoto.setPhotoUri(uri);
String photoPath = galleryPhoto.getPath();
selectedPhoto = photoPath;
try {
Bitmap bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while choosing photos", Toast.LENGTH_SHORT).show();
}
}
}
}
private Bitmap getRotatedBitmap(Bitmap source, float angle){
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap bitmap1 = Bitmap.createBitmap(source,
0, 0, source.getWidth(), source.getHeight(), matrix, true);
return bitmap1;
}
}