Code for picking an image from gallery
private void pickImageFromGallery() {
Intent intent=new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_CODE:{
if(grantResults.length >0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
pickImageFromGallery();
}else {
Toast.makeText(this,"access denied", Toast.LENGTH_LONG).show();
}
}
}
}
To handle the picked image, i inflated the layout_ticket which contains image view.Assigned the image to it which i picked.
// handle the picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(resultCode==RESULT_OK && requestCode==IMAGE_PICK_CODE){
LayoutInflater mInflater = getLayoutInflater();
View myView = mInflater.inflate(R.layout.layout_ticket, null);
ImageView imageview = (ImageView) myView.findViewById(R.id.imageview);
imageview.setImageURI(data.getData());
}
}
}
Related
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.btncheck);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
intent.putExtra("extra_pkgname", getPackageName());
startActivity(intent);
}
});
}
It code only navigate and display other permission screen but not working in require permission.
How to enable and disav other permission in mi phone in android studio
Image here
What kind of permissions do you need?
If I understand you correctly, this should help.
in MainActivity:
private final int REQUEST_CODE_PERMISSIONS = 1001;
private final String[] REQUIRED_PERMISSIONS = new String[]{
"android.permission.CAMERA",
"android.permission.ACCESS_FINE_LOCATION",
"android.permission.RECORD_AUDIO",
"android.permission.INTERNET",
"android.permission.WRITE_EXTERNAL_STORAGE"};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (!allPermissionsGranted()) {
createToast(getString(R.string.error_permission));
finish();
}
}
}
private boolean allPermissionsGranted(){
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this , permission)
!= PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
if(allPermissionsGranted()){
Log.d("TAG", "OK");
} else{
ActivityCompat.requestPermissions(this,
REQUIRED_PERMISSIONS,
REQUEST_CODE_PERMISSIONS);
}
...
}
I want to pick multiple or single images from phone gallery. But my code returning null pointer also one major problem I have notice the createChooser runs twice.
After tries two pick image two time it sends me to the parent activity
OnCreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item_business);
ItemName = findViewById(R.id.item_name);
ItemDes = findViewById(R.id.item_des);
pickImage = findViewById(R.id.pickImage);
ChooseImageList = new ArrayList<>();
UrlsList = new ArrayList<>();
pickImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPermission();
PickImageFromGallery();
}
});
}
Checking Permission
private void CheckPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(addItemBusiness.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(addItemBusiness.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
} else {
PickImageFromGallery();
}
}
}
Move to gallery
private void PickImageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select images"), 100);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("result", "inside activity result");
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Log.i("result", "result is ok");
if (data.getClipData() != null) {
Log.i("result", "fine");
int count = data.getClipData().getItemCount();
for (int i = 0; i < count; i++) {
ImageUri = data.getClipData().getItemAt(i).getUri();
ChooseImageList.add(ImageUri);
SetAdapter();
}
} else if (data.getData() != null) {
Log.i("result", "clip data is null");
ImageUri = data.getData();
ChooseImageList.add(ImageUri);
SetAdapter();
}
}
}
Adapter
private void SetAdapter(){
ViewPagerAdapter adapter = new ViewPagerAdapter(this, ChooseImageList);
viewPager.setAdapter(adapter);
}
Adapter Class
private Context context;
ArrayList<Uri> ImageUrls;
LayoutInflater layoutInflater;
public ViewPagerAdapter(Context context, ArrayList<Uri> imageUrls) {
this.context = context;
ImageUrls = imageUrls;
layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return ImageUrls.size();
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
View view=layoutInflater.inflate(R.layout.show_imgaes_layout,container,false);
ImageView imageView=view.findViewById(R.id.UploadImage);
imageView.setImageURI(ImageUrls.get(position));
container.addView(view);
return view ;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view== object;
}
#Override
public void destroyItem(#NonNull View container, int position, #NonNull Object object) {
((RelativeLayout)object).removeView(container);
}
Hope that you can find the issue. Thank you
I am starting to program in Android and I am testing some functionalities. now I'm trying to get an image from the gallery and save it to a byte array. The problem is that the code that I leave below, works for images saved in the internal memory but not for those that are in the SD, I already spent 3 hours searching to see what it could be but nothing worked for now. Thank you and have a good day!
In the manifest I have this line
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
and the fragment has this code:
public class PhotoFragment extends Fragment {
private ImageButton buttonphoto;
private Context mContext;
private byte[] bytes;
public void getPhoto(){
Intent photoPicker = new Intent(Intent.ACTION_GET_CONTENT);
photoPicker.setType("image/*");
startActivityForResult(photoPicker, 2);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 2){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
getPhoto();
}
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_report, container, false);
buttonphoto = v.findViewById(R.id.fragmentreportesCameraButton);
buttonphoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ActivityCompat.checkSelfPermission(getContext(),Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},2);
}else{
getPhoto();
}
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri images = data.getData();
if(requestCode == 2 && resultCode == Activity.RESULT_OK && data !=null){
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),images);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Toast.makeText(mContext,"agarro?",Toast.LENGTH_SHORT).show();
bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
bytes = stream.toByteArray();
}catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext = context;
}
}
Android Level 10,11 changing your privacy policy. In this policy we cannot get data directly then add this tag in the manifest file inside the application tag:
android:requestLegacyExternalStorage="true"
I've one MainActivity, and few fragments on it.
I am trying to change a ImageView in a fragment using Gallery. But once image is selected, the MainActivity get refresh, which changes the MainActivity back to the default fragment.
Getting permission
textViewChangeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG,"Select Image executed");
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE);
}
});
On Request permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG,"Select Image Permission executed");
if(requestCode == REQUEST_CODE){
progressDialogUploadDp.setMessage("Uploading...");
progressDialogUploadDp.show();
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.putExtra("imageUpdate","true");
startActivityForResult(intent,REQUEST_CODE);
}else{
Toast.makeText(getActivity(), "No Permission Granted", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
On Activity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null){
try {
Uri uri = data.getData();
StorageReference filepath =
storageReference.child("Photos").child("DPs").child(ID).child("profilepicture.jpg");
InputStream inputStream = getActivity().getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageviewpropic.setImageBitmap(bitmap);
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialogUploadDp.hide();
progressDialogUploadDp.dismiss();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Looking forward for a solution!
Updated ---
MainActivity
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null) {
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("questioners")) {
adapter = new SectionStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment(), "HomeFragment");
viewPager.setAdapter(adapter);
}}
}
Back form gallery , activity will run onActivityResult then it will run onResume .
so you can set a FLAG at onActivityResult and make an IF in onResume to set your fragment.
From what you've said it looks like your activity is calling onCreate method and setting default fragment again. What you can do is to in onCreate() create new fragment only if there is no saved state.
if(savedInstanceState==null) setFragment(fragment);
I'm starting DialogFragment from AddFragment by calling showPickImageDialog() method on button press. And in AlertDialogFragment onActivityResult I'm sending results back to AddFragment but AddFragment is not receiving any results. Any ideas why?
AddFragment:
public class AddFragment extends Fragment {
private static final int REQUEST_IMAGE = 3;
private static final String DIALOG_IMAGE = "image";
private static final String TAG = "TAG";
void showPickImageDialog() {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
AlertDialogFragment pdialog = new AlertDialogFragment();
pdialog.setTargetFragment(this, REQUEST_IMAGE);
pdialog.show(fm, DIALOG_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){
Log.e(TAG,"back in AddFragment");
}
}
}
In AlertDialogFragment Im calling sendResult method from onActivityResult method. SendResult method is called I checked it with Logs
AlertDialogFragment:
public class AlertDialogFragment extends DialogFragment {
private final static String TAG = "Cload";
public static final String EXTRA_PHOTOFILENAME =
"com.example.tadas.dreamcload1.image";
private static final int REQUEST_IMAGE = 3;
private String filename;
private Uri uri;
private void sendResult(int resultCode) {
if(getTargetFragment() == null){return;}
Intent i = new Intent();
i.putExtra(EXTRA_PHOTOFILENAME,filename);
getTargetFragment()
.onActivityResult(getTargetRequestCode(), resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//LayoutInflater inflater = getLayoutInflater();
// View dialogLaout = inflater.inflate(R.layout.custom_dialog_pick_image,null);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.custom_dialog_pick_image, null);
final AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setView(view)
.create();
ImageButton gallerybtn = (ImageButton)view.findViewById(R.id.gallery);
ImageButton camerabtn = (ImageButton)view.findViewById(R.id.camera);
gallerybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG,"gallery btn pressed");
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_IMAGE);
}
});
camerabtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return dialog;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){
uri = data.getData();
final String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME};
Cursor c = getActivity().getContentResolver()
.query(uri,filePathColumn,null,null,null);
if (c.moveToFirst()){
int ids = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
uri = Uri.parse(c.getString(ids));
filename = uri.toString();
c.close();
}
sendResult(Activity.RESULT_OK);
dismiss();
}
}
You can override your onActivityResult method in your Activity and call your Fragment's onActivityResult manually like below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_container);
fragment.onActivityResult(requestCode, resultCode, data);
}
You can define this part in your Activity's onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK){
uri = data.getData();
final String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME};
Cursor c = getActivity().getContentResolver()
.query(uri,filePathColumn,null,null,null);
if (c.moveToFirst()){
int ids = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
uri = Uri.parse(c.getString(ids));
filename = uri.toString();
c.close();
}
// You do not need this any more
//sendResult(Activity.RESULT_OK);
//dismiss();
// Just find your fragment and call it's onActivityResult
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.your_container);
fragment.onActivityResult(requestCode, resultCode, data);
}
}
I think this change'll help you.