Passing data by using bundle between tablayout - android

I am using Bundle to passing data from my First TabFragment but it prompts out with the NullPointerException. Error is occur when getArguments() in list_fragments2 in second tab
MainActivity Fragment
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
Toast.makeText(this, "" + b, Toast.LENGTH_SHORT).show();
SecondActivity Fragment
public class list_fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View h = inflater.inflate(R.layout.tab2, container, false);
TextView textView = (TextView) h.findViewById(R.id.textView);
Bundle bundle=getArguments();
//your string
if(bundle != null) {
String test = bundle.getString("test");
textView.setText(test);
}
return h;
}
}

Do you actually load your second fragment?
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
fragmentTransaction.replace(placeholder, fragment);
fragmentTransaction.commit();

I think you can create your instance of list_fragment2 code within list_fragment2. Maybe your codes recreated list_fragment2 many times.
public static list_fragment2 createInstance() {
list_fragment2 fragment = new list_fragment2();
Bundle bundle = new Bundle();
bundle .putString("test","text");
fragment.setArguments(bundle);
return fragment;
}

Related

Share information between fragments

I need to share information between fragments. I know that I can use sharedpreferences but I think that is not optimized.
This is the parent fragment code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_blank, container, false);
....
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.eventos_pager, new BlankFragment2());
ft.commit();
....
return view;
}
This fragment call BlankFragment2 and BlankFragment1 need to sends information to BlankFragment2
I can share information to BlankFragment2 by the BlankFragment2's constructor. It is not allowed.
In Android you pass values to Fragments via bundles.
Using AndroidStudio File > New > Fragment > Fragment (Blank) will generate something like this.
public class MTFragment extends Fragment {
private String mParam1;
public static MTFragment newInstance(String param1) {
MTFragment fragment = new MTFragment();
Bundle args = new Bundle();
args.putString("value", param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("value");
}
}
}
From your code:
MTFragment mFragment = MTFragment.newInstance("Hello");
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.eventos_pager, mFragment);
ft.commit();

How to transfer from one fragment to another in Android

I want to transfer some data like "editText1Double" and "sum" to another fragment (SecondFragment) that will use those data. How would I do that?
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_fragment, container, false);
editText1 = (EditText) v.findViewById(R.id.editText1);
editText2 = (EditText) v.findViewById(R.id.editText2);
editText3 = (EditText) v.findViewById(R.id.editText3);
textView = (TextView) v.findViewById(R.id.textView);
calculateButton = (Button) v.findViewById(R.id.calculateButton);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText1Double = Double.parseDouble(editText1.getText().toString());
editText2Double = Double.parseDouble(editText2.getText().toString());
editText3Double = Double.parseDouble(editText3.getText().toString());
sum = editText1Double + editText2Double + editText3Double;
}
});
1) Using Bundle :
FragmentManager fM = getActivity().getSupportFragmentManager();
FragmentTransaction fT = fM.beginTransaction();
Fragment_B fragment = new Fragment_B();//receiving fragment
Bundle bundle = new Bundle();
bundle.putDouble("key", sum);
fragment.setArguments(bundle);
fT.add(R.id.container, fragment);
fT.addToBackStack(null);
fT.commit();
and Receive as
Bundle bundle = getArguments();
Double sum = bundle.getDouble("key");
2)Using Construcor:
FragmentManager fM = getActivity().getSupportFragmentManager();
FragmentTransaction fT = fM.beginTransaction();
Fragment_B fragment = new Fragment_B(sum);//receiving fragment
fT.add(R.id.container, fragment);
fT.addToBackStack(null);
fT.commit();
and Receive as
public class Fragment_B extends Fragment{
private double sum;
public Fragment_B (double sum) {
this.sum= sum;
}
public Fragment_B () {
}}
Pass data by using
fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putDouble("double", 1.1);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack(null).commit();
And get data in another Fragment using
Bundle bundle = getArguments();
double d = bundle.getDouble("double")
Hope it works fine for you.
Sending data from fragment_A
FragmentManager fM = getActivity().getSupportFragmentManager();
FragmentTransaction fT = fM.beginTransaction();
Fragment_B fragment = new Fragment_B();//receiving fragment
Bundle bundle = new Bundle();
bundle.putDouble("sum_key", sum);
fragment.setArguments(bundle);
fT.add(R.id.container, fragment);
fT.addToBackStack(null);
fT.commit();
Receiving data at fragment_B
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle = getArguments();
Double sum = bundle.getDouble("sum_key");
}

putExtra from activity then getExtra in fragment

i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea? my case is diffrent because i wanna do it in fragment
myActivity :
if(email.matches(users.user1)&&password.matches(users.pass1)){
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
Intent i = new Intent(LoginActivity.this,ProfileFragment.class);
i.putExtra("pn", users.pn1);
i.putExtra("name", users.name1);
i.putExtra("family", users.family1);
i.putExtra("rank", users.rank1);
startActivity(intent);
finish();
}
myfragment
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile2, container, false);
final TextView pn =getActivity().findViewById(R.id.pn);
final TextView name =getActivity().findViewById(R.id.name);
final TextView family =getActivity().findViewById(R.id.family);
final TextView user =getActivity().findViewById(R.id.user);
final TextView rank =getActivity().findViewById(R.id.rank);
String pnget = getActivity().getIntent().getStringExtra("pn");
String nameget = getActivity().getIntent().getStringExtra("name");
String familyget = getActivity().getIntent().getStringExtra("family");
String userget = getActivity().getIntent().getStringExtra("user");
String rankget = getActivity().getIntent().getStringExtra("rank");
pn.setText(pnget);
name.setText(nameget);
family.setText(familyget);
user.setText(userget);
rank.setText(rankget);
}
Hi . i tried to put and get extra from activity to fragment . but something is wrong! anybody have idea?
You start an intent call intent. But the intent have data is i, and it have't started yet.
You can use setArgument and getArgument to send and receive data from activity to fragment or from fragment to fragment:
In YourReceiveFragment:
public static Fragment newInstance(String data1, String data2, ...) {
Fragment f = new YourReceiveFragment();
Bundle bundle = new Bundle();
bundle.putString(DATA_RECEIVE1, data1);
bundle.putString(DATA_RECEIVE2, data2);
f.setArguments(bundle);
return f;
}
In your activity: Just call it:
Fragment f = YourReceiveFragment.newInstance(yourString1, yourString2);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.main_container, f).commit();
Then in YourReceiveFragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null){
String dataReceive1 = getArguments().getString(DATA_RECEIVE1);
String dataReceive2 = getArguments().getString(DATA_RECEIVE2);
}
}
In case you want to send data from an activity to a fragment in another activity, use interface or an easier way is just pass the data to the activity which contains fragment and from that, send data to fragment.
You can't create a Fragment with startActivity. You need to create the fragment with bundle like this:
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putString("name", users.name1);
args.putString("family", users.family1);
fragment.setArguments(args);
// then tell the FragmentManager to attach the fragment
// to the activity
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.your_placeholder, fragment);
ft.commit();
Then in your onCreateView get them with:
String name = getArguments().getString("name", "");
String family = getArguments().getString("family", "");
Please remember that you need to move the return code to the last of onCreateView method and change your code to something like this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile2, container, false);
TextView pn =view.findViewById(R.id.pn);
...
return view;
}
You can send data with the bundle, that is recommended
To Pass Data from Activity
fragment = new YourFragment();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("key", "value");
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
}
To receive data from Fragment
String var = getArguments().getString("value");

Android how to send data from Activity to Fragment?

I want to pass data from my Activity to a Fragment. I have no idea how to do it. I've seen many solutions but no one of them did really work.
I just want to pass a simple String to the Fragment.
I have tried it this way:
public class PhotoActivty extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
if (null == savedInstanceState) {
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
BasicFragment fragInfo = new BasicFragment();
fragInfo.setArguments(bundle);
android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.photo_frame, fragInfo);
transaction.commit();
}
}
}
What is the error there? I call it this way:
String myValue = this.getArguments().getString("message");
In the onCreateView in the Fragment
I usually use a static factory pattern:
public class MyFragment extends Fragment {
public static MyFragment newInstance(int index) {
MyFragment f = new MyFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
}
When you create the fragment in your Activity:
Fragment MyFragment = MyFragment.newInstance(5);
Alex Lockwood has a good rundown on why this is a preferred design pattern:
http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
Fragment fragInfo = new BasicFragment();
fragInfo.setArguments(bundle);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.photo_frame, fragInfo);
transaction.commit();
try this inside your if
from activity:
Bundle bundleObject = new Bundle();
bundleObject.putString("data", " Send From Activity");
/*set Fragmentclass Arguments*/
Fragment fragmentobject = new Fragment();
fragmentobject .setArguments(bundleObject );
From Fragment You receive this way:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String stringText = getArguments().getString("data");
return inflater.inflate(R.layout.fragment, container, false);
Not sure if this is the real cause of the problem, but you have to use getSupportFragmentManager() instead of getFragmentManager() inside AppCompatActivity. Also, classes such as Fragment and FragmentTransaction should come from support.v4 package.
Remove if (null == savedInstanceState) in your activity. If savedInstanceStatenull == null then BasicFragment will not replace your FrameLayout for R.id.photo_frame.

android fragment getArguments returns null in oncreateView()

I have two fragments and FilterFragment and LocationListFragment. when I am switching to LocationListFragment.java I am getting values in getArguments() and from LocationListFragment.java to FilterFragment.java getting null values by calling getArgument(); here is the details
In FilterFargment.java code is here for set values:
LocationListFragment locationListFragment = new LocationListFragment();
bundle = new Bundle();
Log.e("",""+locationList.getLocationListFilter().size());
bundle.putParcelable(Constant.LOCATION_LIST_FILTER, locationList);
bundle.putString(Constant.FROM_DATE_FILTER, textView_time_from.getText().toString());
locationListFragment.setArguments(bundle);
((DashbordActivity) getActivity()).switchFragment(locationListFragment, true);
In LocationListFragment.java (getting values)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
locationList = args.getParcelable(Constant.LOCATION_LIST_FILTER);
getFromDate = args.getString(Constant.FROM_DATE_FILTER);}}
And here from LocationListFragment on button click send data to FilterFragment sending new values with bundle:
FilterFragment filterFragment =new FilterFragment();//.newInstance(getFromDate, getEndDate, getLocation, getCategories);
Bundle bundle = new Bundle();
bundle.putString(Constant.FROM_DATE_FILTER, getFromDate);
bundle.putString(Constant.WHERE_FILTER, getLocation);
filterFragment.setArguments(bundle);
((DashbordActivity) getActivity()).switchFragment(filterFragment, true);
and in FilterFragment.java while returning back getting null value for getArguments(); code is here:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_filter, container, false);
Log.e("FilterFragment", "oncreateview");
Bundle args = getArguments();
Log.e("getArguments", "" + getArguments());//getting null here
Also, I have used this method for switching fragment,
public void switchFragment(BaseFragment fragment, boolean keep) {
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(fragment.getClass().getSimpleName(), 0);
if (!fragmentPopped && manager.findFragmentByTag(fragment.getClass().getSimpleName()) == null) { //fragment not in back stack, create it.
FragmentTransaction tr = manager.beginTransaction();
tr.replace(R.id.container, fragment, fragment.getClass().getSimpleName());
if (keep) {
tr.addToBackStack(fragment.getClass().getSimpleName());
Log.e("keep", "BaseAct:" + keep);
}
tr.commit();
}
}
Can you tell me what I am missing? Any help will be appreciated.

Categories

Resources