I want to transfer data from an activity with edit texts to a fragment class with a list to only display the edit_name box. I want to be able to click a button in the activity class and for it to save all of the information and display only the edit_name box. Anyone have any idea how to do this?
Basically you could use Intents to do this, here is an example :
https://stackoverflow.com/a/12739968/5552022
Otherwise, you could use a library like EventBus which handles the process pretty efficiently :
https://github.com/greenrobot/EventBus
// Create a new Intent object as container for the result
final Intent data = new Intent();
// Add the required data to be returned to the MainActivity
data.putExtra(EXTRA_DATA, "Some interesting data!");
// Set the resultCode as Activity.RESULT_OK to
// indicate a success and attach the Intent
// which contains our result data
setResult(Activity.RESULT_OK, data);
// With finish() we close the DetailActivity to
// return back to MainActivity
finish();
You can tranfer your data via bundle:
From your activity use below code to addd data in bundle:
Bundle bundle = new Bundle();
bundle.putString("key", "your string");
// set Fragmentclass data as fragment arguments
YourFragment fobj = new YourFragment();
fobj.setArguments(bundle);
and in Fragment you can get your data:
String strtext = getArguments().getString("key");
Related
I want to make use of some TextViews(cityField, updatedField) I have in my activity inside my fragment.
I know it would have been easier to make use of them in the activity instead, but the problem is that I have to join in with some codes on Fragment due to getting some JSON data
Already I've gotten the id for the codes on activity
cityField = findViewById(R.id.textView4);
updatedField = findViewById(R.id.textView9);
Now I want to make use of them in my fragment
So the question is - is it possible? if it's possible, how?
Already, I checked some answers on this site - Send data from activity to fragment in Android
How to pass data from Activity to Fragment using bundle
but they directly didn't solve my problem.
You should create a SharedViewModel and let the Activity set values of variables like cityField and updateField while the Fragment Observe the changes done to them, basically the Activity will Set and Fragment will Get
for more information about ViewModels check this:
https://developer.android.com/topic/libraries/architecture/viewmodel
You can access these instances from your fragment like this:
String cityFieldFragment = (activity as YourActivity).cityField;
String updatedFieldFragment = (activity as YourActivity).updatedField;
If I understood this right, the fragment lives in your activity, so you are able to access the data from it, just make sure that the instances are public.
if the fragment is not already created you can make use of the constructor of the fragment and pass arguments to it.
If the fragment is already created, create a method inside the fragment and invoke it in the activity.
Let's say you want to pass it from an activity to another activity that contains fragments. First, you need to pass the data like so :
Intent intent = new Intent();
intent.setClass(FirstActivity.this, SecondActivity.class);
intent.putExtra("name", username);
intent.putExtra("pass", password);
startActivity(intent);
In this case, the fragment is inside the SecondActivity.java but to receive the data, we need code inside the Fragment.java instead of the SecondActivity.java.
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
getUsername = extras.getString("name");
getPassword = extras.getString("pass");
}
I haven't tried to pass the data directly to the fragment, but you can try with the same code. All you need to do is changing the intent instead of intent.setClass(FirstActivity.this, SecondActivity.class); to intent.setClass(FirstActivity.this, Fragment.class);.
Have you tried with SharedPreferences?
in you MainActivity
// create sharedPrefences file with the name "info"
SharedPreferences sp = this.getSharedPreferences("info",0);
// here the name and default value
sp.getString("name", "default value");
// create editor
SharedPreferences.Editor editor = sp.edit();
// enter a new value
editor.putString("name", "new value");
// save changes
editor.apply();
in your Fragment
SharedPreferences sp = getActivity().getSharedPreferences("info",0);
String str = sp.getString("name", "default value"); //will get you the new value you entered
How do you pass LiveData with intent to another Activity?
I'm trying to pass the LiveData object into a new Activity that uses ViewPager 2 to display one object at a time.
Here is Live data in the ViewModel
private LiveData<List<WrestlersEntity>> mWrestlersList;
public LiveData<List<WrestlersEntity>> getWrestlersList() {
return mWrestlersList;
}
Fragment passing live data.
adapter.setOnItemClickListener(wrestler -> {
Bundle bundle = new Bundle();
bundle.putSerializable("Value", (Serializable)mViewModel.getWrestlersList());
Intent addEditIntent = new Intent(getActivity(), AddEditWrestlerActivity.class);
addEditIntent.putExtras(bundle);
startActivityForResult(addEditIntent);
Pager Activity
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
List<WrestlersEntity> wrestler (List<WrestlersEntity>)bundle.getSerializable("Value");
I get the following error.
java.lang.ClassCastException: androidx.room.RoomTrackingLiveData cannot be cast to java.io.Serializable
If you can't cast live data as Serializable what are my other options to pass a LiveData> to a new activity.
here is a link to the git if you want to look at the full code.
https://github.com/Shawn-Nichol/Wrestlers
Your getWrestlersList() method returns a LiveData wrapping your List<WrestlersEntity>. What you want to pass to your Bundle is the List<WrestlersEntity> directly, but wrapped in a Serialized implementation of List. That's why the code below wraps the value of your LiveData in an ArrayList.
So, you can do this instead:
bundle.putSerializable("Value", new ArrayList<>(mViewModel.getWrestlersList().getValue()));
And this to read it back from the Bundle:
List<WrestlersEntity> wrestlers = (List<WrestlersEntity>)bundle.getSerializable("Value");
In my FirstActivity, user will log in. If the user exists in the database, it is loaded and should be "passed" to the SecondActivityFragment which is within the SecondActivity. The need is to check whether the user is with incomplete register, if so, the toolbar will display a warning menu item telling it to complete the registration.
┌FirstActivity
├─SecondActivity
└──SecondActivityFragment
Every tutorial that I see showing how pass data through Activity and Fragment talking about replace fragments and so on, I think that's not my case.
I created newInstance() on my SecondActivityFragment but I'm kinda lost.
public static SecondActivityFragment newInstance(User user) {
Bundle args = new Bundle();
args.putSerializable("user", user);
SecondActivityFragment fragment = new SecondActivityFragment();
fragment.setArguments(args);
return fragment;
}
And when user clicks in login button
if (userExists()) {
userManager = new UserManager();
User user = userManager.getByEmailPwd(editEmail.getText().toString(), editPwd.getText().toString());
Intent secondActivity = new Intent(getContext(), SecondActivity.class);
SecondActivityFragment.newInstance(user);
startActivity(secondActivity);
}
Try to put user into your secondActivity intent.
Then in the SecondActivity's onCreate method get the user class using getIntent().getSerializable() and create an instance of SecondActivityFragment.
Calling
SecondActivityFragment.newInstance(user);
that way, will not cause any effects in what will got presented.
If you want to present the fragment in the context of Second activity, consider passing the data that the fragment need to know to the Second activity - it should be sth like:
secondActivity.putSerializable("user", user)
Then in SecondActivity's onCreate, or in other method, you have to replace fragment being displayed, for your SecondActivityFragment instance:
User user = null;
final Bundle args = getIntent().getExtras();
if(args.getSerializable("user") instanceof User){
user = (User)args.getSerializable("user");
}
if(user != null){
Fragment secondActivityFragment = SecondActivityFragment.newInstance(user);
FragmentMenager fragmentMenager = getFragmentMenager();
FragmentTransaction fragmentTransaction = fragmentMenager.beginTransaction();
fragmentTransaction.replace(R.id.frame_for_your_fragment, secondActivityFragment);
}
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()?
I have two activities in my tab-bar application. One activity (activity1) is a normal activity and the other (activity2) is a ListActivity. In activity1, there is a button which stores every time I tap on the button data (date, value1,value2..) in an array of objects. I read that this is possible with Intents. But I dont want to start activity2 everytime I tap on the button.
How can I pass the array to activity2, so I can display them later after I tapped more than once on the button in my ListView?
EDIT :
Here is my code. But I get a NullPointerException, so it doesn't store correctly. My Object hat Serializable implemented.
Activity1:
Intent datenIntent = new Intent(this, LoggerActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("Daten",aDatensatz);
datenIntent.putExtras(bundle);
Activity2:
Bundle bundleData = this.getIntent().getExtras();
Datensatz[] aDatensatz = (Datensatz[]) bundleData.getSerializable("Daten");
You can pass an array in one shot from one activity to another in the following way :
Bundle myBundle = new Bundle();
b.putStringArray(key, array);
Intent i = new Intent(context, Class);
i.putExtras(myBundle);
And for receiveing
You can retrieve the value in another activity in following way:
Bundle b = this.getIntent().getExtras();
String[] array = b.getStringArray(key);
Hope this helps.