I want to pass string value from activity to fragment. For that I'm using bundle for transferring string value.
PUT STRING ACTIVITY
Passing string value :-
Bundle bundle = new Bundle();
bundle.putString("Value", resultp.get(CurrentProjectActivity.VALUE));
Log.d(TAG, "Value ::: " + resultp.get(CurrentProjectActivity.VALUE));
// set Fragmentclass Arguments
AmenetiesFragment fragobj = new AmenetiesFragment();
fragobj.setArguments(bundle);
In log I got "Value" value as well.
GET STRING VALUE IN FRAGMENT (IT IS NOT WORKING).
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_listview, container, false);
Bundle bundle = this.getArguments();
Log.d(TAG, "Value's value:) ::: " + bundle);
String strtext = bundle.getString("Value");
return rootView;
}
In log I'm getting NULL value for BUNDLE. Please help me to resolve this Issue. Thanks in advance.
I advice you to follow this link1 and this . You should use interface. Check here
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in the Frament task
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Suppose you want to send String data from Activity to Fragment
In Fragment.java file add the following code,
public static String name= null;
public void setName(String string){
name = string;
}
In MainActivity.java from which you want to send String add the following code,
String stringYouWantToSend;
Fragment fragment = new Fragment();
fragment.setName(stringYouWantToSend);
The savedInstance variable will be empty the first time you run your app,
it only gets filled when the onSaveInstanceState method is called, this usually happens when you rotate the screen, then savedInstance variable will be populated. Try this :
if(savedInstance != null){
Log.d(TAG, "There's is something");
}else{
Log.d(TAG, "Nothing in there");
}
First time in logcat you will see the first message, try turning your device and the message in the else will show.
As #james said, the recommended way is to use interfaces, or have a field class but this increases coupling and destroys the whole point of fragments.
make public first in activity that object you required in fragment.
then you can use like ((ACtivityName)getActivity()).objectName;
i hope it help.this is not best way to pass data into fragment.
there are some other way also.
create constructor of your fragment class and pass it and save in fragment like:
public MyFragment(String data){
this.data = data;
}
also you can use as bundle #james answer.
EDIT:-
First Way
private class MyFeagment extends Fragment {
private String data;
private Object myObject;
public MyFeagment(String data, Object anyObject) {
this.data = data;
this.myObject = myObject;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("My Fragment", "data :: " + data + " and myObject :"
+ myObject);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
let's say it is your framgnet.
and put this code in your activity
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_container, new MyFeagment("My Data",
"data"));
transaction.commit();
Easiest Approach but not Recommended
You can access activity data from fragment:
Activity:
public class MyActivity extends Activity {
private String myString = "hello";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
...
}
public String getMyData() {
return myString;
}
}
Fragment:
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyActivity activity = (MyActivity) getActivity();
String myDataFromActivity = activity.getMyData();
return view;
}
}
Related
This is the activity class of my project
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs_activity);
String LicID = "DATA"
Fragment FragmentDetail = new FragmentDetail();
Bundle data = new Bundle();
data.putString("data",LicID);
FragmentDetail.setArguments(data);
ViewPageAdapter adapter = new ViewPageAdapter(getSupportFragmentManager());
adapter.AddFragment(new FragmentDetail(),"Detail");
viewp.setAdapter(adapter);
tablay.setupWithViewPager(viewp);
}
}
This is my fragmentDetail activity. and it is a tab fragment...
public class FragmentDetail extends Fragment {
public FragmentDetail() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.detail_fragment,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String LicID = getArguments().getString ("data");
Toast.makeText(getContext(),""+LicID+" ",Toast.LENGTH_SHORT).show();
}
This code is not work.app crash without any error.... please help. thank you
in tab_activity:
public String LicID = "DATA"
When you want to access this variable from the fragment attached to activity,
in Detail Fragment :
((tab_activity) (getActivity)).LicID
so you don't have to pass arguments to the fragment and use bundle for this. If you need further assistance, please show your logcat
I think the problem is that you set argument to one fragment:
Fragment FragmentDetail = new FragmentDetail();
Bundle data = new Bundle();
data.putString("data",LicID);
FragmentDetail.setArguments(data);
And add to adapter another fragment:
adapter.AddFragment(new FragmentDetail(),"Detail");
Please, try to use the same fragment.
I want to pass data from Activity to Fragment using Bundle (I used Bundle to passing data between 2 Fragment, and that's worked).
In my Activity I have a ListView, in the OnItemClickListener I want to open a new Fragment, and the Item, which clicked pass through the Activity to this Fragment. But the Item is null, so basically nothing is send to the Fragment.
Here is my Activity:
public class Jegyek extends AppCompatActivity {
View v;
DB mydb;
ListView listView;
private String teszt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jegyek);
listView = (ListView)findViewById(R.id.jegyekLista);
mydb = new DB(this);
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(this, "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
bundle.putString("Tantárgy neve", teszt);
Toast.makeText(Jegyek.this, teszt, Toast.LENGTH_SHORT).show();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, jegyekAllando);
ListView listaNezet = (ListView) findViewById(R.id.jegyekLista);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
);
}
}
public String getTanNev () {
System.out.println("WARNING: "+ teszt);
return teszt;
}
}
And my Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = new Bundle();
String tanNev = bundle.getStrin
g("Tantárgy neve");
Jegyek jegyAct = new Jegyek();
String tanNevv = jegyAct.getTanNev();
mydb = new DB(getActivity());
String jegyAtlag =String.valueOf(mydb.JegyekAtlaga(tanNev));
String jegyDarab =String.valueOf(mydb.JegyekDarabszama(tanNev));
return rootView;
}
}
When I realized, that the bundle is null, I try to pass that List Item through getter, so I changed my Fragment code for that:
Jegyek jegyek = new Jegyek();
String jegy = jegyek.getTanNev();
But that's not solved my problem, so I back to the Bundle, which also have some problem, but I can't find it. Intresting, that in the OnItemClickListener when I Toast the Item it's correct and works, but when I want to display in the console or pass to the Fragment, the value's is null.
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Hope this helps
Please follow this example:
In your activity, Pass data like
Bundle bundle = new Bundle();
bundle.putString("test", "Test Data");
// set in your testFragment Arguments
TestFragment testFragment = new TestFragment();
testFragment.setArguments(bundle);
And Receive Data from your TestFragment Like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String text = getArguments().getString("test");
return inflater.inflate(R.layout.fragment, container, false);
}
In fragment "jegyekAllando" you must get your string from onCreate() with Bundle data = getArguments(), but you create new bundle.
I used below code to passing data from Activity to Fragment.
Fragment Code
public class StoryDetailFragmentInfo extends Fragment {
View view;
TextView txtDescrible;
final static String getData = "abc";
public static StoryDetailFragmentInfo newInstance(String paramater){
Bundle bundle = new Bundle();
bundle.putString(getData,"Message");
StoryDetailFragmentInfo fragmentInfo = new StoryDetailFragmentInfo();
fragmentInfo.setArguments(bundle);
return fragmentInfo;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments()!=null){
String test = getArguments().getString(getData);
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.story_detail_fragment_info_layout, container, false);
txtDescrible = view.findViewById(R.id.txt_describleDetail);
return view;
}
}
MainActivity Code
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story_detail_layout);
addControls();
loadData();
intentData();
fillDataToView();
}
private void intentData() {
StoryDetailFragmentInfo.newInstance("Hello babe");
}
Problem is getArgument() in my fragment is null and i can't get data What should i do?
Can you help me explain it? Thanks for reading.
If you want to pass data from activity to fragment as initial data, you can send data from activity to ViewPagerAdapter, then pass data from ViewPagerAdapter to fragment in getItem() function.
In Activity:
adapter = new ViewPagerAdapter(getSupportFragmentManager(), this,false));
adapter.setData(data);
In ViewPagerAdapter:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
MyFragment fragment = new MyFragment();
fragment.setData(data);
return fragment
}
}
If you want to pass data from activity to fragment in real time (like updating data), I recommend to use EventBus. It is a modern and convenient tool to communicate between activity and fragment. Check it at https://github.com/greenrobot/EventBus
Firstly, in the method newInstance of class StoryDetailFragmentInfo, you write these:
bundle.putString(getData,"Message"); while leave paramater alone. So you need change
bundle.putString(getData,"Message");
to
bundle.putString(getData,paramater);
Secondly, you try to get values from arguments from fragment by the key 'AdapterStoryDetailViewPager.idData', but this key is different from the key which you used to save value. So you need to change
String test = getArguments().getString(AdapterStoryDetailViewPager.idData);
to
String test = getArguments().getString(getData);
After these two steps, you would get the right value.
i must pass two parameters from fragment to another fragment. First parameter is type String and second parameter is type int. i want pass parameters with bundle but doesn't work.
FIRST FRAGMENT
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("totale", totalAmount);
fragment.setArguments(bundle);
SECOND FRAGMENT
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
TextView titolo2 = (TextView) getView().findViewById(R.id.quantità2);
Bundle bundle=this.getArguments();
int myInt = bundle.getInt("totale", 0);
titolo2.setText(myInt);
return inflater.inflate(R.layout.fragment_two, container, false);
}
Change Second Fragment like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
TextView titolo2 = rootView.findViewById(R.id.quantità2);
Bundle bundle=this.getArguments();
int myInt = bundle.getInt("totale", 0);
titolo2.setText(myInt + "");
return rootView;
}
In first fragment write this:
TwoFragment fragment = new TwoFragment ();
Bundle bundle = new Bundle();
bundle.putInt("totale", totalAmount);
fragment.setArguments(bundle);
Second fragmnent:
Bundle bundle=getArguments();
int myInt = bundle.getInt("totale", 0);
titolo2.setText(myInt);
Create a public class with two static members like this :
public class SomeClass {
public static String stringValue="";
public static int integerValue=0;
}
Then from your first fragment just set values like this :
SomeClass.stringValue="yourValue";
SomeClass.integerValue=yourIntegerValue;
You can use these variable from your second fragment where you want :
int a =SomeClass.integerValue;
String str=SomeClass.stringValue;
If both fragments belong to the same activity, better to use this approach:
In activity you should save references to fragments, and all comunications between this fragments should be through activity, let's name it BaseActivity. For example add to activity method which will pass params to second fragment:
void updateSecondFragment(int param1, String param2){
mFragment2.updateTitle(param2);
}
In second fragment:
void updateTitle(String title){
mTextView.setText(title);
}
And in first fragment:
BaseActivity mActivity;
#Override
void onAttach(Activity activity) {
if (activity instanceOf BaseActivity){
mActivity = (BaseActivity) activity;
}
}
private void updateSecondFragment(){
if (mActivity != null){
mActivity.updateSecondFragment(int param1, String param2);
}
}
You should do the work of second fragment as:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_two, container, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView titolo2 = view.findViewById(R.id.quantità2);
Bundle bundle=getArguments();
int myInt = bundle.getInt("totale", 0);
titolo2.setText(String.valueOf(myInt));
}
I don't understand how to transfer data between two fragments. I've tried this:
public class Connection extends Fragment
{
SendMessage sender;
public interface SendMessage
{
public void send(String one, String two);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
//my data
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
send = (SendMessage) getActivity();
}
private class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(final Context context, Intent intent)
{
if(message.equals("POS"))
{
sender.send(position,id);
}
}
}
in the first fragment; in the MainActivity:
public class MainActivity extends FragmentActivity implements Connection.SendMessage
{
protected void onCreate(Bundle savedInstanceState)
{
//my code
}
#Override
public void send(String one, String two)
{
Map map = new Map();
final Bundle bundle = new Bundle();
bundle.putString("Position",one);
bundle.putString("ID:",two);
map.setArguments(bundle);
}
}
and in the Map fragment(it need to receive this data):
public class Map extends Fragment
{
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Bundle bundle = new Bundle();
bundle.getArguments();
if (bundle != null)
{
String pos = bundle.getString("Position");
String id = bundle.getString("ID");
}
//then show this on googleMaps
}
}
but I don't understand why this code doesn't work..could you help me? thanks...
1) Please change your class name from Map.java to anything else. Because in java map is imported as java.util Package.
2)
Fragment map = new Fragment ();
final Bundle bundle = new Bundle();
bundle.putString("Position",one);
bundle.putString("ID:",two);
map.setArguments(bundle);
map.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, map).commit();
and in recieve
Bundle bundle = getArguments();
if (bundle != null)
{
String pos = bundle.getString("Position");
String id = bundle.getString("ID:"); (You miss : in ID)
}
Do This send fragment
String cid=id.getText().toString();
Fragment fr=new friendfragment();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
Bundle args = new Bundle();
args.putString("CID", cid);
fr.setArguments(args);
ft.commit();
Received fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("CID");
return inflater.inflate(R.layout.fragment, container, false);
}
Well, firstly. Your receiving fragment is actually accessing an empty bundle. You are doing this:
Bundle bundle = new Bundle();
bundle.getArguments();
Instead of:
Bundle bundle = getArguments();
Secondly, a good way to communicate between two fragments is by using an interface. The interface communicates with the activity and the activity with the second fragment.
Here's google's tutorial:
http://developer.android.com/training/basics/fragments/communicating.html
Also, it doesn't seem like you are inflating any xml layout file for your Map Fragment or even adding it with FragmentTransaction after you have created it. Here is a short and sweet tutorial for that as well:
http://android-er.blogspot.com/2011/12/programmatically-add-fragment.html