How to send data from Activity to Fragment?(Android) - android

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

Related

text clicked on first and second activity, should be visible to third

I am trying to find best way to show textview we have clicked on first and second activity, in third one.
Like i have three activities AccountFrom, AccountTo and transferDetails.
I want to know that on what accounttype user has clicked so that i can show in third activity.
1. on AccountFrom Activity
Intent intent = new Intent(AccountFrom.this, AccountTo.class);
**intent.putExtra("accounttype","accountTypeVariable");**
startActivity(intent);
2. Receive intent on AccountTo Activity
Intent intent = getIntent();
if (intent != null)
{
String accountTypeValue = intent.getStringExtra("accounttype")
}
Consider using a view model.
You create the view model in the first Activity and then it is accessible in all activities that you open from it.
Here is simple workflow:
Create view model class that extends ViewModel and has the values you need to keep around
public class MyViewModel extends ViewModel {
private String value1 = "";
private boolean isValue2 = false;
// ...
}
In the first activity create your view model class member
private MyViewModel viewModel;
In the OnCreate you can get the view model like this:
viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
You can do it also in the activities that are launched from this activity - they will share the same view model object. You can set the values in the activities and access them in other activities from the same 'launch-chain'.
When the initial activity (your first one) gets destroyed then the view model also does.
PS. using view model is also good when you need to handle screen orientation changes.
Save the text from TextView on sharedPreferences when it is clicked. Then read it on your third activity.
Call this on your first activity where the user chooses the account type.
void saveText(String stringFromTextView)
{
SharedPreferences sharedpreferences = getSharedPreferences("account", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("account_type", stringFromTextView);
editor.commit();
}
And on your third activity, call this on onCreate() to get the account type.
String getAccountType()
{
SharedPreferences sharedpreferences = this.getSharedPreferences("account", Context.MODE_PRIVATE);
String accountType = sharedpreferences.getString("account_type", null);
return accountType;
}

Save EditText and TextView data and display it in another activity

I'm developing an app which adds two numbers. The user provides the numbers via EditText and the result is displayed via TextView. What I want to do is to save the values of the numbers entered by the user and the result via button (to see them whenever the user wants) and display them in the layout of another activity (whithout EditText's). Remark that the user would be able to see the results saved whenever he/she wants.
Hope you can help me. Thank you so much.
There is multiple ways to achieve that :
Method 1:
Use static class setter and getter method:
create static class and set values from first activity and get value from second activity
Method 2:
Post your values through the intent
Method 3:
Use database to store data from one activity and get data from other activity
Method 4:
Use Shared preference
From Your question what i understand::
Your first editText1 has value1
Your second editText2 has value2
textView1 has the result of value1 and value2
Solution:: Get the values from the views and use intents to pass the data between activities
Code::
In your current Activity, create a new Intent: - OnCreate()
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("editText1",editText1.getText());
i.putExtra("editText2",editText2.getText());
i.putExtra("textView1",textView1.getText());
startActivity(i);
Then in the new Activity, retrieve those values: - OnCreate()
Bundle extras = getIntent().getExtras();
if (extras != null) {
String editText1= extras.getString("editText1");
String editText2= extras.getString("editText2");
String textView1= extras.getString("textView1");
}
Use the variables editText1,editText2 and textView1 in second activity to set the values to any views as u wish
HOPE THAT HELPS, let me know if you face any problems in debugging
make use of SharedPreferences like this:
SharedPreferences sp= getSharedPreferences("ttt", 0);
SharedPreferences.Editor editor = sp.edit();
String etValue=(EditText)findViewById(R.id.yourEditTextId).getText().toString();
String tvValue=(TextView)findViewById(R.id.yourTextView).getText().toString();
editor.putString("etValue", etValue);
editor.putString("tvValue", tvValue);
editor.commit();
// in anywhere user wants
SharedPreferences settings = getSharedPreferences("ttt", 0);
String yourEditTextValue=settings.getString("etValie", "");
String yourTextViewValue=settings.getString("tvValie", "");

Pass parameters without open activity

I am novice programming on Android. I have one question, I have 2 activities. Firs I pass a parameter from the Activity A to the B like this:
Intent intent = new Intent(getBaseContext(), ActivityB.class);
intent.putExtra("ALMACEN_ANTES", almacen.getText().toString());
startActivity(intent);
And now in the activity B y get the extras. Later since the Activity B, I pass parameters to the A too.
My question is, is it possible to pass parameters to another activity without doing
Intent intent = new Intent(getBaseContext(), ActivityB.class) because I donĀ“t want to open 2 times the same activity.
Thank you!
Yes . You can save the value using SharedPreferences
It will be stored in an internal xml file and you can save it and retrive whenever you want. It need not start the activity when value passing.
An example shows below
SharedPreferences sharedpreferences;
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.commit;
you can retrive this value from the activity where you need to access these values. It can be done by:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name=sharedpreferences.getString("Name","");
String ph=sharedpreferences.getString("Phone","");
You want to update a value in the activity A , you mean? because if you don't open it why sending a value to it ?
you can share data between two activities by other ways. In your case the best one would be a Singleton class:
you create a class which is inheriting from Application and containing your data, and from every activity you can update you data or get it...
Your singleton class:
import android.app.Application;
public class MyApplication extends Application {
private String data;
public String getData() {return data;}
public void setData(String data) {this.data = data;}
}
From activity B , you can set your data:
MyApplication app = (MyApplication) getApplicationContext();
app.setData(someData);
And teh Ativity A can have them like this:
MyApplication app = (MyApplication) getApplicationContext();
String data = app.getData();
See this answer

How to pass data between activities

My question is how to pass data like String between two activities. Normally I would do this:
Intent i = new Intent(thisclass.this,NextClass.class);
Bundle b = new Bundle();
i.putExtras(b);
b.putString("Name",Name);
StartActivity(i);
But this would make my Activity close and will open the next Activity, no? Is there any way that I can only pass data without opening the other activity?
I think you are looking for something with the SharedPreference see the documentation : SharedPreference
if it is what are looking for.
Try this:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna save your data:
String data = "yourData"
pref.edit().putString("myData", data).commit();
And the other Activity:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna take your data:
String dataFromFristActivity = pref.getString("myData", null);
Your calling activity does not close but is paused.
I am with #Egor on this. The called activity does not yet exist. Unless u are trying to send data between activities in two different apps. That is a whole different can of worms.

How to ensure the data remain in an activity after clicking a button to another page then return to current page?

I've an application where a user creates events. The user need to retrieve a certain name from an activity which is a ListView of names list.
I'm having an issue with making sure that a name should remain in an activity after clicking a date button which links to another activity(calendar activity), then return back to the current activity.
My codes of the 3 pages:
Create_Events.java - codes for getting a certain name from ListView activity and the btnDate onClickListener which links to the another activity(calendar activity)
Bundle bundle = getIntent().getExtras();
if(bundle != null)
{
String date = bundle.getString("date");
txtDate.setText(date);
}
Bundle b = getIntent().getExtras();
if(b != null)
{
String name = bundle.getString("name");
txtName.setText("Create an event for:" +name);
}
buttonDate = (Button) findViewById(R.id.btnDate);
buttonDate.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent calIntent = new Intent(Create_Events.this, Calendar_Event.class);
startActivity(calIntent);
}
});
ContactsList.java -- the ListView of the names which is passed to the Create_Events page.
Cursor cursor = null;
cursor = (Cursor) l.getItemAtPosition(position);
Intent intent = new Intent(ContactsList.this, Create_Events.class);
intent.putExtra("name", cursor.getString(cursor.getColumnIndex(buddyDB.KEY_NAME)));
startActivity(intent);
I need help with this. Any help provided will be greatly appreciated. Thanks in advance! =)
you can get this behavior by saving you current screen state,
you can either use shared preferences or other ways (xml,data base, ..),
this way before you leave the activity (onPause) you save any information you need..
and on (onResume) if the information exists (its not the first time the activity loads),
collect the data and put it on screen..
if this is too much for you and you only need the name string to save,
try doing this :
How to declare global variables in Android?
hope it helps...
okay what i understand from your question is you want to retain your data on screen after coming back from another activity.
like Activity A--> Activity B--> Activity A
so, set in menifest file for activity A
android:launchmode="singletop"
and, when you are coming back from Activity B to Activity A
set
Intent intent=new Intent(ActivtyB.this, ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
you can use SharedPreferences to store the name while use bundle to store the date.
From contactLists.java add these codes
private void SavePreferences(String key, String value)
{
SharedPreferences sharedPref = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences()
{
SharedPreferences sharedPref = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String name = sharedPref.getString("name", "");
}
Then set the name to the textView which will show on the listView. And then load the preference in the create_events page and the name will be shown even when you go to another activity.
Do inform me if you still have any questions. (:

Categories

Resources