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?
Related
public class SignUpActivity extends AppCompatActivity
{
private CircleImageView profilePic,galleryPick,cameraPick;
private ActivityResultLauncher<Intent> activityResultLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
profilePic = findViewById(R.id.circular_image);
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result)
{
if(result.getResultCode() == RESULT_OK && result.getData() != null)
{
Bundle bundle = result.getData().getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
profilePic.setImageBitmap(bitmap);
}
}
});
profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
chooseProfilePic();
}
});
}
private void chooseProfilePic()
{
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_dialog,null);
builder.setCancelable(false);
builder.setView(dialogView);
galleryPick = findViewById(R.id.gallery_pick);
cameraPick = findViewById(R.id.camera_pick);
AlertDialog alertDialog = builder.create();
alertDialog.show();
cameraPick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager()) != null)
{
activityResultLauncher.launch(cameraIntent);
}
}
});
}
}
So I am a beginner in Android Studio and since startForActivityResult is deprecated I am
looking for something to replace it. The new method works but there occurs a problem when
used with private method including the alert dialog.
You are finding the resourceId of the button in the dialog from wrong view.
Buttons are present in dialog while you are finding it from activity/fragment view.
Update your code to find it from dialogView.
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_dialog,null);
builder.setCancelable(false);
builder.setView(dialogView);
galleryPick = dialogView.findViewById(R.id.gallery_pick); // find id from dialog view
cameraPick = dialogView.findViewById(R.id.camera_pick); // find id from dialog view
AlertDialog alertDialog = builder.create();
alertDialog.show();
There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing
If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});
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
I'm having problems storing intent extras from my previous activity when I use another intent to open an activity and return the result.
Logic:
Activity A: receive string from check box, uses intent hasExtra to pass to activity b
Activity B: List of edit text fields with buttons to activity c
Activity C: uses intent extra to get string and pass to another editTextField in activity b
Problem is that I keep losing the intentExtra from a to b.
I apologise if my description is not thorough, I'm new to Java.
Activity A
public class PipesInspection extends AppCompatActivity{
private static final String TAG = "PipesInspection";
ArrayList<String> pipesInspectionSelection = new ArrayList<String>();
Button nextButtonToPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.residential_pipes_inspection_lv_selected);
Log.d(TAG, "onCreate: starting");
initialiseWidgets();
}
public void initialiseWidgets(){
nextButtonToPost = (Button) findViewById(R.id.nextButton);
nextButtonToPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String final_category_selection = "";
for (String Selections : pipesInspectionSelection){
final_category_selection = final_category_selection + Selections + ", ";
}
Log.v(TAG,"gotten text: " + final_category_selection);
String selectedChoices = pipesInspectionSelected.getText().toString();
Intent pipesInspectionIntent = new Intent(v.getContext(), PostAJobActivity.class);
pipesInspectionIntent.putExtra("selectedChoices", selectedChoices);
v.getContext().startActivity(pipesInspectionIntent);
}
});
}
}
Activity B
public class PostAJobActivity extends AppCompatActivity {
private static final String TAG = "PostAJobActivity";
EditText jobTitle, jobDescription, jobLocation;
String location, title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_a_job);
Log.d(TAG, "onCreate: starting");
jobDescription = (EditText)findViewById(R.id.input_job_description);
mapsButton = (ImageButton) findViewById(R.id.mapButton);
mapsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, LaunchMapsActivity.class);
startActivity(intent);
}
});
getIntentExtras();
}
public void getIntentExtras(){
jobLocation = (EditText) findViewById(R.id.location);
Intent intentLocation =getIntent();
location= intentLocation.getStringExtra("location");
jobLocation.setText(location);
jobTitle = (EditText) findViewById(R.id.title);
Intent pipesInspectionIntent = getIntent();
title = pipesInspectionIntent.getStringExtra("selectedChoices");
jobTitle.setText(title);
}
}
Activity C
public class PlaceListAdapter extends RecyclerView.Adapter<PlaceListAdapter.PlaceViewHolder> {
private Context mContext;
private PlaceBuffer mPlaces;
public PlaceListAdapter(Context context, PlaceBuffer places) {
this.mContext = context;
this.mPlaces = places;
}
#Override
public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Get the RecyclerView item layout
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.maps_item_place_card, parent, false);
return new PlaceViewHolder(view);
}
#Override
public void onBindViewHolder(final PlaceViewHolder holder, int position) {
String placeName = mPlaces.get(position).getName().toString();
String placeAddress = mPlaces.get(position).getAddress().toString();
holder.nameTextView.setText(placeName);
holder.addressTextView.setText(placeAddress);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentLocation = new Intent(v.getContext(), PostAJobActivity.class);
intentLocation.putExtra("location",holder.nameTextView.getText().toString()+
", " + holder.addressTextView.getText().toString());
v.getContext().startActivity(intentLocation);
}
});
}
I think this article may be helpful
https://developer.android.com/training/basics/intents/result.html
I am not sure I understand the problem correctly...activity A starts first and passes data to activity B which invokes activity C and gets data from it return to activity B which uses the data collected from both activities to do something
....If this is your problem you should not start activity C the normal way you should use startActivityforresult() form activity B to start activty C
and wait for it to finish then return to B with the data collected from C....starting the activity B from activity C will create new instance of B without having the data collected form A while using this way the instance of B with data from A will wait to C to finish and take the data from it in addition to that move the getIntentExtras() function inside the onClick()
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));