How to open an Image in new activity when clicked in viewpager? - java

I'm using viewpager to display the slideshow of the images but when I'm clicked on any one of the image it need to opened in new activity. Can anyone help me?
I'm displaying toast message when clicked on image but my actually requirement is to open the image in new activity.
The code is below:
class MyCustomPagerAdapter extends PagerAdapter{
private Context context;
private int images[];
private LayoutInflater layoutInflater;
public int i;
MyCustomPagerAdapter(Context context, int images[]) {
this.context = context;
this.images = images;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
View itemView = layoutInflater.inflate(R.layout.full_profile, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.expandedImage);
imageView.setImageResource(images[position]);
container.addView(itemView);
//listening to image click
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "you clicked image " + (position + 1), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ImageOpeningActivity.class);
intent.putExtra("MY_IMAGE", images[position]);
context.startActivity(intent);
}
});
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
ImageOpeningActivity.class
class ImageOpeningActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageopening);
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
if(getIntent()!=null){
int image = getIntent().getExtras().getInt("MY_IMAGE");
imageView.setImageResource(image);
}
}
}
although i changed my code i getting an error, the error is below.
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.vmax.kalyanam/com.vmax.kalyanam.ImageOpeningActivity}: java.lang.IllegalAccessException: java.lang.Class<com.vmax.kalyanam.ImageOpeningActivity> is not accessible from java.lang.Class<android.app.Instrumentation>
public class Full_profile extends Activity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayout;
//public String title = "KANDIBANDA ROJA";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_profile);
ViewPager viewPager;
int images[] = {
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.one
};
MyCustomPagerAdapter myCustomPagerAdapter;
viewPager = (ViewPager)findViewById(R.id.viewPager);
myCustomPagerAdapter = new MyCustomPagerAdapter(Full_profile.this, images);
viewPager.setAdapter(myCustomPagerAdapter);

put intent here in "listening to image click"
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this,PhotoViewerActivity.class);
intent.putExtra("image", imageurl);
startActivity(intent);
}
});
public class PhotoViewerActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = getIntent().getStringExtra("image");
// you can show image from url using library like glide or picasso
}
#Override
protected int getLayoutResourceId() {
return R.layout.activity_photo_viewer;
}
#Override
public void onBackPressed() {
PhotoViewerActivity.this.finish();
}
}

First of all do this in your code instead of Toast. Comment out Toast and paste these lines.
Intent intent = new Intent(this, ImageOpeningActivity.class);
intent.putExtra("MY_IMAGE", images[position]);
context.startActivity(intent);
step2: Create activity with the name of ImageOpeningActivity and in its xml take a Imageview , let suppose its Id is myImageView then do following in your on create
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
if(getIntent()!=null){
int image = getIntent().getExtras().getInt("MY_IMAGE");
imageView.setImageResource(image);
}
I am supposing that your images[position] is integer array.

Like #Pratap said you can send image url from one activity to another. But if you wanted to pass image itself as bitmap follow this method.
Bitmap implements Parcelable, so you can pass it as intent extra.
Intent intent = new Intent(this, ImageDetailActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it in ImageDetailActivity by calling,
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
Warning: Do not pass data more than 500Kb through Intent Refer this site

create new activity with imageview in xml layout and call this from your viewpager image onclick
Intent intent = new Intent(this, ImageDetailActivity.class);
intent.putExtra("image",images[i]);
startActivity(intent);
ImageDetailActivity.java
public class ImageDetailActivity extends AppCompatActivity {
Drawable imageDrawable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_detail);
Intent intent = getIntent();
imageDrawable= getResources().getDrawable(intent.getIntExtra("image",-1));
imageView.setImageDrawable(imageDrawable);
}
}
Make sure you add this ImageDetailActivity to your android manifest file

Related

why can't I put item_form.class on intent?

I want to transfer Uri from a dialog activity to a normal activity
public class popup extends AppCompatDialogFragment {
ActivityItemFormBinding binding;
ActivityResultLauncher<String> selectpic;
public Uri newUri;
public Button camera, gallery, send;
public popuplistener listener;
public ImageView Display;
#Override
public Dialog onCreateDialog( Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.popup, null);
builder.setView(view);
binding = ActivityItemFormBinding.inflate(getLayoutInflater());
Display = view.findViewById(R.id.display);
selectpic = registerForActivityResult(
new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
if(!(result == null)) {
Display.setVisibility(View.VISIBLE);
send.setVisibility(View.VISIBLE);
newUri = result;
Display.setImageURI(newUri);
}
}
}
);
Ive made a method to take Uri from selectpic result but I cannot start intent because it wont take the parameters item_form.class
private void sendpic() {
Intent intent = new Intent(popup.this, item_form.class);
intent.putExtra("imageUri", newUri);
startActivity(intent);
I do not understand how to resolve this part where Intent won't take item_form as parameter. How do I proceed to fix this problem?

NextActivity onCreate() is skipped

I am creating a social app and the users can upload an image and then write a caption on the next screen right after. My problem is that the activity where the user creates the caption, gets completely skipped over and goes to the profile page. The image goes to the firebase storage but I can't write a caption.
07-10 15:23:21.150 30970-31309/tabian.com.hash E/ImageLoader: UIL doesn't support scheme(protocol) by default [com.google.android.gms.tasks.zzu#f488c6e]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
java.lang.UnsupportedOperationException: UIL doesn't support scheme(protocol) by default [com.google.android.gms.tasks.zzu#f488c6e]. You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromOtherSource(BaseImageDownloader.java:280)
at com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:99)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.downloadImage(LoadAndDisplayImageTask.java:291)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryCacheImageOnDisk(LoadAndDisplayImageTask.java:274)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:230)
at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:136)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
GalleryFragment.Java
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: Started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Closing the gallery screen.");
Objects.requireNonNull(GalleryFragment.this.getActivity());
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to the final share screen.");
if (isTaskRoot()) {
Intent intent = new Intent(GalleryFragment.this.getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
GalleryFragment.this.startActivity(intent);
} else {
Intent intent = new Intent(GalleryFragment.this.getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
GalleryFragment.this.startActivity(intent);
Objects.requireNonNull(GalleryFragment.this.getActivity());
}
}
});
init();
return view;
}
NextActivity.Java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = (EditText) findViewById(R.id.caption) ;
setupFirebaseAuth();
ImageView backArrow = (ImageView) findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Closing the activity");
finish();
}
});
TextView share = (TextView) findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = (Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
}
});
setImage();
}
ProfileActivity.Java :
public class ProfileActivity extends AppCompatActivity implements
ProfileFragment.OnGridImageSelectedListener ,
ViewPostFragment.OnCommentThreadSelectedListener,
ViewProfileFragment.OnGridImageSelectedListener{
private static final String TAG = "ProfileActivity";
#Override
public void onCommentThreadSelectedListener(Photo photo) {
Log.d(TAG, "onCommentThreadSelectedListener: selected a comment thread");
ViewCommentsFragment fragment = new ViewCommentsFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.view_comments_fragment));
transaction.commit();
}
#Override
public void onGridImageSelected(Photo photo, int activityNumber) {
Log.d(TAG, "onGridImageSelected: selected an image gridview: " + photo.toString());
ViewPostFragment fragment = new ViewPostFragment();
Bundle args = new Bundle();
args.putParcelable(getString(R.string.photo), photo);
args.putInt(getString(R.string.activity_number), activityNumber);
fragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(getString(R.string.view_post_fragment));
transaction.commit();
}
private static final int ACTIVITY_NUM = 4;
private static final int NUM_GRID_COLUMNS = 3;
private Context mContext = ProfileActivity.this;
private ProgressBar mProgressBar;
private ImageView profilePhoto;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Log.d(TAG, "onCreate: started.");
init();
}

Add a font to an Intent to send to another activity

I've got 2 activities (well actually 4 but only 2 matter for now), the main activity and the font changing activity. The main activity sends text that the user has typed in to the font changing activity using an intent and startActivityForResult. Within the font changing activity the user can change the font of the text, as expected. What I'm trying to do is after the user has changed the font, send the text and the new font back to the main activity. But I'm not sure how to do this. I'm thinking of using some kind of bundle but I am stuck. If anyone could help me that would be greatly appreciated.
Here's my (relevant) Main Activity code:
public class MainActivity extends AppCompatActivity
{
RelativeLayout move_group;
ImageView view;
String backgroundImageName;
SeekBar seekSize;
TextView user_text;
Button button;
SeekBar tiltChange;
String temp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_text = (TextView) findViewById(R.id.user_text);
static final int REQUEST_FONT = 4;
public void FontChange(View view)
{
Intent fontIntent = new Intent(this, Main4Activity.class);
fontIntent.putExtra("Text", temp);
startActivityForResult(fontIntent, REQUEST_FONT);
}
//There's supposed to be an accompanying onActivityResult method as well
//but i haven't figured that part out yet
}
Here's my (relevant) Font Activity code:
public class Main4Activity extends AppCompatActivity
{
TextView user_font_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
user_font_text = (TextView) findViewById(R.id.user_font_text);
}
public void boldText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_bold);
user_font_text.setTypeface(custom_font);
}
public void italicText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_italic);
user_font_text.setTypeface(custom_font);
}
public void regularText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_regular);
user_font_text.setTypeface(custom_font);
}
public void thinText(View view)
{
Typeface custom_font = getResources().getFont(R.font.avenir_next_thin);
user_font_text.setTypeface(custom_font);
}
public void OK(View view)
{
//The intent and/or bundle would go here but I don't know what to do
}
}
public void FontChange(View view)
{
temp = user_text.getText().toString();
Intent fontIntent = new Intent(this, Main4Activity.class);
fontIntent.putExtra("Text", temp);
startActivityForResult(fontIntent, REQUEST_FONT);
}
this will fetch your string from textview to fontActivity.
Now in your FontActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
Intent intent = getIntent();
String text = intent.getStringExtra("temp");
user_font_text = (TextView) findViewById(R.id.user_font_text);
user_font_text.setText(text);
}
public void OK(View view)
{
Intent returnIntent = new Intent();
returnIntent.putExtra("result",
user_font_text.getText().toString());
returnIntent.putExtra("font",
ypur_font_type);
setResult(Activity.RESULT_OK, returnIntent);
}
Remaining part of setting font style can be done using SpannableStringBuilder. here you can check SpannableStringBuilder . Hope this helps.

Get onActivityResult when returning from startActivityForResult in Adapter

I am trying to return some data when a user clicks back from the Activity.
I am calling startActivityForResult from the adapter, but when I actually press back from the Activity, onActivityResult never seems to be called
Code is trimmed down for example
Fragment1
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View mainView = inflater.inflate(R.layout.grid_view, container, false);
return mainView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new Adapter(this.getActivity(), new ArrayList<Item>());
mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view);
mGridView.setAdapter(mAdapter);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.w(TAG, "in activity result");
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
}
Adapter
public Adapter(Context context, List<Item> objects) {
super(context, -1, objects);
this.context = context;
addAll(objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.grid_view_item, parent, false);
}
View recommendationLayout = view.findViewById(R.id.recommendation_layout);
recommendationLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), Activity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
((Activity) context).((Activity) context).startActivityForResult(intent, 1);(intent, 1);
}
});
return view;
Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailed_view);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
denyEditPermission = extras.getBoolean("denyEditPermission");
}
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("denyEditPermission", denyEditPermission);
setResult(RESULT_OK, intent);
finish();
}
Since you use activity context to start the activity, you will get onActivityResult callback in activity, not in fragment. To get callback in fragment, you need to use fragment context/start activity in fagment itself. I would suggest interface approach to fix the issue here.Create an interface and implement it in your fragment and when the recommendationLayout is clicked, call the interface method from adapter so that you can handle the click event in fragment itself.
Something like,
Create an interface file -
public interface RecommendationClickListener {
public void onRecommendationClicked();
}
Fragment:
public class MyFragment extends Fragment implements RecommendationClickListener{
...
...
...
#Override
public void onRecommendationClicked() {
Intent intent = new Intent(getActivity(), NextActivity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
startActivityForResult(intent, 1);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = new Adapter(this.getActivity(), new ArrayList<Item>());
mAdapter.setRecommendationClickListener(this);
mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view);
mGridView.setAdapter(mAdapter);
}
Adapter:
private RecommendationClickListener mRecommendationClickListener;
public void setRecommendationClickListener(RecommendationClickListener recommendationClickListener) {
this.mRecommendationClickListener = recommendationClickListener;
}
View recommendationLayout = view.findViewById(R.id.recommendation_layout);
recommendationLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRecommendationClickListener != null) {
mRecommendationClickListener.onRecommendationClicked();
}
}
});
The Broadcast solution is as follows:
In Fragment
Declare on top of the class
public final static String START_ACT = "com.yourcompanyname.appname.START_ACT";
private Radio radio;
On the createView initiate and register the receiver
//Initiate our receiver
radio = new Radio();
//Activate our recevier
getActivity().getApplicationContext().registerReceiver(radio, new IntentFilter(START_ACT));
Also in the fragment, create the receiver class and the mothod which calls the Activity
/**
* Receiver Class
* This setup checks for the incoming intent action to be able to
* attach more messages to one receiver.
*/
private class Radio extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(START_ACT)){
getDataFromActivity();
}
}
}
public void getDataFromActivity(){
Intent intent = new Intent(getActivity(), Activity.class);
Bundle extras = new Bundle();
extras.putBoolean("denyEditPermission", true);
intent.putExtras(extras);
startActivityForResult(intent, 1);
}
After from anywhere in the application send message to our radio
context.sendBroadcast(new Intent(Fragment1.START_ACT));

Android GridView Adapter with AsyncTask

I parse XML from web and I want to put this data to GridView in other activity, can you help me?
My first activity:
public class HomeScreenActivity extends Activity {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton:
Intent intent = new Intent(this, TopArtistsScreen.class);
intent.putExtra("username", username);
new DownloadXmlTask(this, HomeScreenActivity.this)
.execute("URL");
startActivity(intent);
}
My AsyncTask
public class DownloadXmlTask extends AsyncTask<String, Void, List<Artist>> {
#Override
protected void onPostExecute(List<Artist> result) {
progressDialog.dismiss();
gridView.setAdapter(new TopArtistsImageAdapter(context, result));
}
TopArtistsImageAdapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView==null) {
view = inflater.inflate(R.layout.items, null);
}
TextView textView = (TextView) view.findViewById(R.id.grid_item_name);
ImageView imageView = (ImageView) view.findViewById(R.id.grid_item_image);
textView.setText(artistsList.get(position).getName());
imageLoader.DisplayImage(artistsList.get(position).getImage(), imageView);
return view;
}
PS I shoud start another activity only after downloading all information
I shoud start another activity only after downloading all information
=> Make changes as below:
1) Only execute your AsyncTask on button click
new DownloadXmlTask(this, HomeScreenActivity.this).execute("URL");
2) Start Activity inside onPostExecute() method of your AsyncTask:
Intent intent = new Intent(HomeScreenActivity.this, TopArtistsScreen.class);
intent.putExtra("username", username);
startActivity(intent);

Categories

Resources