I have an image which is coming from custom Gallery inside fragment's onActivityresult
Calling custom Gallery
Custom_Gallery custom_gallery=new Custom_Gallery();
custom_gallery.setTargetFragment(this,301);
getFragmentManager().beginTransaction().replace(R.id.FragmentMain,custom_gallery).addToBackStack(null).commit();
Sending Result back to fragment from Custom Gallery
bundle.putStringArrayList("Media",media);
Intent intent = new Intent();
intent.putExtras(bundle);
getTargetFragment().onActivityResult(getTargetRequestCode(),getActivity().RESULT_OK,intent);
FragmentManager fragmentManager=getFragmentManager();
fragmentManager.popBackStack();
Getting result inside onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==301 && resultCode==getActivity().RESULT_OK){
List<String> image=data.getStringArrayListExtra("Media");
Log.d(TAG,"Image "+image.get(0));
String img=image.get(0);
//File uploadedImage = new File(image.get(0));
/*Bitmap myImage=BitmapFactory.decodeFile(image.get(0));
uploadImage.setImageBitmap(myImage);*/
Glide.with(getActivity()).load(img)
.apply(new RequestOptions()
.skipMemoryCache(true)
.error(R.drawable.add_fav)
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.NONE))
.into(uploadImage);
uploadButton.setEnabled(true);
functions=new App_Functions(getActivity());
Bitmap bitmap = BitmapFactory.decodeFile(image.get(0));
String Base64Image=functions.Convert_To_Base64(bitmap);
//Log.d(TAG,"Base 64 "+Base64Image);
}
}
Here's the image path which I am getting from custom gallery inside Fragment's onActivityResult
/storage/emulated/0/Download/Media/Images/Ximg1520693707996.jpg
I tried with Bitmap's decodefile method then set manually to Imageview but still not working i thought its Glide issue but its not even setting with Bitmap.
Imageview has onClicklistener and i wanted to set selected image to ImageView
There is an issue with lifecycle of android ecosystem. As onResume calls after onActivityResult. All i need to save image path in String when getting result at onActivityResult then use it on set path in ImageView at onResume
Related
I have images selected from the gallery displayed in ImageView, But not retaining or saved Image when the android device restart I need to re-pick an image again. My plan is for the image to still stay on the image view even the device is rebooted , or do I need to create some data to save the image and display to ImageView
public class FirstFragment extends Fragment implements View.OnClickListener{
ImageView imageButton1;
private Uri mImageUri;
#Override
public void onResume() {
super.onResume();
}
private File mSnapFile;
private static final String ARG_URI_IMAGE_1 = "image1Uri";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_first, container, false);
imageButton1 = (ImageView) v.findViewById(R.id.firstimagebtn);
imageButton1.setOnClickListener(this::onClick);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
imageButton1.setImageURI(Uri.parse(mImageUri));
}
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.firstimagebtn:
Intent intent;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 0:
if(resultCode == Activity.RESULT_OK){
if (data != null) {
// This is the key line item, URI specifies the name of the data
mImageUri = data.getData();
// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(mImageUri));
editor.commit();
// Sets the ImageView with the Image URI
imageButton1.setImageURI(mImageUri);
imageButton1.invalidate();
}
}
break;
case 1:
if(resultCode == Activity.RESULT_OK){
// This is the key line item, URI specifies the name of the data
mImageUri2 = data.getData();
// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image2", String.valueOf(mImageUri2));
editor.commit();
// Sets the ImageView with the Image URI
imageButton2.setImageURI(mImageUri2);
imageButton2.invalidate();
}
break;
}
}
You can use image loading libraries like Glide or Picasso. They provide data caching and your image will be persisted.
See docs
By default, Glide checks multiple layers of caches before starting a new request for an image:
1.Active resources - Is this image displayed in another View right now?
2.Memory cache - Was this image recently loaded and still in memory?
3.Resource - Has this image been decoded, transformed, and written to the disk cache before?
4.Data - Was the data this image was obtained from written to the disk cache before?
The first two steps check to see if the resource is in memory and if so, return the image immediately. The second two steps check to see if the image is on disk and return quickly, but asynchronously.
If all four steps fail to find the image, then Glide will go back to the original source to retrieve the data (the original File, Uri, Url etc).
Hope this helps. Let me know if you face an issue with this but I think the docs are pretty much self explanatory.
Trying to create an app which makes lists. To create a new element in my list I want to use another activity. I do it like that:
public void onNewTask(View view)
{
Intent newTask = new Intent(MainActivity.this, NewTaskActivity.class);
MainActivity.this.startActivityForResult(newTask, 0);
}
After returning to the main activity with results like this:
public void onSave(View view){
Intent main = new Intent();
String[] data;
//getting data here//
main.putExtra("New_task", data);
setResult(RESULT_OK, main);
finish();
}
After that, the linear layout does not show any children, though if I debug my code, I can see that the layout still has them inside. I am adding children programmatically, like this:
LinearLayout linearLayout = findViewById(R.id.toDoLayout); //is in OnCreate()
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams //is in OnCreate()
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout newLayout = new LinearLayout(this);
newLayout.setOrientation(LinearLayout.HORIZONTAL);
TextView newNumberTextView = new LargeTextViewWithMargins(this);
newNumberTextView.setText("Test");
newLayout.addView(newNumberTextView);
linearLayout.addView(newLayout, layoutParams);
And the onActivityResult is now in this form:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
setContentView(R.layout.activity_main);
}
I've found a similar question here. Does anyone know what may cause such a situation and how it is better to overcome it?
As kelvin suggested, I've removed setContenView from activityResult and this helped. However, I do not understand how it works, but it will do for me for now.
setContentView(R.layout.activity_main); sets the XML (Layout ) for your activity when you call setContentView it will inflate the Layout on the Screen. Now when you are calling it again in onActivityResult You are inflating the view again.
Also I would suggest you to use ListView / RecyclerView for showing lists.
I am currently working on a movie review app. I am trying to pass data from a Recyclerview to another recyclerview in a new activity. Currently I know how to pass data from Recyclerview to textview and imageview. However I looked online and also tried codes but still I could not pass data from recyclerview to recyclerview. What I am trying to pass is a String ArrayList that contains urls. How could I pass the data? Please help me TY! I just recently started on android studio
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(mContext)
.asBitmap()
.load(mImageUrls.get(position))
.into(holder.image);
holder.name.setText(mNames.get(position));
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Clicked on an image: " + mNames.get(position));
Toast.makeText(mContext, mNames.get(position), Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(v.getContext(), MovieDetails.class);
//v.getContext().startActivity(intent);
Intent intent = new Intent(mContext, MovieDetails.class);
intent.putExtra("image_url", mImageUrls.get(position));
intent.putExtra("image_name", mNames.get(position));
intent.putExtra("director_name", mDirector.get(position));
intent.putStringArrayListExtra("movieTrailer", mTrailer);
mContext.startActivity(intent);
}
});
}
private void setImage(String imageUrl, String imageName, String directorName, ArrayList trailerUrl) {
Log.d(TAG, "setImage: setting the image and name to widgets.");
TextView name = findViewById(R.id.text_movie_original_title);
name.setText(imageName);
ImageView image = findViewById(R.id.image_movie_detail_poster);
Glide.with(this)
.asBitmap()
.load(imageUrl)
.into(image);
TextView director = findViewById(R.id.text_movie_director_name);
director.setText(directorName);
RecyclerView trailer = findViewById(R.id.movie_videos);
trailer.set;
bundle.putParcelableArrayList("urlList", list)
send it via intent
get arraylist by
getParcelableArrayList("urlList")
i think these steps would help:
1. create arrays
put the same values to the arrays, you put on the recyclerView.
pass the arrays using intent. Example:
Bundle bundle = new Bundle();
bundle.putStringArray("arrayOfName", new String[]{name1, name2});
bundle.putStringArray("arrayOfImageUrls", new String[]{url1, url2});
Intent intent=new Intent(context, SecondActivity.Class);
intent.putExtras(bundle);
then in the second activity:
Bundle bundle = this.getIntent().getExtras();
String[] names=bundle.getStringArray("arrayOfName");
String[] urls=bundle.getStringArray("arrayOfImageUrls");
add this arrays to the recyclerView adapter in the SecondActivity
set the Adapter to your recyclerView
I managed to use myimageview.setImageUri when the scheme was content://
But it doesnt work if my Uri has a file:// scheme. What is wrong and how can I make it work?
I have given both read and write permission.
Edit:
To make sure I haven't messed up anything, I created a whole new project.
Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
ArrayList<Uri> myimageUri = null;
myimageUri = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
Uri theuri = myimageUri.get(0);
ImageView myimageView = findViewById(R.id.imageView);
myimageView.setImageURI(theuri);
}
Attaching a debugger I found out that theuri is
file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/IMG-20171101-WA0005.jpg
It still doesn't work, but content :/// URIs work.
Try following code:
InputStream in = myimageView.g etContext().getContentResolver(). openInputStream(theuri);
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close();
myimageView.setImageBitmap(bitmap);
You need to decode image file to a bitmap and give it to ImageView.
Bitmap mBitmap = Media.getBitmap(this.getContentResolver(), yourUri);
imageView.setImageBitmap(bitmap);
I am new to programming and I need to know how do I use getpixels to convert the image I have into grayscale.Pls help me: ( I need to get an image from my gallery, convert it into bitmap and start doing image processing. I only have 2 days left for my submission. I really need help with using getPixels.
public class SelectImageActivity extends Activity implements OnClickListener {
// Image loading result to pass to startActivityForResult method.
private static int LOAD_IMAGE_RESULTS = 1;
// GUI components
private Button button; // The button
private ImageView image;// ImageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_image);
// Find references to the GUI objects
button = (Button)findViewById(R.id.button);
image = (ImageView)findViewById(R.id.image);
// Set button's onClick listener object.
button.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
Bitmap bitmap1=BitmapFactory.decodeFile(imagePath);
int threshold=50;
int result[];
for (int x=0; x<bitmap1.getWidth();x++)
{
for (int y=0; y<bitmap1.getHeight();y++)
{
if (bitmap1.getPixel(x, y)>threshold)
result[x,y]=255; () //((I have a error here saying "The primitive type int of x does not have a field y"))
else
result[x,y]=0;
}
}
I think the reason for error The primitive type int of x does not have a field y is your result array initialization.
You should wrote :
int[][] result = new int[bitmap1.getWidth()][bitmap1.getHeight()];
instead of int result[]; and access the element using result[x][y].