Send String from an Activity to a Fragment of another Activity - android

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);

Related

Transferring Data from EditText from one Activity to EditText of another

When Transferring data from one activity to another, can you transfer from one EditText to another EditText of the other Activity
I'm trying to transfer data from EditText of one Activity to EditText of another Activity.
1 ) Way
First activity
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“data”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Sceond Activity where you get
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString(“data”);
2)Way
public static AutoCompleteTextView textView;
you can access textview with
SceondActivity.textview;
3 Way
Store value in Preference or database
You can send the content of 1st EditText as an intent extra to another activity. In the destination Activity, call getIntent() to extract the intent extras and then you can call setText() on that Activity's EditText
Activity A:
String data=myEditText.getText().toString();
Intent i=new Intent(ActivityA.this,ActivityB.class); //Create Intent to call ActivityB
i.putExtra("editTextKey",data);
startActivity(i);
Activity B:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b_layout);
EditText newEditText=findViewById(R.id.new_edittext_id); //Get the reference to your edittext
String receivedData = getIntent().getStringExtra("editTextKey");
newEditText.setText(receivedData); //Set the data to new editteext
...
}
Ref : What's the best way to share data between activities?
You can achive this by
Send data inside intent
Static fields
HashMap of WeakReferences
Persist objects (sqlite, share preferences, file, etc.)
TL;DR: there are two ways of sharing data: passing data in the intent's extras or saving it somewhere else. If data is primitives, Strings or user-defined objects: send it as part of the intent extras (user-defined objects must implement Parcelable). If passing complex objects save an instance in a singleton somewhere else and access them from the launched activity.
Some examples of how and why to implement each approach:
Send data inside intents
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("some_key", value);
startActivity(intent);
On the second activity:
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
Intents are used for communication between Activities. You should get the text from EditText using EditText.getText().toString() and create an Intent to wrap up the value to be passed eg;
Intent in = new Intent(FirstActivity.this, TargetActivity.class).putExtra("STRING IDENTIFIER","string value from edittext");
You can retrieve this value and set it in EditText
Option B use shared preferences like this class I use:
class QueryPreferences
{
private static final String TEXT_ID = "2";
static void setPreferences(String text, Context context)
{
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(TEXT_ID,text)
.apply();
}
static String getPreferences(Context context)
{
return PreferenceManager.getDefaultSharedPreferences(context).getString(TEXT_ID,"");
}
}

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

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 :)

Passing a reference of an object to activity

I have a reference to an anonymous class object that I want to pass to an activity. It is a kind of reference to a callback fn which gets called based on an action on activity i.e. click of button. But, I dont know a way to do so as activities can not be instantiated directly (done only through startActivity) and using intents will pass my object by value not by reference. So, I need tips on a good solution. I want to avoid statics.
Short Answer: No You cannot pass objects as references to activities.
Try this
CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);
Afterwards to call
Bundle b = this.getIntent().getExtras();
if (b != null)
mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);
Here is the answer :
Create a public static method in the Activity to which you want to pass the reference of an object.
public static void openActivity(Activity activity, Class object){
YourNextActivity.object = object;
Intent intent = new Intent(activity, YourNextActivity.class);
activity.startActivity(intent);
}
Call this method from current Activity :
YourNextActivity.openActivity(this, classObject);

How to send text from activity to fragment of other activity

I've two activity "Name_Status" and "Main_activity".
In Main_activity , i've fragments . i wanna send a string value from Name_Status activity to one of Main_activity fragment.
Below is the method of Name_Status activity:
#Override
public void onClick(View v) {
if (v.getId() == R.id.ok_change_name)
{
name = name_change.getText().toString();
System.out.println(name);
Log.d("entered", "entred");
MainActivity obj=new MainActivity();
Log.d("obj created", "obj created");
obj.changeMainName(name);
Log.d("obj.changename", "obj.changename");
}
}
By using this method i'm first sending data to the Main_activity and from there sending data to fragment as below.
Below is the code of Main_activity:
public void changeMainName(String s) {
FragActivity1 obj = (FragActivity1) getSupportFragmentManager().findFragmentById(R.id.person_profile); obj.changeName(s);
}
Now from here I'm sending string value to fragment class and there I'm only setting the string to the textview like below:
public void changeName(String s)
{
Log.d("changename entry" ,"changename netry");
System.out.println(s);
System.out.println(name_field.getText().toString());
name_field.setText(s);
System.out.println(name_field.getText());
}
I'm getting
NullPointerException at obj.changeMainName(name);
You gonna have to do some relay. For instance you have activity A which has no Fragment and Activity B which has a fragment. On Android framework you can first pass data to From Activity A to B and From Activity B you can pass data to its Fragment following the view Hierarchy.
In Activity A. do the following
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("key", "value");
startActivity(intent);
Now inside Activity B, get data from activity A
String stringValue= getIntent().getStringExtra("key");
Then pass that data your Fragment as an argument before to start Frag
Bundle bundle = new Bundle();
bundle.putString("key", stringValue);
ActivityBFrag fragment = new ActivityBFrag();
fragment.setArguments(bundle);
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(container, fragment, tag);
transaction.addToBackStack(tag);
transaction.commit();
Then inside your Fragment class. get data like below whenever you wanna access your data, can be inside onCreate, OnActivityCreated etc.
public void getArguments(){
Bundle bundle = getArguments();
if(bundle != null){
String stringValue = bundle.get("key");
}
}
Send data to second activity by Intent bundle. Then get the data in second activity by getIntent().getExtras() and then pass the data to fragment.

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()?

Categories

Resources