How do I pass gson JsonObject between fragments in the same activity - android

I'm refactoring my app and currently rewriting two activities as two fragments in the same activity. This was how I used to send gson JsonObject from the first activity to the second activity:
Activity1:
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("form", gson.toJson(form));
startActivity(intent);
Activity2:
intent = getIntent();
form = gson.fromJson(intent.getStringExtra("form"), JsonObject.class);
Now that I've rewritten Activity1 and Activity2 as fragments in the same activity, is there a similar approach that I can use to send and retrieve data in the fragments? I just find using intents very intuitive, but I figured fragments use a different way of communicating with one another.

Bundle args = new Bundle();
args.putString("form", gson.toJson(form));
secondFragment.setArguments(args);
and in your targeted Fragment :
getArguments().getString("form");

Hi hope i am not late on this. Using the Gson Library you can achieve this feature.
In your first fragment say Fragment A. you can parse the Gson to a new
Bundle bundle = new Bundle();
bundle.putSerializable("form", new Gson().toJson(Form));
FragmentA fragment = new FragmentA();
fragment.setArguments(bundle);
loadFragment(fragment); // TODO
Then get this in your second fragment (Fragment B) as so
private Form form;
....
....
Bundle bundle = this.getArguments();
if(bundle != null){
form = new Gson().fromJson((String) bundle.getSerializable("form"), Form.class);
// get parameters e.g form name, form id
String name = form.getName();
....
}
Hope this helps. Have fun :)

Related

Trying to get string value from activity1 to fragment of activity 2 but it returns as null. GetArgument always returns as null

I am trying to get bundle extras from activity 1 to fragment of activity 2 but getargument() always returns as null.
//Using this to get string in fragment
String value = getArguments().getString("abc");
//activity1 code that i used to get the extras
Bundle bundle = new Bundle();
bundle.putString("abc", townextra);
UserFragment myFrag = new UserFragment();
myFrag.setArguments(bundle);
There is a problem with logic of passing data.
Correct way would be: Pass data from Activity1 to Activity2, and then from Activity2 to Fragment.
all fixed. I added a new function on my activity 2 to create fragment. instead of doing it in oncreat. it all works fine, thanks
Your Activity
Bundle bundle = new Bundle();
bundle.putString("params", "Your String data");
// set MyFragment Arguments
MyFragment myObj = new MyFragment();
myObj.setArguments(bundle);
The Fragment.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam = getArguments().getString("params");
}
}
But will be better if you show the code how you pass data between activities and then use my answer.
And please add your fragment code.

Is it a good idea to send data to two fragments from the same activity?

Below is a snapshot of the activity code. I want to send the lists to separate fragments. The first one works fine, however in stepsFragment.setArguments(stepsBundle); setArguments isn't recognized. thank you.
//
// Send the ingredients array list in Parcelable to the Ingredients Fragment
//
private void sendArrayToIngredientsFragment() {
//Pack Data in a bundle(call the bundle "ingredientsBundle" to differentiate it from the "stepsBundle"
Bundle ingredientsBundle = new Bundle();
ingredientsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Ingredients Fragment
IngredientsFragment ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setArguments(ingredientsBundle);
getSupportFragmentManager().beginTransaction().replace(R.id.ingredients_fragment_container, ingredientsFragment).commit();
}
/*
Send the steps array list in Parcelable to the Steps Fragment
*/
private void sendArrayToStepsFragment() {
//Pack Data in a bundle(call the bundle "stepsBundle" to differentiate it from the "ingredientsBundle"
Bundle stepsBundle = new Bundle();
stepsBundle.putParcelable("Recipes", recipes);
//Pass Over the bundle to the Steps Fragment
StepsFragment stepsFragment = new StepsFragment();
stepsFragment.setArguments(stepsBundle);
getSupportFragmentManager().beginTransaction().replace(R.id.steps_fragment_container, stepsFragment).commit();
}
}
Take sure, your fragment classes both extends from Fragment class. If that so, there must be method setArguments()

Android: How to pass MULTIPLE ArrayList<String> values and one ArrayList<LatLng> from one activity to another in a bundle? Not working

I have several List<String> variables to pass from Splash to the Main activity:
1) I read somewhere that I can pass them as ArrayList<String> from Splash to Main, and it works... i.e.
I can receive only the first ArrayList<String> variable. In my bundle below, I am not able to receive the second ArrayList<String>. (array_list2) Why?
2) How to pass ArrayList<LatLng> from one activity to another
First Activity:
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
Bundle b=new Bundle();
b.putStringArrayList("array_list1",(ArrayList<String>)Names);
b.putStringArrayList("array_list2",(ArrayList<String>)City);
b.putStringArrayList("array_list3",(ArrayList<String>)Country);
b.putStringArrayList("array_list4",(ArrayList<String>)Code);
b.putStringArrayList("array_list5",(ArrayList<LatLng>)coordinates); //ERROR in this line, type mismatch!
intent.putExtras(b);
startActivity(intent);
Second Activity:
Bundle b = getIntent().getExtras();
if (b != null) {
testList1 = b.getStringArrayList("array_list1");
testList2 = b.getStringArrayList("array_list2"); //THIS gives the same arraylist as testList1 and it is incorrect!
Log.e("TESTLIST1",testList1.toString()); //just using Log.e to view o/p as test
Log.e("TESTLIST2",testList1.toString());
Please answer both my questions. None of the other topics helped me, and I spent over 2 hours on this.
Thank you.
putStringArrayList() will not support for ArrayList .
use
putParcelableArrayList();
instead of
putStingArrayList();
or else you can use direct method of intent.
Change your code somethng like this:
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
Bundle b=new Bundle();
b.putStringArrayList("array_list1",(ArrayList<String>)Names);
b.putStringArrayList("array_list2",(ArrayList<String>)City);
b.putStringArrayList("array_list3",(ArrayList<String>)Country);
b.putStringArrayList("array_list4",(ArrayList<String>)Code);
If you want to pass through bundle object use below line of code.
b.putParcelableArrayList("array_list5",(ArrayList<LatLng>)coordinates);
Otherwise pass through intent object.
intent.putParcelableArrayListExtra("array_list5",coordinates);
intent.putExtras(b);
startActivity(intent);
Because LatLng class implements Parcelable interface, so instead of using Bundle. putStringArrayList use Bundle.putParcelableArrayList to send ArrayList which contains class object which is implementing Parcelable interface. Use
b.putParcelableArrayList("array_list5",coordinates);
How to use parcelable with List or ArrayList - What is
the syntax?
Do it as:
ArrayList<String> arrCoordinates = new ArrayList<>(coordinates.size());
arrCoordinates.addAll(coordinates);
b.putParcelableArrayList("array_list5",arrCoordinates);
and get array_list5 as from Bundle
ArrayList<LatLng> coordinates = b.getParcelableArrayList("array_list5");

How to pass Multiple information from one screen to another screen in android

I have a sign-up form, and I have to pass all info filled in that form to another screen. I know how to display if there is one field, but in sign-up form there are multiple fields. so I want to know how to display all the info.
If you are launching a new activity, just create a Bundle, add your values, and pass it into the new activity by attaching it to the Intent you are using:
/*
* In your first Activity:
*/
String value = "something you want to pass along";
String anotherValue = "another something you would like to pass along";
Bundle bundle = new Bundle();
bundle.putString("value", value);
bundle.putString("another value", anotherValue);
// create your intent
intent.putExtra(bundle);
startActivity(intent);
/*
* Then in your second activity:
*/
Bundle bundle = this.getIntent().getExtras();
String value = bundle.getString("value");
String anotherValue = bundle.getString("another value");
To pass User data(multiple info) from one screen to another screen :
Create a model for user with setter and getter method.
make this class Serializable or Parcelable (Prefer) .
Create object of user class and set all data using setter method.
Pass this object from one activity to another by using putSerializable.
Person mPerson = new Person();
mPerson.setAge(25);
Intent mIntent = new Intent(Activity1.this, Activity2.class);
Bundle mBundle = new Bundle();
mBundle.putSerializable(SER_KEY,mPerson);
mIntent.putExtras(mBundle);
startActivity(mIntent);
And get this object from activity 2 in on create methode.
Person mPerson = (Person)getIntent().getSerializableExtra(SER_KEY);
and SER_KEY will be same.
for more detail please go to this link:
http://www.easyinfogeek.com/2014/01/android-tutorial-two-methods-of-passing.html
I hope it will work for you.
You can make use of bundle for passing values from one screen to other
Passing a Bundle on startActivity()?

Send String from an Activity to a Fragment of another Activity

I have two Activities (A and B) and a Fragment F
The Fragment F is contained in the Activity B
I'd like to send Strings from Activity A to Fragment F
How can do that?
Thanks!
It is Almost same as you would exchange data between activities. you should just use getActivity() in the beginning in order to access in fragments.
check below code:
In Activity A:
Intent intent = new Intent(this,ActivityB.class);
intent.putExtra("data",data); //data is a string variable holding some value.
startActivity(intent);
In fragment F of Activity B
String data = getActivity().getIntent().getStringExtra("data");
First, you'll actually send that string to your activity B. For example:
Intent intent = new Intent(this, YourActivityClass.class);
intent.putExtra("myString", "this is your string");
startActivity(intent);
then later read that string from your activity B and inject into your fragment before executing the fragment-transaction. For example:
Bundle args = new Bundle();
args.putString("myString", getIntent().getExtras().getString("myString"))
yourFragment.setArguments(args);
Later, use getArguments() in your fragment to retrieve that bundle.
Or alternatively, use the following in your fragment to directly access the activity intent and fetch your required value:
String str = getActivity().getIntent().getStringExtra("myString");
For more info, read this.
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);

Categories

Resources