Android How to pass EditText and ImageView within Fragments - android

So what i want to do is that from first.java Fragment pass the EditText data and ImageView to two.java. I manage to replace first.java with two.java when i click the button (transaction.replace(R.id.top,Two);). I am familiar with Intent but i am not sure how to pass EditText and Imageview in Fragments. Please refer to the screenshot.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
first first=new first();
transaction.add(R.id.top,first);
transaction.commit();
}
}
first.java
public class first extends Fragment implements View.OnClickListener{
Button get_button;
EditText get_input_name;
ImageView get_image;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first,container,false);
get_input_name=(EditText)rootView.findViewById(R.id.input_name);
get_button=(Button)rootView.findViewById(R.id.submit);
get_image=(ImageView)rootView.findViewById(R.id.img1);
get_button.setOnClickListener(this);
return rootView;
}
public void onClick(View v){
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
two Two=new two();
transaction.replace(R.id.top,Two);
transaction.commit();
}
}
two.java
public class two extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
Anyone can help? thx

Put both values in Bundle.
Bundle bundle = new Bundle();
bundle.putString("edtValue", <EditText value>);
bundle.putString("image", <Image path/url>);
Pass Bundle in Fragment
Two.setArguments(bundle);
Fetch these value in second fragment
Bundle bundle = getArguments();
String edtValue = bundle.getString("edtValue");
Tip : You should use camel case while declaring class name, check Java Coding Style Guidelines or Google Java Style Guide

You cannot share data between two fragments if they are on different activities but you can declare a variable in activity and get the result in any of the two fragments.
If both fragment are on same activity you can use Bundle , putExtra method for sharing data.
Further read Link
RRR answer is right.

You can do this by using constructor too.
in second activity make on constructor with values you want to get.
String text;
String imagepath;
// or int imageid;
public Two(String text, String imagepath /* or int imageid*/) {
super();
this.text = text;
this.imagepath = imagepath;
//or
this.imageid = imageid;
}
and from first fragment do like this.
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
two Two=new two(get_input_name.getText().toString.Trim(),imagepath /*or R.drawable.Imageid*/);
transaction.replace(R.id.top,Two);
transaction.commit();

FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
Bundle args = new Bundle();
args.putInt("your_data",value);
two Two=new two();
two.setArguments(args);
transaction.replace(R.id.top,Two);
transaction.commit();
in two.java
Get these value and set in fragment
public class two extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Bundle b = getArguments();
String s = b.getInt("your_data");
// Do Whatever you want
return inflater.inflate(R.layout.fragment_two, container, false);
}
}

Related

Activity to Fragment Bundle not being received

UPDATE: This is my current code, however it breaks after I re-click the same button....
Cause: java.lang.IllegalStateException: Fragment already active
I have a main_activity.xml split into Frame layouts.
The upper frame layout contains an edit text and 3 buttons (small, medium, large).
The lower frame layout contains a text view to populate the text of the edit text in either small, medium or large font.
I put the text into a bundle and am attempting to reopen that bundle in the corresponding fragment once the button is clicked.... however, the bundle does not contain any text information from the text according to my debugger.
Here is my code with the medium, large buttons removed
Any help, please?
MainActivity:
public class MainActivity extends AppCompatActivity {
TextView textView;
Button bSmall;
Small fSmall = new Small();
Bundle bundle = new Bundle();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.fragment)!=null){
if(savedInstanceState!=null){
return;
}
}
final EditText editText = (EditText) findViewById(R.id.type_here);
final Button bSmall = (Button)findViewById(R.id.small);
Button bMedium = (Button)findViewById(R.id.medium);
bSmall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message_small = editText.getText().toString();
small = message_small;
bundle.putString("message_small", message_small);
fSmall.setArguments(bundle);
FragmentManager fm =getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment, fSmall).commit();
}
});
bMedium.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message_medium = editText.getText().toString();
bundle.putString("message_medium", message_medium);
fMedium.setArguments(bundle);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment, fMedium).commit();
}
});
}
public String getMyData(){
return small;
}
}
Small:
public class Small extends Fragment {
EditText editText;
View myView;
public Small() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_small, container, false);
Bundle bundle = new Bundle();
bundle = getArguments();
MainActivity activity = (MainActivity)getActivity();
//String dataFromMainActivity = activity.getMyData();
String myString = bundle.getString("message_small");
TextView set = myView.findViewById(R.id.small_text);
set.setText(myString);
// Inflate the layout for this fragment
return myView;
}
}
You forgot to add the bundle to the fragment.
You need to do something like this:
Small fSmall = new Small();
...
bundle.putString("message_small", message_small);
fSmall.setArguments(bundle);
FragmentManager fm =getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment, fSmall);
I think you forgot to add your bundle to your Fragment before calling the fragment manager.
You should try something like this:
Small fSmall = new Small();
Bundle bundle = new Bundle();
bundle.putString("message_small", message_small); //parameters are (key, value).
fSmall.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, fSmall).commit();
In your second fragment, you should check if myString is not null or empty.
String myString = getArguments().getString("message_small");
if (myString == null) {
Log.e("TAG", "Error: null argument");
}
EDIT I see another problem here. You are accessing varaibles that have not been instatiated. You should inflate your layout before calling findViewById() or it will return a NullPointerException.
Update your Small class like this :
public class Small extends Fragment {
private EditText editText;
View myView;
public Small() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
myView = inflater.inflate(R.layout.fragment_small, container, false);
String myString = getArguments().getString("message_small");
// Here, myView is != null
TextView editText = myView.findViewById(R.id.small_text);
// Here, editText is != null
editText.setText(myString);
return myView;
}
}
Best

replace fragment with another fragment along with remove view

I have one activity and two Fragments. FragmentA and FragmentB.
I need to implement like, Initially FragmentA should be there.
and After Button click FragmentB should be there.
in my condition when activity is being displayed,fragmentA is showing and when click to button,fragmentB placed at the bottom of fragmentA and do not replace FragmentA
My activity Code is:
public class FragmentActivity extends AppCompatActivity {
FrameLayout activityFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
activityFragment = (FrameLayout) findViewById(R.id.activityFragment);
Fragment fragment = new FragmentA();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.activityFragment, fragment);
transaction.commit();
}
public void goToFrag(View view) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = new FragmentB();
transaction.add(R.id.fragmentRoot, fragment);
transaction.commit();
}
}
my first fragment code:
public class FragmentA extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view=inflater.inflate(R.layout.fragment_a,container,false);
return view;
}
}
my second fragment code:
public class FragmentB extends Fragment {
public FragmentB() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view=inflater.inflate(R.layout.fragment_b,container,false);
return view;
}
}
First of all, you should always have a FrameLayout in xml to replace your fragments there, then you use different containers to add fragments activityFragment and fragmentRoot .You should replace fragments in one container. You can use either add or replace for FragmentManager , so it activityFragment is your container (which should be a framelayout as a wrapper as the docs suggest) you use
public void goToFrag(View view) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = new FragmentB();
transaction.replace(R.id.activityFragment, fragment); // use the same container where you switch A and B
transaction.commit();
}

Getting NullPointerException while passing string between two Fragments [duplicate]

This question already has answers here:
How to pass values between Fragments
(18 answers)
Closed 6 years ago.
I have Two Dynamic Fragments associated with one activity, I am trying to pass one Text from First Fragment to Second Fragment using Bundle, but I am getting Null Pointer Exception. Is it the right way to pass String between two fragments? Below is my code :
First Fragment
public class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_main, container, false);
String text = "GetThisStringInSecondFragment";
TextView txtView = null;
txtView = (TextView) view.findViewById(R.id.firstfragmenttext);
txtView.setText(text);
Bundle bundle = new Bundle();
bundle.putString("HI", text);
return view;
}
}
Second Fragment
public class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_secondmain,
container, false);
TextView txtView = null;
txtView = (TextView) view.findViewById(R.id.secondfragmenttext);
Bundle bundle = this.getArguments();
String myInt = bundle.getString("HI");
txtView.setText(myInt);
return view;
}
}
Activity
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnLoad = (Button) findViewById(R.id.btn_load);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FirstFragment hello = new FirstFragment();
fragmentTransaction.add(R.id.fragment_container, hello, "HELLO");
fragmentTransaction.commit();
FragmentManager fragmentManager2 = getFragmentManager();
FragmentTransaction fragmentTransaction2 = fragmentManager2.beginTransaction();
SecondFragment hello2 = new SecondFragment();
fragmentTransaction2.add(R.id.fragment_container, hello2, "HELLO");
fragmentTransaction2.commit();
}
};
btnLoad.setOnClickListener(listener);
}
}
You are doing getArguments in second fragment but where are you sending those arguments from first fragment. You can use Interface here and define it in activity. From activity, you can use setArgument() method for second fragment.
check the following link for more detailed information and steps to do that.
https://developer.android.com/training/basics/fragments/communicating.html

Pass value to fragment

I am creating a app in which i wanna slide images,so for that i will be using view pager.For the image i have created a fragment which will display the images.
Code
public class ImageSwitcher extends BaseFragment {
private ImageView imageView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
}
private void initialize() {
imageView = (ImageView) view.findViewById(R.id.image_switcher);
imageView.setBackgroundResource("");
}
Now at this line
imageView.setBackgroundResource("");
the image will come from the int array which i will pass.
My doubt is
How will i pass int values to fragments
Is there any better way to use image switcher
Pass your Integer value from your fragment using Bundle as below:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
fragment.setArguments(bundle);
Access the value in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int m_id=getArguments().getInt("id");
return inflater.inflate(R.layout.fragment, container, false);
}
class MyFragment extends Fragment {
private static final String ARG_BG_RES="ARG_BG_RES";
public Fragment() {}
static public newInstance(String backgroundRes) {
Bundle args = new Bundle();
args.putExtra(ARG_BG_RES, backgroundRes);
Fragment fragment = new Fragment();
fragment.setArguments(args);
return f;
void whereYouNeedIt() {
String backgroundRes = getArguments().getStringExtra(ARG_BG_RES);
...
}
}
From outside:
MyFragment f = MyFragment.newInstance("black");
Don't omit public Fragment() {} it's required by the OS.
You can use bundle to pass values to the fragment or during initializing pass values via a custom constructor
For background resource if you are not changing images based on some logic in code, apply it via XML background and a drawable :-/

Fragments the right way

I'm trying out some fragments right now. I've got a fragment with a button and when I click that button I switch to another fragment. Now when I push on the back button I return to the first fragment that's good. Now when I click again on that button a new fragment is started. So I always start a new fragment. I think thats not the way it needs to be done. Is there a better way to for example resume the already created fragment?
My code:
public static class PlaceholderFragment extends Fragment{
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button test = (Button)rootView.findViewById(R.id.button);
test.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
Log.d("Test", "Button clicked.");
TestFrag newFragment = new TestFrag();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
return rootView;
}
}
public static class TestFrag extends Fragment {
public TestFrag() {
Log.d("Test","New fragment");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
return rootView;
}
}
When you use the fragment transaction you can specify a tag for the fragment
fragmentTransaction.add(R.id.main_fragment, newFragment, fragTag);
fragmentTransaction.commit();
Then later you can find a fragment by tag from the fragmentManager
newFragment = fragMan.findFragmentByTag(fragTag);
if newFragment then is null you should create the Fragment since it wasnt found by the tag
Thanks to Joakim:
fragmentTransaction.add(R.id.main_fragment, newFragment, fragTag); fragmentTransaction.commit();
Then later you can find a fragment by tag from the fragmentManager
newFragment = fragMan.findFragmentByTag(fragTag); if newFragment then is null you should create the Fragment since it wasnt found by the tag. If the tag isn't null you can just add and commit the new one.

Categories

Resources