In my app, I' using Tab. There are three tabs. In which 3rd tab is Activity group which has two activities. In first activity, there are two options for user. User can choose image from camera or from gallery. After selecting an image, user should move to child activity, which will display selected image in that activity. Till this app is working fine. But only problem here I'm facing is, image is not being cleared when I move back to parent activity from child activity. Means once I choose image from gallery/camera, user moves to child activity, and image is being displayed in child activity. Now when I press back button from child activity, user moves back to parent activity and again if user selects different image from galley/camera, that different image is not there in child activity. The previous image is there in child activity. Below is my code.
ABCGroup.java
public class ABCGroup extends ActivityGroup{
public static ABCGroup group;
private ArrayList<View> history;
View view;
int column_index;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.history = new ArrayList<View>();
group = this;
view = getLocalActivityManager().startActivity("ParentActivity", new Intent(ABCGroup.this, Tab1.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(view);
}
public void replaceView(View v) {
history.add(v);
setContentView(v);
}
public void back() {
if(history.size() > 0)
{
history.remove(history.size()-1);
if(history.size()<=0)
{
finish();
}
else
{
setContentView(history.get(history.size()-1));
}
}
else
{
finish();
}
}
#Override
public void onBackPressed() {
ABCGroup.group.back();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK){
ABCGroup.group.back();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if (requestCode == Tab1.REQUEST_ID && resultCode == Activity.RESULT_OK) {
try
{
stream = getContentResolver().openInputStream(data.getData());
Bitmap original = null;
original= BitmapFactory.decodeStream(stream);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
}
catch (Exception e)
{
e.printStackTrace();
}
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
if (requestCode == 3 && resultCode == Activity.RESULT_OK)
{
getContentResolver().notifyChange(Tab1.mUri, null);
ContentResolver cr = getContentResolver();
try
{
Tab1.mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, Tab1.mUri);
Second.bmp = Tab1.mPhoto;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Tab1.mPhoto.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File direct = new File(Environment.getExternalStorageDirectory() + "/ABCGroup");
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
Toast.makeText(getBaseContext(), "Time :" + mydate, 5000).show();
if(!direct.exists())
{
direct.mkdir();
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/ABCGroup/image" + mydate +".jpg");
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
}
else
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/ABCGroup/image" + mydate +".jpg");
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
}
View mview = ABCGroup.group.getLocalActivityManager().startActivity("activity3", new Intent(ABCGroup.this, Second.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(mview);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("data", cursor.getString(column_index) );
editor.commit();
View mview = ABCGroup.group.getLocalActivityManager().startActivity("activity3", new Intent(ABCGroup.this, Second.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)).getDecorView();
replaceView(mview);
return cursor.getString(column_index);
}
public void onResume()
{
super.onResume();
column_index = 0;
}
}
Tab1.java
public class Tab1 extends ActivityGroup {
Button gallery, camera;
private ArrayList<View> myActivityHistory;
ImageView iv;
private static final int TAKE_PICTURE = 3;
public static final int REQUEST_ID = 1;
private static final int HALF = 2;
public static Uri mUri;
public static Bitmap mPhoto;
int i = 0;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.tab1);
View viewToLoad = LayoutInflater.from(Tab1.this.getParent()).inflate(R.layout.tab1, null);
Tab1.this.setContentView(viewToLoad);
myActivityHistory = new ArrayList<View>();
gallery = (Button)viewToLoad.findViewById(R.id.gallery);
camera = (Button)viewToLoad.findViewById(R.id.camera);
iv = (ImageView)viewToLoad.findViewById(R.id.iv);
gallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
ABCGroup.group.startActivityForResult(intent, REQUEST_ID);
}
});
camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
ABCGroup.group.startActivityForResult(i, TAKE_PICTURE);
}
});
}
public void replaceContentView(String id, Intent newIntent)
{
View mview = ABCGroup.group.getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)).getDecorView();
ABCGroup.group.replaceView(mview);
}
}
Second.java
public class Second extends Activity {
public static Bitmap bmp;
Bitmap myBitmap;
String path;
ImageView iv;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
View viewToLoad = LayoutInflater.from(Second.this.getParent()).inflate(R.layout.second, null);
Second.this.setContentView(viewToLoad);
Button btn = (Button)viewToLoad.findViewById(R.id.button1);
iv = (ImageView)viewToLoad.findViewById(R.id.imageView1);
iv.setImageBitmap(bmp);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
File imgFile = new File(path);
if(imgFile.exists()){
Toast.makeText(getBaseContext(), "" + path, 1000).show();
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ABCGroup.group.back();
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(Second.this, Tab1.class);
Tab1 parentActivity = (Tab1)getParent();
parentActivity.replaceContentView("Profile", new Intent(Second.this, Tab1.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY ) );
}
public void onResume()
{
super.onResume();
}
}
Finally I got the answer
public void onResume()
{
super.onResume();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
imgFile = new File(path);
Toast.makeText(getBaseContext(), "" + path, 2000).show();
if(imgFile.exists())
{
myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
}
Related
I have Main Activity with Navigation drawer. In that I have edit button which open Edit Fragment. The user selected image from Camera or gallery should be displayed in ImageView.
Here the issue I am facing is I can select the image successfully and it also returns the image in onActivityResult(). But it exits the fragment and gets redirected to Main activity fragment after returning back from Camera or Gallery.
I am required to set image in ImageView and stay in the same fragment after onActivityResult() is called.
Here is my code:
EditProfileFragment.java
public class EditProfileFragment extends Fragment {
RadioButton radioMale, radioFemale;
Calendar birthDataCalendar = Calendar.getInstance();
CustomEditText etBirthDate;
CustomClearableEditText etName, etNumber, etAddress;
CircleImageView civProfile, civChoose;
ImageView ivBack;
Bundle extra;
byte[] byteArray;
Bitmap bitmap;
private static final int REQUEST_CAMERA = 55;
private static final int SELECT_FILE = 66;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_profile, container, false);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
etName = view.findViewById(R.id.edit_profile_et_name);
etNumber = view.findViewById(R.id.edit_profile_et_contact_no);
etAddress = view.findViewById(R.id.edit_profile_et_address);
radioMale = view.findViewById(R.id.edit_profile_radio_male);
radioFemale = view.findViewById(R.id.edit_profile_radio_female);
etBirthDate = view.findViewById(R.id.edit_profile_et_birth_date);
civProfile = view.findViewById(R.id.edit_profile_civ_profile);
civChoose = view.findViewById(R.id.edit_profile_civ_choose);
ivBack = view.findViewById(R.id.edit_profile_iv_back);
civChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] options = {"Camera", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogCustom);
builder.setTitle("Add Photo from..");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Camera")) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startActivityForResult(cameraIntent, REQUEST_CAMERA);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_FILE);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
});
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
birthDataCalendar.set(Calendar.YEAR, year);
birthDataCalendar.set(Calendar.MONTH, monthOfYear);
birthDataCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
if (getActivity().getIntent().getStringExtra("signInProfileImage") == null) {
extra = getActivity().getIntent().getExtras();
if (extra != null) {
byteArray = extra.getByteArray("signUpProfileImage");
bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
civProfile.setImageBitmap(bitmap);
}
} else {
String imagePath = getActivity().getIntent().getStringExtra("signInProfileImage");
Picasso.with(getActivity()).load(imagePath).into(civProfile);
}
etBirthDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(getActivity(), date, birthDataCalendar
.get(Calendar.YEAR), birthDataCalendar.get(Calendar.MONTH),
birthDataCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
if (REQUEST_CAMERA == requestCode && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (bitmap != null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
}
String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "", null);
File filesDir = getActivity().getFilesDir();
File imageFile = new File(filesDir, "image" + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
Uri.parse(path);
Picasso.with(getActivity()).load(path).noPlaceholder().centerCrop().fit().into(civProfile);
}
if (requestCode == SELECT_FILE) {
Toast.makeText(getActivity(), "Gallery clicked", Toast.LENGTH_SHORT).show();
Uri selectedImageURI = data.getData();
String filePath = getRealPathFromURIPath(selectedImageURI, getActivity());
File file = new File(filePath);
//RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
try {
InputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
Picasso.with(getActivity()).load(selectedImageURI).noPlaceholder().centerCrop().fit()
.into((civProfile));
}
}
private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
private void updateLabel() {
String myFormat = "dd-MMM-yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
etBirthDate.setText(sdf.format(birthDataCalendar.getTime()));
}
}
Initialisation in MainActivity.java
ivEditProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportActionBar().hide();
EditProfileFragment editProfileFragment = new EditProfileFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.main_frame, editProfileFragment);
transaction.addToBackStack(null);
transaction.commit();
drawer.closeDrawer(GravityCompat.START);
}
});
Thanks in advance.
I think as per your conversation(and my past experience). You have put something in onResume() like open your first fragment code, So you need to remove that code from onResume() and need to keep it at 'onCreate()' method in your activity.
For my case, I realized that it is due to I have enabled following option:
Developer Options -> APPS -> Don't keep activities
I disable above option when testing image selection activity. And enable it back for other testings.
I am trying to develop some kind of OCR application with Text Recognizing feature. I wrote and found some codes which is working properly but my problem is I want make some customization in the camera layout. I want to add my own capture button and add a frame. I actually did it on a different project with "surface view/holder". But I cannot implement my project because it works so differently.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_GALLERY = 0;
private static final int REQUEST_CAMERA = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private Uri imageUri;
private TextView detectedTextView; // layouttaki text view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.choose_from_gallery).setOnClickListener(new View.OnClickListener() { // galeriden resim seçme işlemi
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
});
findViewById(R.id.take_a_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // resim çekme işlemi
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
});
detectedTextView = (TextView) findViewById(R.id.detected_text);
detectedTextView.setMovementMethod(new ScrollingMovementMethod());
}
private void inspectFromBitmap(Bitmap bitmap) { //kendisine gelen bitmap resimden inspect yapar
TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
try {
if (!textRecognizer.isOperational()) {
new AlertDialog.
Builder(this).
setMessage("Text recognizer could not be set up on your device").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> origTextBlocks = textRecognizer.detect(frame);
List<TextBlock> textBlocks = new ArrayList<>();
for (int i = 0; i < origTextBlocks.size(); i++) {
TextBlock textBlock = origTextBlocks.valueAt(i);
textBlocks.add(textBlock);
}
Collections.sort(textBlocks, new Comparator<TextBlock>() {
#Override
public int compare(TextBlock o1, TextBlock o2) {
int diffOfTops = o1.getBoundingBox().top - o2.getBoundingBox().top;
int diffOfLefts = o1.getBoundingBox().left - o2.getBoundingBox().left;
if (diffOfTops != 0) {
return diffOfTops;
}
return diffOfLefts;
}
});
StringBuilder detectedText = new StringBuilder();
for (TextBlock textBlock : textBlocks) {
if (textBlock != null && textBlock.getValue() != null) {
detectedText.append(textBlock.getValue());
detectedText.append("\n");
}
}
detectedTextView.setText(detectedText); // detectedText is a final string
}
finally {
textRecognizer.release();
}
}
private void inspect(Uri uri) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 2;
options.inScreenDensity = DisplayMetrics.DENSITY_LOW;
bitmap = BitmapFactory.decodeStream(is, null, options);
Bitmap rotatedMap = RotateBitmap(bitmap,90);
inspectFromBitmap(rotatedMap);
} catch (FileNotFoundException e) {
Log.w(TAG, "Failed to find the file: " + uri, e);
} finally {
if (bitmap != null) {
bitmap.recycle();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.w(TAG, "Failed to close InputStream", e);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GALLERY:
if (resultCode == RESULT_OK) {
inspect(data.getData());
}
break;
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
if (imageUri != null) {
inspect(imageUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
public static Bitmap RotateBitmap(Bitmap source, float angle) // it rotates the bitmap for given parameter
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
In that case, what should I do ? Thank you guys.
No, you cannot change the layout of the camera app that fulfills ACTION_IMAGE_CAPTURE intent. Actually, different devices will not have same camera apps. Each may have very different look-and-feel. You need a 'custom camera' to control its layout and UX.
I have tried many different approaches but none of them seem to help, so the problem is the following:
Image isn't uploading to imageButton. I have the path and I have checked it via debugger, added some Toasts to that the fragment gets to the onActivityResult and it does, but the image isn't uploading. Any ideas?
public class AddProductFragment extends Fragment {
private static final String TAG = "AddProductFragment";
private static final int GALLERY_INTENT = 2;
private Uri imageUri;
private ImageButton imageButton;
private EditText productName,produtPrice,productDescription;
private Button btnCancel,btnAdd;
private FirebaseDatabase mDb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDb = FirebaseDatabase.getInstance();
}
private void onClickEvents() {
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i,"Select Picture"),GALLERY_INTENT);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: Edit this;
String name = productName.getText().toString();
String price = produtPrice.getText().toString();
String description = productDescription.getText().toString();
DatabaseOperation dbOps = new DatabaseOperation(mDb,getContext());
dbOps.AddProduct(imageUri,name,price,description);
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO: exit fragment
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_product, container, false);
imageButton = (ImageButton) v.findViewById(R.id.imageButton2);
productName = (EditText)v.findViewById(R.id.addProduct_productName);
produtPrice = (EditText)v.findViewById(R.id.addProduct_productPrice);
productDescription = (EditText)v.findViewById(R.id.addProduct_productDescription);
btnAdd = (Button) v.findViewById(R.id.addProduct_addBtn);
btnCancel = (Button) v.findViewById(R.id.addProduct_cancelBtn);
onClickEvents();
return v;
}
public Bitmap getBitmap(String path) {
Bitmap bitmap = null;
try {
File f = new File(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
imageButton.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(AddProductFragment.this.getActivity(), "Number 1", Toast.LENGTH_SHORT).show();
if(requestCode == GALLERY_INTENT){
Toast.makeText(AddProductFragment.this.getActivity(), "Number 2", Toast.LENGTH_SHORT).show();
if(resultCode == Activity.RESULT_OK) {
Toast.makeText(AddProductFragment.this.getActivity(), "Number 3", Toast.LENGTH_SHORT).show();
String path = getPathFromCameraData(data, this.getActivity());
Toast.makeText(AddProductFragment.this.getActivity(), "Uploading", Toast.LENGTH_SHORT).show();
if (path != null) {
setFullImageFromFilePath( path);
Toast.makeText(AddProductFragment.this.getActivity(), "Uploaded", Toast.LENGTH_SHORT).show();
}
}
}
}
public void setFullImageFromFilePath( String imgPath) {
// btn.setImageBitmap(BitmapFactory.decodeFile(imgPath));
getBitmap(imgPath);
}
public static String getPathFromCameraData(Intent data, Context ctx) {
Uri selectedImage = data.getData();
String[] pathToFile = {MediaStore.Images.Media.DATA};
Cursor cursor = ctx.getContentResolver().query(selectedImage, pathToFile, null,
null, null);
if(cursor == null) return null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(pathToFile[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
}
}
case GALLERY_INTENT:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageURI(selectedImage);// To display selected image in image view
}
Can someone help me understand how to use OnPause() and OnResume() in this code? I'm trying to save last Selected or Captured image in imageView so when the user closes the program and comes back again he doesn't need to set or take the image again.
package com.example.thang.sdcardimagesactivity;
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
Button button;
ImageView imageView;
String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
imageView=(ImageView) findViewById(R.id.image);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Switch();
return true;
}
});
}
public void Switch(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==REQUEST_CODE&&resultCode== Activity.RESULT_OK){
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 filePath = cursor.getString(columnIndex);
Log.v("roni", filePath);
cursor.close();
if(bitmap != null && !bitmap.isRecycled())
{
bitmap = null;
}
bitmap = BitmapFactory.decodeFile(filePath);
//imageView.setBackgroundResource(0);
imageView.setImageBitmap(bitmap);
}catch (Exception e){
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);};
#Override
protected void onPause() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
SharedPreferences.Editor editor = sp.edit();
editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
super.onPause();
}
#Override
protected void onResume() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
imageView.setImageBitmap(myBitmap);
super.onResume();
}
}
View Activity
public class ViewActivity extends Activity {
ImageButton imageViews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
imageViews = (ImageButton) findViewById(R.id.image);
// textView=(TextView) findViewById(R.id.textview);
Intent intent = getIntent();
Uri data = intent.getData();
if (intent.getType().indexOf("image/") != -1)
{
imageViews.setImageURI(data);
}
setResult(RESULT_OK, intent);
Bundle bundle=new Bundle();
bundle.putInt("image",R.id.image);
intent.putExtras(bundle);
finish();
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
You can save an image to the SD card so it can be permanently accessed. It's best you do this immediately in the onActivityResult() method.
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "ImagesFolder");
File file = new File(imagesFolder, "image.jpg");
String fileName = file.getAbsolutePath();
try {
FileOutputStream out = new FileOutputStream(file);
squareBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("Image", "Convert");
}
And to load it back when you restart the application (in onCreate or preferably in onResume):
try {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "ImagesFolder");
if (!imagesFolder.exists())
imagesFolder.mkdirs();
if (new File(imagesFolder, "image.jpg").exists()) {
String fileName = new File(imagesFolder, "image.jpg").getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(fileName);
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);
}
} catch (NullPointerException e) {
Log.e("Exception", "null");
}
Of course you can change the folder and image name.
I can capture an image, either through camera or gallery. I also have two imageviews to set the captured images to it. But I always get the failed binder transaction when I try to start an intent with the passed two compressed bitmaps:
public class PostFragment extends Fragment implements OnClickListener {
View post_view;
Button button1, button0;
ActionBar actionBar;
private Uri mImageCaptureUri;
private ImageView mImageView, mImageView2;
private AlertDialog dialog;
private String imagepath = null;
Bitmap bitmap, bitmap1, bitmap2, bitmap_image1, bitmap_image2;
String krt, krt1, krt2;
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
post_view = inflater.inflate(R.layout.postoffer_fragment_layout,
container, false);
getActivity().getActionBar().setIcon(R.drawable.ic_offer);
button1 = (Button) post_view.findViewById(R.id.button1);
button1.setOnClickListener(this);
button0 = (Button) post_view.findViewById(R.id.button0);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
captureImageInitialization();
mImageView = (ImageView) post_view.findViewById(R.id.imageView1);
mImageView2 = (ImageView) post_view.findViewById(R.id.imageView2);
return post_view;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
// setText() sets the string value of the TextView
Intent intent = new Intent(getActivity(), OfferInformation.class);
if (krt1 != "" && krt2 != "") {
intent.putExtra("image", krt1);
intent.putExtra("image2", krt2);
startActivity(intent);
}
}
private void captureImageInitialization() {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
/*tbd
*/
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
mImageView.setTag("2");
/*tbd
*/
}
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
if (mImageView.getDrawable() == null) {
bitmap1 = BitmapFactory.decodeFile(imagepath);
mImageView.setImageBitmap(bitmap1);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
byte[] imageBytes1 = baos1.toByteArray();
krt1 = Base64.encodeToString(imageBytes1, Base64.DEFAULT);
} else if (mImageView.getDrawable() != null
&& mImageView2.getDrawable() == null) {
bitmap2 = BitmapFactory.decodeFile(imagepath);
mImageView2.setImageBitmap(bitmap2);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
krt2 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
}
break;
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, proj,
null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
}