How to progress into saving the image into SQLiteDatabase - java

This is where I import the image to(from gallery) and I want to save it to SQLite to hopefully display it in another activity, how would I go about doing so? I am kind of new to Android Studio so if there is some newbie kind of easy way that I would go about doing so would be very helpful.
(Update) So I have added this two lines marked by /* */ but now I can't get my app to work still have no idea how to do this.. any ideas?
Import image>Save to SQLite>Take Image to SQLite>Display in another activity
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DataInput extends AppCompatActivity {
private EditText inputName;
private EditText inputAge;
private Button buttonSave;
private Button buttonGetLocation;
private Button buttonImportImage;
private ImageView mImageView;
private static final int IMAGE_PICK_CODE = 1000;
private static final int PERMISSION_CODE = 1001;
private InputHelper helper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_input);
inputName = (EditText) findViewById(R.id.input_name);
inputAge = (EditText) findViewById(R.id.input_age);
address = (TextView) findViewById(R.id.address);
buttonSave = findViewById(R.id.button_save);
buttonSave.setOnClickListener(onSave);
buttonImportImage = findViewById(R.id.button_import_image);
mImageView = findViewById(R.id.image_view);
buttonImportImage.setOnClickListener(onImport);
helper = new InputHelper(this); }
private View.OnClickListener onSave = new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameStr = inputName.getText().toString();
String ageStr = inputAge.getText().toString();
String addressStr = address.getText().toString();
String combineStr = nameStr + "\n" + ageStr + "\n" + addressStr;
Toast.makeText(v.getContext(), combineStr, Toast.LENGTH_LONG).show();
/*BitmapDrawable drawable = (BitmapDrawable)mImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
byte[] image = getBitmapAsByteArray(bitmap);*/
Intent i = new Intent(DataInput.this,InformationDisplay.class);
startActivity(i);
helper.insert(nameStr,ageStr,addressStr,image);
finish();
}
/* public byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray(); */
}
};
private View.OnClickListener onImport = new View.OnClickListener() {
#Override
public void onClick(View v) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
//permission not granted, request it.
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_CODE);
} else {
//permission already granted
pickImageFromGallery();
}
} else {
//system os is less then marshmallow
pickImageFromGallery();
}
}
};
private void pickImageFromGallery() {
//intent to pick image
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
//handle result of runtime permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
//permission was granted
pickImageFromGallery();
} else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_LONG).show();
}
}
}
}
//handle result of picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
//set image to image view
mImageView.setImageURI(data.getData());
}
}

You can save an Image in SQLite database in the form of blob. Another simple way to storing the image is in the form of base64 string. This is what I tried in my previous project and this works:
public class Profile_Class extends AppCompatActivity {
private Bitmap photo, OutImage;
private AppPreferences preferences;
private CircularImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile__class);
EditText name = findViewById(R.id.name);
preferences = new AppPreferences(this);
Toolbar toolbar = findViewById(R.id.toolbar_t);
EditText userName = findViewById(R.id.userName);
EditText passWord = findViewById(R.id.passWord);
imageView = findViewById(R.id.iv_profile_auditor);
ImageView take_pic1 = findViewById(R.id.take_pic1);
if (prefernces.getProfileImage().equals(" ")) {
Log.e("TAG", "NoProfilePic");
} else {
imageView.setImageBitmap(decodeBase64(prefernces.getProfileImage()));
}
take_pic1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
OutImage = Bitmap.createScaledBitmap(photo, 300, 400, true);
prefernces.setProfileImage(encodeTobase64(OutImage));
Intent intent2 = new Intent("header_pic_update");
LocalBroadcastManager.getInstance(Profile_Class.this).sendBroadcast(intent2);
}
}
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
// method for base64 to bitmap
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return true;
}
If you see in OnActivityResult class, I'm converting the outImage into Base64 string. Here use the method encodeTobase64 and add the image string to your table.
Now in the other activity where you want to show the image, call the method decodeBase64 and decode the image. In the above code I'm decoding the string to image and setting it to imageview like this:
imageView.setImageBitmap(decodeBase64(prefernces.getProfileImage()));
There are numerous ways to store and retrieve the image. This is one way I did. Mind here that I'm storing the image in bitmap so the quality will not be good. If you want image with full quality than you have to use URI to store the image in your mobile and then call the image in required quality.

Related

Unresponsive data.getData for PICK_IMAGE_REQUEST

One of the Activities on an app i am building is a profile update activity with an option to upload display picture. I am trying to implement upload picture option using Picasso through the following code. So far i am unable to retrieve the picture from the phone with a constant null for Uri and failure to display picture in the ImageView due to that.
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class UploadProfilePicture extends AppCompatActivity {
private ProgressBar progressBar;
private ImageView imageViewUploadPic;
private FirebaseAuth authProfile;
private StorageReference storageReference;
private FirebaseUser firebaseUser;
private static final int PICK_IMAGE_REQUEST =1 ;
private Uri uriImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_profile_pciture);
getActionBar();
authProfile = FirebaseAuth.getInstance();
firebaseUser = authProfile.getCurrentUser();
Button buttonUploadPictureChoose = findViewById(R.id.upload_profile_pic_choose_button);
Button buttonUploadProfilePicture = findViewById(R.id.upload_profile_pic_upload_button);
progressBar = findViewById(R.id.progressBar);
imageViewUploadPic = findViewById(R.id.imageView_profile_pic_upload);
storageReference = FirebaseStorage.getInstance("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").getReference("UsersDisplayPictures");
Uri uri = firebaseUser.getPhotoUrl();
//Set User's current DP in ImageView (if uploaded already). Will be using Picasso
//Regular URIs
Picasso.with(UploadProfilePicture.this).load(uri).into(imageViewUploadPic);
//choosing image from phone to upload
buttonUploadPictureChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
//upload image to app
buttonUploadProfilePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
UploadPic ();
}
});
}
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
uriImage = data.getData();
imageViewUploadPic.setImageURI(uriImage);
Toast.makeText(UploadProfilePicture.this, "Picture was chosen, please click the upload button", Toast.LENGTH_SHORT).show();
} else if (uriImage == null){
Toast.makeText(UploadProfilePicture.this, "Uri is null", Toast.LENGTH_SHORT).show();
}
}
private void UploadPic(){
if (uriImage != null){
// save the image with uid of the currently logged user
StorageReference fileReference = storageReference.child(authProfile.getCurrentUser().getUid() + " . " + getFileExtension(uriImage));
//Upload image to storage
fileReference.putFile(uriImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
firebaseUser = authProfile.getCurrentUser();
//Finally set the display image of the user after upload
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setPhotoUri(downloadUri).build();
firebaseUser.updateProfile(profileUpdates);
}
});
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadProfilePicture.this, "Picture Upload is successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(UploadProfilePicture.this, UserProfileActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadProfilePicture.this, e.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(UploadProfilePicture.this, "Something went wrong!" ,Toast.LENGTH_SHORT).show();
}
});
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadProfilePicture.this, "No file was selected", Toast.LENGTH_SHORT).show();
}
}
//Obtaining File Extension of the image
private String getFileExtension(Uri uri){
ContentResolver CR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(CR.getType(uri));
}
No errors or noticeable Logcat line related. Simply it would exit the Picture picker and would not display the image in the imageView. Of course it would Toast the message of " Uri is null" since it is following the if statement included to follow the process steps to see the missing task !
Is my code of choosing and uploading picture is wrong or something is missing >
I guess it was a syntax error in the if statement within the onActivityResult
it was:
if (resultCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
Correction :
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
At the moment the issue is resolved and image could be chosen and displayed within the app.
Facing a new issue with this code but this should be for another question if needed
E/StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403

No suitable method found for into(Uri)

I want to allow the user to upload two images,Cover and Logo.Then have them saved in firestore.I get an error at
Picasso.get().load(uri).into(Logo); line saying
no suitable method found for into(Uri)
method RequestCreator.into(Target) is not applicable
(argument mismatch; Uri cannot be converted to Target)
method RequestCreator.into(ImageView) is not applicable
(argument mismatch; Uri cannot be converted to ImageView)
package com.example.littlemarketplaceapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class Shop extends AppCompatActivity {
private ImageButton Logoimage;
private ImageButton Cover;
private EditText ShopnameEditText;
private TextView ShowShopName;
private Button SaveButton;
DatabaseReference databaseReference1;
private FirebaseAuth mAuth;
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference storageReference1 = FirebaseStorage.getInstance().getReference();
Uri Logo;
Uri coverUri;
private Uri uri;
int coverOrLogo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
Intent intent = getIntent();
String emaila = intent.getExtras().getString("emaili");
String passworda = intent.getExtras().getString("passwordi");
String fullnamea = intent.getExtras().getString("fullnamei");
String usernamea = intent.getExtras().getString("usernamei");
String mobilea = intent.getExtras().getString("mobilei");
String Shopname;
Logoimage = findViewById(R.id.shoplogobutton);
Cover = findViewById(R.id.coverphotobutton);
ShowShopName = findViewById(R.id.shopname);
ShopnameEditText = findViewById(R.id.shopnameedittext);
Shopname = ShopnameEditText.getText().toString().trim();
String key = databaseReference1.push().getKey();
//Saves Owner's Data
SaveButton.setOnClickListener(v -> {
ForOwner s_owner = new ForOwner(fullnamea, usernamea, emaila, mobilea, passworda, Shopname);
databaseReference1.child(key).setValue(s_owner);
Toast.makeText(getApplicationContext(), "Registration complete", Toast.LENGTH_SHORT).show();
});
//Uploads the Logo
Logoimage.setOnClickListener(view -> {
//open Gallery
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent, 1000);
});
//Uploads the Cover photo
Cover.setOnClickListener(view -> {
//open Gallery
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent, 2000);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #androidx.annotation.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
Uri imageUri1 = data.getData();
Logoimage.setImageURI(imageUri1);
uploadImageToFirebase(imageUri1, 1);
} else if (requestCode == 2000 && resultCode == Activity.RESULT_OK) {
Uri imageUri2 = data.getData();
Cover.setImageURI(imageUri2);
uploadImageToFirebase(imageUri2, 0);
}
}
//}
private <final_fileRef> void uploadImageToFirebase(Uri imageUri1, int coverOrLogo) {
//upload image to firebase
StorageReference fileRef = null;
if (coverOrLogo == 1) {
fileRef = storageReference.child("logo.jpg");
} else if (coverOrLogo == 0) {
fileRef = storageReference.child("cover.jpg");
}
fileRef.putFile(imageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef.putFile(imageUri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(Uri uri) {
if (coverOrLogo == 1) {
Picasso.get().load(uri).into(Logo);
}
if (coverOrLogo == 0) {
Picasso.get().load(uri).into(Cover);
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Shop.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
In your code Logo is Uri
You need this:
Picasso.get().load(uri).into(imageView);
where imageView is ImageView object in your layout

App Crash in Moblile phone

I am trying to make a camera App for an android phone. The code is showing no error, but when I run it on my phone after launching the app, it crashes, giving this error:
"Unfortunately the app stopped"
package com.my.hp.myapp;
import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_CODE_SOME_FEATURES_PERMISSIONS = 1;
private static final int CAMERA_PIC_REQUEST = 2;
private ImageView img;
private Button btn1;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
img = findViewById(R.id.image);
btn1 = findViewById(R.id.butt);
btn1.setOnClickListener(this);
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkpermission() {
int hasCameraPermission =
checkSelfPermission(Manifest.permission.CAMERA);
int hasStoragePermission =
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> permissions = new ArrayList<>();
if (hasCameraPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.CAMERA);
}
if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!permissions.isEmpty()) {
requestPermissions(permissions.toArray(new String[permissions.size()]),
REQUEST_CODE_SOME_FEATURES_PERMISSIONS);
}
}
#RequiresApi(api=Build.VERSION_CODES.M)
private boolean hasPermission() {
int hasCameraPermission =
checkSelfPermission(Manifest.permission.CAMERA);
int hasStoragePermission =
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
return (hasCameraPermission==PackageManager.PERMISSION_GRANTED && hasStoragePermission==PackageManager.PERMISSION_GRANTED);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.butt:
if(hasPermission())
{
openCamera();
}
else{
checkpermission();
}
break;
}
}
private void openCamera()
{
String timeStamp=new
SimpleDateFormat("yyyyMMdd_HHmms").format(new Date());
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"IMG_"+ timeStamp+".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri =
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode) {
case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED)
{
Log.d("Permissions", "Permission Denied: " + permissions[i]);
}
}
}
break;
default:{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
if(data != null){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
img.setImageBitmap(imageBitmap);
}
}
}
}
}
First check if you added camera and read storage permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

How to load an image from android gallery into a ImageView? [duplicate]

This question already has answers here:
Android get image from gallery into ImageView
(13 answers)
Closed 5 years ago.
I am trying to load an image from an android device into my application.
I've already used the permission in execution time in my code because I found it was necessary in the recents Api but it doesn't work the same way.
I can click the button and choose the image, but it doesn't appears in my ImageView.
Here is my ActivityCode:
package geoapp.testemapas.com.geoapp;
import android.app.VoiceInteractor;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
public class PegarImagemActivity extends AppCompatActivity {
public static final int IMAGEM_ID = 1;
public static final int PERMISSAO_REQUEST = 2;
private Button pegarImgemBotaoPegarImagem;
private Button PegarImgemBotaoEnviarImagem;
private ImageView pegarImagemImageViewImgem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pegar_imagem);
pegarImgemBotaoPegarImagem = (Button) findViewById(R.id.pegar_imagem_botao_pegar_imagem);
pegarImagemImageViewImgem = (ImageView) findViewById(R.id.pegar_imagem_iv);
pegarImgemBotaoPegarImagem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, IMAGEM_ID);
}
});
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)){
}else{
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSAO_REQUEST );
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
if(requestCode == IMAGEM_ID){
if(requestCode == RESULT_OK){
Uri imagem_selecionada = intent.getData();
String[] colunas = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imagem_selecionada, colunas, null, null, null);
cursor.moveToFirst();
int index = cursor.getColumnIndex(colunas[0]);
String pathImg = cursor.getString(index);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(pathImg);
pegarImagemImageViewImgem.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == PERMISSAO_REQUEST){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
}else{
}
return;
}
}
}
You can try this method.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
1001);
on activity result, you will get the image selected and you can show it in your image view
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == 1001) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
if (bitmap != null) {
ImageView img = (ImageView)findViewById(R.id.imgeview_id);
img.setImageBitmap(bitmap);
}
}
}
Looks good! few corrections are required to make it working for you.
add uses permission on Manifest file.
correct code mistake.
if (resultCode == RESULT_OK){
}
That's it :)

I have the following code for taking pictures, I need to know how to take video and also put a permission class for taking pictures

This first part are simple imports, not really relevant to my question.
details details android studio
much details, such wow
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
Declaration of class
public class MainActivity extends Activity {
Variables being declared
private final static int TAKE_PICTURE = 0;
private final static int SAVE_PICTURE = 1;
private final static int TAKE_VIDEO = 2;
private final static int STORAGE_PERMISSION = 3;
private ImageView iv;
private VideoView vv;
private MediaController mc;
private String lastURI;
Basic create method, nothing special here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView)findViewById(R.id.imageView);
vv = (VideoView)findViewById(R.id.videoView);
mc = new MediaController(this);
mc.setMediaPlayer(vv);
vv.setMediaController(mc);
}
Method that takes picture
public void takePicture(View v){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent, TAKE_PICTURE);
}
}
Method that saves picture
public void savePicture(View v){
Log.i("SAVE PICTURE", "save");
if(Build.VERSION.SDK_INT >= 23 &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
// request permission!
Log.i("SAVE PICTURE", "asking permission");
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION);
} else {
savePicturePermitted();
}
}
Main method
protected void onActivityResult(int requestCode, int resultCode, Intent data){
Log.wtf("RETURN", requestCode + "");
if(resultCode == Activity.RESULT_OK){
Test cases
switch(requestCode){
case TAKE_PICTURE:
Bundle extra = data.getExtras();
Bitmap image = (Bitmap)extra.get("data");
iv.setImageBitmap(image);
break;
}
}
}
}
It looks like what you have to do is the following:
For the permission part use this:
private void savePicturePermitted(){
// the actual code
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null){
File photo = null;
try{
String time = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String name = "GUYZ_" + time;
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
photo = File.createTempFile(name, ".jpg", directory);
// keep track of the URI
lastURI = photo.getAbsolutePath();
}catch(IOException ioe){
ioe.printStackTrace();
}
if(photo != null){
//intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", photo));
startActivityForResult(intent, SAVE_PICTURE);
}
}
}
Also add a result or feedback so the user knows what's up, this could be done like so:
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == STORAGE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED){
savePicturePermitted();
} else {
Toast.makeText(this, "Permission required", Toast.LENGTH_SHORT).show();
}
}
For taking video, the method looks like this:
public void takeVideo(View v){
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent, TAKE_VIDEO);
}
}
Finally, I suggest you add all of these to your test cases so you can test they work. This is how that should look like:
case TAKE_VIDEO:
Uri video = data.getData();
vv.setVideoURI(video);
vv.start();
break;
Noticed you missed a save picture use case:
case SAVE_PICTURE:
Log.wtf("SAVING PICTURE", lastURI);
Bitmap image2 = BitmapFactory.decodeFile(lastURI);
iv.setImageBitmap(image2);
break;
Also I noticed that you were missing some imports, these should appear automatically, but in case they don't, here's what those should be:
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

Categories