Changing an image when button click from another fragment - java

I want to be able to click a button on my settings fragment, which will change an image on another fragment called home fragment. My app keeps crashing once i click the button and im not sure why.
Settings Fragment :
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
button = (Button) getView().findViewById(R.id.button1);
Torso = (ImageView) getView().findViewById(R.id.Torso);
ShopGreenTorso= (ImageView) getView().findViewById(R.id.ShopGreenTorso);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Purchased", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SettingsFragment.this.getActivity(), AvatarFragment.class);
//i.putExtra("resID", R.drawable.torso2green);
Bundle b= new Bundle();
b.putInt("resID", R.drawable.torso2green);
SettingsFragment.this.setArguments(b);
//setArguments(bundle);
startActivity(i);
}
});
}
Avatar Fragment:
public class AvatarFragment extends Fragment {
public ImageView IV;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
//Bundle bundle = getActivity().getIntent().getExtras();
// Bundle bundle=getArguments();
Bundle b=getArguments();
if(b!= null)
{
int resid = b.getInt("resID");
IV.setBackgroundResource(resid);
}
return rootView;
}
}
I believe the error is coming from IV.setImageResource(resid) but im not entirely sure, any help would be much appreciated.

It's hard to tell without seeing the exception, but it might be because Bundle mappings are case-sensitive.
Your SettingsFragment uses "ResId", but your HomeFragment is expecting "resID". If no mapping is found in the Bundle, you'll be given the default value of 0 for resID. It's possible that you're crashing when calling IV.setImageResource(0);.

Your image implementation in code is wrong, you need to init your image view like this :
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
Bundle bundle = getActivity().getIntent().getExtras();
if(bundle!= null)
{
int resid = bundle.getInt("resId");
IV.setImageResource(resid);
}
return rootView;
}

Don't pass value from Fragment to Fragment directly.
You should use setArguments from SettingsFragment and getArguments in HomeFragment

Related

How to get the onClick function?

I am trying to make a scientific calculator inside a fragment. Actually following a YT video and that guy is doing all that in his mainactivity not the fragment. I used this code in xml of my fragment:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_scientific_calculator, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
previousCalculation = view.findViewById(R.id.previousCalculationView);
display = view.findViewById(R.id.displayEditText);
}
private void updateText(String strTOAdd) {
display.setText(strTOAdd);
}
public void zeroBTNPush(View view) {
updateText("0");
}
All I know is that to use findViewById in a fragment, I have to create a onViewCreated void. So after doing all this I should get the updateText function in fragment.java>design>attributes>onClick but I get nothing there
enter image description here
I'm new to this. Please help
You can just set OnClickListener in your fragment code like this
someBtn.setOnClickListener(new OnClickListener(){
// call the method you want to be excecuted when the buttun is being pressed
})
also you can specify it in the design, but for example I would prefer to work with the XML code directly - it's much more understantable for me
To use findViewById I think all you need is a View object, which is returned by onCreateView, so you could just do:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scientific_calculator, container, false);
Button btn = view.findViewById(R.id.yourButtonId);
btn.setOnClickListener((View v) -> {
// do something here
});
}
You can do this in onViewCreated with the view that is passed in by getting the button and setting a click listener on it like this:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//...
Button myButton = view.findViewById(R.id.myButton);
myButton.setOnClickListener((View v) -> {
// do button stuff
});
}

Can't see Dialog Fragment in Android Studio

I use dialog fragment to show dialog from activity.
There is no error and I can find Log at my Logcat but I can't see the dialog when I run the application.
I don't know what's the problem.
Here is my Activity code:
btnEventRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getSupportFragmentManager();
DialogPlusEvent dialogPlusEvent = new DialogPlusEvent();
Bundle bundle = new Bundle();
bundle.putString("eventPlaceName", eventPlaceName);
bundle.putLong("currentUserDistance", currentUserDistance);
dialogPlusEvent.setArguments(bundle);
dialogPlusEvent.show(fragmentManager, "DialogPlusEvent");
Log.d("Dialog Fragment", "Working");
}
});
Dialog Fragment code:
public class DialogPlusEvent extends DialogFragment implements View.OnClickListener{
TextView dpeTvPlaceName, dpeStar, dpeTvMyDistance;
private String dpePlaceName;
private Long dpeMyDistance;
private Button dpeBtnOkay;
public static DialogPlusEvent getInstance() {
DialogPlusEvent dialogPlusEvent = new DialogPlusEvent();
return dialogPlusEvent;
}
#Nullable
public View OnCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_plus_event, container);
SharedPreferences sharedPreferences = this.getContext().getSharedPreferences("file", Context.MODE_PRIVATE);
currentPage = sharedPreferences.getString("currentPage", "");
/.../
Bundle bundle = getArguments();
dpePlaceName = bundle.getString("eventPlaceName");
dpeMyDistance = bundle.getLong("currentUserDistance");
dpeBtnOkay = view.findViewById(R.id.dpeBtnOkay);
dpeBtnOkay.setOnClickListener(this);
setCancelable(false);
return view;
}
public void onClick(View view) {
dismiss();
}
}
#Shay Kin is right. you did not implement the onCreateView method correctly.
I ran the code as you provided, it works well and I can see the dialog, so I think the problem is not in this code.
public class TestFragmentActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_fragment);
findViewById(R.id.btn_click).setOnClickListener(this);
}
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getSupportFragmentManager();
DialogPlusEvent dialogPlusEvent = new DialogPlusEvent();
Bundle bundle = new Bundle();
dialogPlusEvent.setArguments(bundle);
dialogPlusEvent.show(fragmentManager, "DialogPlusEvent");
Log.d("Dialog Fragment", "Working");
}
}
public class DialogPlusEvent extends DialogFragment implements View.OnClickListener{
TextView dpeTvPlaceName, dpeStar, dpeTvMyDistance;
private String dpePlaceName;
private Long dpeMyDistance;
private Button dpeBtnOkay;
public static DialogPlusEvent getInstance() {
DialogPlusEvent dialogPlusEvent = new DialogPlusEvent();
return dialogPlusEvent;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_plus_event, container);
setCancelable(false);
return view;
}
public void onClick(View view) {
dismiss();
}
}
You made a mistake while implementing the onCreateView method
Just change the method from OnCreateView to onCreateView like below :
#Nullable
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_plus_event, container);
SharedPreferences sharedPreferences = this.getContext().getSharedPreferences("file", Context.MODE_PRIVATE);
currentPage = sharedPreferences.getString("currentPage", "");
/.../
Bundle bundle = getArguments();
dpePlaceName = bundle.getString("eventPlaceName");
dpeMyDistance = bundle.getLong("currentUserDistance");
dpeBtnOkay = view.findViewById(R.id.dpeBtnOkay);
dpeBtnOkay.setOnClickListener(this);
setCancelable(false);
return view;
}

How to pass data from Fragment to Tablayout fragment

This is will run fragment in fragment that use viewpageAdapter.I want to pass data from fragment to tablayout fragment. i have try any method and still crash. i just want to passs once data to fragment in the tablayout.
First fragment. this line i want pass to tablayout fragment:-
specItem = getArguments().getString("spec_item");
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageUrl = getArguments().getString("image_url");
priceItem = getArguments().getString("price_item");
specItem = getArguments().getString("spec_item");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_details_item, container, false);
textPrice = (TextView) rootView.findViewById(R.id.textPrice);
image_Details = (ImageView) rootView.findViewById(R.id.image_Detail);
tabLayout = (TabLayout) rootView.findViewById(R.id.tablayout_id);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpage_id);
textPrice.setText(priceItem);
Picasso.get().load(imageUrl).into(image_Details);
ViewPageAdapter adapter = new ViewPageAdapter(getActivity().getSupportFragmentManager());
adapter.AddFragment(new FragmentSpecifications(), "Specification");
adapter.AddFragment(new FragmentReview(), "Review");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
Second fragment in tablayout, i dont know how to recieve:-
View rootView;
TextView textSpec;
String specItem;
public FragmentSpecifications() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_specification, container, false);
textSpec = (TextView) rootView.findViewById(R.id.textviewspec);
textSpec.setText();
return rootView;
}
Inside your FragmentSpecifications create a instance of the Fragment to send data to it, like this:
public static FragmentSpecifications newInstance(String priceItem) {
Bundle args = new Bundle();
args.putString("priceItem", priceItem);
FragmentSpecifications fragment = new FragmentSpecifications();
fragment.setArguments(args);
return fragment;
}
After that in same FragmentSpecifications override onCreate method and get value:
private String priceItem;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
priceItem = getArguments().getString("priceItem");
}
And finally when you add FragmentSpecifications do adapter pass the value:
adapter.AddFragment(FragmentSpecifications.newInstance(priceItem), "Specification");

How to call fragment method from another fragment using androidx

I am using androidx jetpack navigation component in my application and I am confused on how to call a method in previous fragment from the current fragment.
There is currently no resource online on how to do this.
My implementation is below...
FRAGMENT A
This is the code sample of the first fragment.
public class FragmentOne extends Fragment{
private String holder;
private NavController navController;
private Button btn_next;
private void findViews(View view){
btn_next = view.findViewById(R.id.btn_next);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
findViews(view);
holder = "VALUE IN HOLDER VARIABLE";
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
navController.navigate(R.id.action_fundone_to_fragmenttwo);
}
});
}
public void executeInFragmentTwo(){
System.out.println(holder);
Toast.makeText(getContext(), holder, Toast.LENGTH_LONG).show();
}
}
FRAGMENT TWO
This is the code sample of the second fragment
public class FragmentTwo extends Fragment{
private NavController navController;
private Button btn_exec_fragment_one_method;
private void findViews(View view){
btn_exec_fragment_one_method= view.findViewById(R.id.btn_exec_fragment_one_method);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
findViews(view);
btn_exec_fragment_one_method.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//HOW DO I CALL FRAGMENT ONE METHOD FROM HERE
//The method with name "executeInFragmentTwo"
}
});
}
}
Please any help on this would really be appreciated.
Your first fragment will not be in a resumed state when the user is onto the second fragment.
If you need a function to be executed from another screen/fragment then you probably need to move this function to a ViewModel that is either tied to the lifecycle of the graph that these screens/fragments are part of or to the host activity lifecycle so that you get the same instance in both screens/fragments.
To inject a model that lives as long as your graph you use the following syntax:
private val model: MyViewModel by navGraphViewModels(R.id.myGraph) { ViewModelFactory() }

clickable card view simple without recycler view

I have a fragment and have linear layout that contains 2 simple card views.
How can I make card view clickable cardviews?
I have searched, but all topics are about cardviews in recycler view ... But I have a simple clickable cardview.
public class popFragment extends Fragment {
public popFragment()
{
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.popfragment,container,false);
return view;
}
}
You can simply assign id in your layout xml to each card view. then in oncreateView() of the fragment bind the view and use mycardView.setOnclickListener.... .
public class popFragment extends Fragment {
private CardView cardView1;
private CardView cardView2;
public popFragment()
{
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.popfragment,container,false);
cardView1 = view.findViewById(R.id.my_card_view_1);
cardView2 = view.findViewById(R.id.my_card_view_2);
cardView1.setOnClickListener(v->{
//set on click functions here
});
cardView2.setOnClickListener(v->{
//set on click functions here
});
return view;
}
}
do not forget to assign the corresponding ids in your layout.xml

Categories

Resources