Displaying Cropped Image On ImageView - java

Overview: I have a simple layout with a button which when pressed.. opens up gallery telling me to choose a picture to crop, once picture is chosen, it goes into a cropping image screen. Once cropping of the image finishes and I hit "save/done" it should display the new cropped image onto my ImageView.
Issue: I can't seem to display the new cropped image onto the ImageView; when I hit "save" after I finish cropping the image, it goes back to my main layout indicating that it was saved but it never displays the image onto the view.
This activity starts when a button is pressed and goes into the second activity. Once the picture from the second activity is acquired, it crops the image and should display it on the ImageView.
package com.example.pau.crop_test;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class ImageSelecter extends Activity {
private final int GALLERY_ACTIVITY_CODE = 200;
private final int RESULT_CROP = 400;
private ImageView imageView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
Button profile_button = (Button) findViewById(R.id.button);
profile_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start Activity To Select Image From Gallery
Intent gallery_Intent = new Intent(getApplicationContext(), GalleryUtil.class);
startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_ACTIVITY_CODE) {
if (resultCode == Activity.RESULT_OK) {
String picturePath = data.getStringExtra("picturePath");
//perform Crop on the Image Selected from Gallery
performCrop(picturePath);
}
}
if (requestCode == RESULT_CROP) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap selectedBitmap = extras.getParcelable("data");
// Set The Bitmap Data To ImageView
ImageView image =(ImageView) findViewById(R.id.imageView2);
image.setImageBitmap(selectedBitmap);
// imageView2.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
}
}
}
private void performCrop(String picUri) {
try {
//Start Crop Activity
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
File f = new File(picUri);
Uri contentUri = Uri.fromFile(f);
cropIntent.setDataAndType(contentUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 280);
cropIntent.putExtra("outputY", 280);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, RESULT_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Below is the second activity which allows us to go into our gallery and choose a picture, then returns it to the first activity for cropping:
package com.example.pau.crop_test;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class GalleryUtil extends Activity{
private final static int RESULT_SELECT_IMAGE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "GalleryUtil";
String mCurrentPhotoPath;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
//Pick Image From Gallery
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_SELECT_IMAGE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case RESULT_SELECT_IMAGE:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
try{
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();
//return Image Path to the Main Activity
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}catch(Exception e){
e.printStackTrace();
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
}else{
Log.i(TAG,"RESULT_CANCELED");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
break;
}
}
}
Below is my layout which displays button and image view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
>
<ImageView
android:layout_width="200dp"
android:layout_height="fill_parent"
android:id="#+id/imageView2"
android:layout_marginTop="41dp"
android:contentDescription="#string/abc_activity_chooser_view_see_all" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/crop"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageView2"
android:layout_toEndOf="#+id/imageView2" />
</RelativeLayout>

Put some debugging in the requestCode == RESULT_CROP block to ensure that section is running. If the ImageView is not getting updated and since the only place you do the updating is a successful crop then it would suggest that activity is not returning as you expect

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

How to progress into saving the image into SQLiteDatabase

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.

passing a variable to classes

i can not figure out how to pass the results from onActivityResult to resultBreakdown. I know there is a get/set and I've looked at a few tutorials, but I'm just not getting it. Or, Is there a better way? The program runs fine up if i comment out */ the resultBreakdown Class
Side note, I just started with java/android. I'm a better learner at doing then reading. I know my code is a little clumsy. Thanks for the help
Note: i edited code to reflect suggested changes
package com.example.spdwiz18.testproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
import java.text.DateFormat;
import java.time.*;
import java.time.temporal.*;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
public class GrindLogActivity extends AppCompatActivity {
TextView barcodeResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gringlogactivity);
// this is how to set id's from the xml file with vNames. (julianDate)
TextView bcc = (Textview)findViewById(R.id.bccheck);
TextView pc = (Textview)findViewById(R.id.pcode);
TextView pd = (Textview)findViewById(R.id.pdate);
// TextView en = (Textview)findViewById(R.id.estnum);
TextView sn = (Textview)findViewById(R.id.seqnum);
TextView nw = (Textview)findViewById(R.id.nweight);
barcodeResult = (TextView) findViewById(R.id.barcode_result);
TextView julianDate = (TextView) findViewById(R.id.datecode);
TextView td1 = (TextView) findViewById(R.id.todaydate1);
// this is how you get a julian/original date for android
LocalDate now = LocalDate.now();
int julian = now.get(ChronoField.DAY_OF_YEAR);
// this how to set you current date for android
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
// this is how to set your vNames to your method variables
julianDate.setText(Integer.toString(julian));
td1.setText(stringDate);
}
/*add click event to the scan barcode button */
public void scanBarcode(View v) {
Intent intent = new Intent(this, ScanBarcodeActivity.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(String result) {
if (result.length() == 44) {
pc.setText(result.CharSequence(2,10));
pd.setText(result.CharSequence(13,18));
sn.setText(result.CharSequence(21,27));
nw.setText(result.CharSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}
The code posted needs a lot of work - so this answer most likely is just partial
(1) TextView initialization in wrong place
The TextViews declared as class instance variables cannot also be initialized at that point. So leave the declarations there (where bardcodeResult is declared):
TextView barcodeResult;
TextView bcc;
TextView pc;
TextView pd;
TextView sn;
TextView nw;
but move the initialization to the onCreate method in the same manner barcodeResult.
// in onCreate
barcodeResult = (TextView) findViewById(R.id.barcode_result);
bcc = (TextView)findViewById(R.id.bccheck);
pc = (TextView)findViewById(R.id.pcode);
pd = (TextView)findViewById(R.id.pdate);
sn = (TextView)findViewById(R.id.seqnum);
nw = (TextView)findViewById(R.id.nweight);
(2) The syntax is of resultsBreakdown is invalid and the functionality is wrong (need to invoke setText)- try:
public void resultsBreakdown(String result) {
if (result.length() == 44) {
pc.setText(result.CharSequence(2,10));
pd.setText(result.CharSequence(13,18));
sn.setText(result.CharSequence(21,27));
nw.setText(result.CharSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}
(3) Actually invoke the resultsBreakdown method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
//-- THIS LINE WAS ADDED TO CALL METHOD
resultsBreakdown(barcode.displayValue.toString());
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
I think there should be resultCode instead of requestCode in requestCode == CommonStatusCodes.SUCCESS
 #Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
resultsBreakdown(barcode.displayValue)
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(String barcodeData){
if (barcodeData.length == (44)) {
pc = (barcodeData.CharSequence(2,10);
pd = (barcodeData.CharSequence(13,18);
sn = (barcodeData.CharSequence(21,27);
nw = (barcodeData.CharSequence(13,18);
)else(
bcc = "invalid barcode";
}
)
}
resultBreakdown neither a class nor a method.İt isn't even compile. You change your resultBreakDown to Method:
public void resultsBreakdown(Barcode barcodeResult){
if (barcodeResult.length == (44)) {
pc = (barcodeResult.CharSequence(2,10);
pd = (barcodeResult.CharSequence(13,18);
sn = (barcodeResult.CharSequence(21,27);
nw = (barcodeResult.CharSequence(13,18);
} else{
bcc = "invalid barcode";
}
and later in onActivityResult call your method with Barcode parameters.
The code is incomplete as you have not placed ScanBarcodeActivity java file. Well... I am placing a small code in my project which will clear your concept and even you can use it.
Here suppose i am in Activity MyClassA.java where is a button and when it is clicked it will start another activity MyClassB.java, Remember it will start that activity along with layout.. from that activity you have to finish it on certain event and when it is finished your MyClassA.java will collect its result...
From Activity MyClassA.java on button click i want to start a activity
MyClassB.java for result:
ContactsBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
ContactsBtn.setEnabled(false);
Intent intent = new Intent(MyClassA.this, MyClassB.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
Where REQUEST_CODE should be declared in MyClassA class as public static final int REQUEST_CODE = 1;
Now From Activity MyClassB.java on particular event say on click of a button you want to close this activity and want to send result to previous activity :
SelectContactsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.putStringArrayListExtra("WhitelistNames", (ArrayList<String>) WhitelistNames);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
Here i am placing WhitelistNames array list as result to be sent to calling activity.
Now From Activity MyClassA.java again you have to collect the result with :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK)
{
ArrayList<String> WhitelistNames = data.getStringArrayListExtra("WhitelistNames");
Log.d("ContactsContracts", "\nPREVIOUS LIST : "+ContactsNumbers);
}
}
}
Remember onActivityResult method should be part of your MyClassA.java class and should not be in onCreate nor in some other existing standard methods of this class.
Hope it helps
Thank you for everyones help. This one worked as needed
package com.example.spdwiz18.testproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
import java.text.DateFormat;
import java.time.*;
import java.time.temporal.*;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
public class GrindLogActivity extends AppCompatActivity {
TextView barcodeResult;
TextView bcc;
TextView pc;
TextView pd;
TextView sn;
TextView nw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gringlogactivity);
bcc = (TextView)findViewById(R.id.bccheck);
pc = (TextView)findViewById(R.id.pcode);
pd = (TextView)findViewById(R.id.pDate);
// TextView en = (TextView)findViewById(R.id.estnum);
sn = (TextView)findViewById(R.id.seqnum);
nw = (TextView)findViewById(R.id.nweight);
barcodeResult = (TextView) findViewById(R.id.barcode_result);
TextView julianDate = (TextView) findViewById(R.id.datecode);
TextView td1 = (TextView) findViewById(R.id.todaydate1);
// this is how to set id's from the xml file with vNames. (julianDate)
// this is how you get a julian/original date for android
LocalDate now = LocalDate.now();
int julian = now.get(ChronoField.DAY_OF_YEAR);
// this how to set you current date for android
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
// this is how to set your vNames to your method variables
julianDate.setText(Integer.toString(julian));
td1.setText(stringDate);
}
/*add click event to the scan barcode button */
public void scanBarcode(View v) {
Intent intent = new Intent(this, ScanBarcodeActivity.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (requestCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
Barcode barcode = data.getParcelableExtra("barcode");
barcodeResult.setText("Barcode value : " + barcode.displayValue);
resultsBreakdown(barcode.displayValue.toString());
} else {
barcodeResult.setText("No Barcode Found");
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public void resultsBreakdown(CharSequence result) {
if (result.length() == 44) {
pc.setText(result.subSequence(2,10));
pd.setText(result.subSequence(13,18));
sn.setText(result.subSequence(21,27));
nw.setText(result.subSequence(13,18));
} else {
bcc.setText("invalid barcode");
}
}}

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 :)

Error with image view when displaying an image by camera capturing

i am new to android and i am trying to make my phone cam take a picture and display it in an image view. When the image is captured, it is saved correctly but after that the app stops working when the image should be displayed in an image view. Any help is appreciated. I searched some topics but still nothing works.
Here is the code:
package myfirstapp.myapps.me.camera;
import ...
public class MainActivity extends ActionBarActivity {
ImageButton camBtn;
ImageView imageView;
ScrollView scrollView;
private File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OpenCam(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"image.jpg");
Uri tempURI=Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, tempURI);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0)//==0 the same where startActivityForResult(intent, 0) so we are in the same process
{
switch (resultCode){
case Activity.RESULT_OK:
if(imageFile.exists())
{
Toast.makeText(MainActivity.this, "Image was saved at "+imageFile.getAbsolutePath(), Toast.LENGTH_SHORT)
.show();
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
else
{
Toast.makeText(MainActivity.this, "Image wasn't saved", Toast.LENGTH_SHORT)
.show();
}
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MainActivity.this, "Image capture was cancelled", Toast.LENGTH_SHORT)
.show();
break;
}
}
}
}
Stacktrace
Caused by: java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=0, result=-1, data=null} to activity
{myfirstapp.myapps.me.camera/myfirstapp.myapps.me.camera.MainActivity}:
java.lang.NullPointerException at
android.app.ActivityThread.deliverResults(ActivityThread.java:3410) at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2817)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2859)
Please go through this Code:
public static final int REQUEST_IMAGE_CAPTURE = 1;
public static final int RESULT_LOAD_IMAGE = 10;
private Bitmap myBitmap;
ImageView myImage ;
public void OpenCam(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
And also,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
{
Bundle extras = data.getExtras();
myBitmap= (Bitmap) extras.get("data");
myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
}
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
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();
myBitmap= BitmapFactory.decodeFile(picturePath);
// photoUri = picturePath;
myImage.setImageBitmap(myBitmap);
}
}
Why are you first saving and trying to show the saved image file. Use the returned data from onActivityResult. Before file is actually created in the memory, broadcast is sent so it can refresh the directory and show the new file. But better is to use what camera intent is returning as data.
Replace your this code
Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
with this
ImageView myImage = (ImageView) findViewById(R.id.imageView);
Bitmap photo = (Bitmap) data.getExtras().get("data");
myImage.setImageBitmap(photo);
first : comment the line
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // no need to write for capture camera
second : use this line
imageFile=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc); // abc folder name
instead of
imageFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"image.jpg");
Note : your code work upto kitkat but lollipop it will crash because in lollipop imageFile return null so Uri failed to convert in file . Hope your problem will resolve . and one more thing before open camera u should check that sdcard permission .

Categories