Pass parameters without open activity - android

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

Related

How to send data from Activity to Fragment?(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

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

Passing data via intent in android

I have 5 activities, say activity A,B,C,D and E.
Each activity has two buttons yes & no,buttons have the data which I want to pass to activity E only.
I need to do following things:
--> When user press yes/no button of A_activity, the user move to B_activity but data passed to activity E via intent.
Similarly at activity B user press yes/no button, user will move to activity C but data passed to activity E and so on.
I have done lot of search but couldn't find solution is there any way to do this.
Use SharedPreferences class to pass the data:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "Value");
editor.commit();
Then in the Activity E:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String value = sharedPref.getString("key", defaultValue);
Hope this helps.
You can indeed pass data back through an intent to an Activity's onActivityResult()
Activity E starting Activity A
final int RESULT_FOR_CLASS_DATA = 12; // pick a number to use
String returnedData;
Intent intent = new Intent(this, ActivityA.class);
startActivityForResult(intent, RESULT_FOR_CLASS_DATA);
Example in A (started from E)
Intent data = new Intent();
data.putExtra("ReturnData", dataToReturn);
setResult(RESULT_OK, data);
finish(); // returning to Activity E
Example in onActivityResult() of E
if (requestCode == RESULT_FOR_CLASS_DATA) {
returnedData = data.getStringExtra("ReturnData"));
}
There's a wide variety of ways to accomplish moving data around though so this is just one example.
To recommend an alternative, use Handler instead of this. Supposed that since the return Activity is paused, handler might require setting data in a separate class or global static variables, etc. and retrieved on Activity restart or something. So its possible to do with little to no code duplication in any class. Just retrieve and use. Whereas Intent requires code duplication in every class. It would also easily allow going from any Activity to any Activity like A->B->E->C instead of requiring E->A->E->B. Just something to think about.

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.

Crash while sending data between Activities

So, I'm basically fooling around with some kind of login form, and trying to say a customized hello with the user name on the upcoming activity. The code compiles with no problem but the app crashes as soon as I click on the login button, the login worked successfully before I tried to implement the customized hello, so the problem has to be somewhere in the following code.
Here is where I call the activity:
Intent k = new Intent(this, MainActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
//login is the EditText variable name for the login text field
startActivity(k);
Here is where I retrieve the extra data and try to use it as described:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ProfileActivity extends Activity {
TextView helloString;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Bundle extras = getIntent().getExtras();
//Getting the hello text string
helloString = (TextView)findViewById(R.id.textHello);
String loginName = extras.getString("loginName");
helloString.setText("¡Hello, " + loginName + "!");
}
}
It somehow avoids the crash if I put in comment these two lines:
String loginName = extras.getString("loginName");
helloString.setText("¡Hello, " + loginName + "!");
Still, I can't be sure if the problem is really there or not, I thought it could have something to do with the type of data sent from the first activity not matching with the type being retrieved on the second, but still got no clue after trying some stuff around that.
Thanks in advance.
Editing:
I actually found out that I may have something to do with the fact that I am calling to mainActivity.class while the text is being shown in an activity called profileActivity.class, the problem is, profileActivity is being shown as a tab inside the mainActivity so I don't really know how should I approach that.
Editing 2:
So I solved it finally myself, for anyone interested I just sent the data to the MainActivity.class
Intent k = new Intent(this, MainActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
startActivity(k);
And, inside the Main Activity, when calling the ProfileActivity to set it up as a tab:
//Profile tab
intent = new Intent(this, ProfileActivity.class);
Bundle extras = getIntent().getExtras();
intent.putExtra("loginName", extras.getString("loginName"));
spec = mTabHost.newTabSpec("home")
.setIndicator("Home", res.getDrawable(R.drawable.profile_icon))
.setContent(intent);
mTabHost.addTab(spec);
Problem solved, thanks for the help everyone anyways.
Your intent is refering to MainACtivity.class and you are trying to fetch the extras in ProfileActivity. Try changing the MainActivity.class to ProfileActivity.class if that is what your flow is.Please cross check your activities flow.
Hope it helps.
Intent k = new Intent(this, ProfileActivity.class);
//Sends login name to activity k
k.putExtra("loginName", login.getText().toString());
//login is the EditText variable name for the login text field
startActivity(k);
Since you stated that you want the data sent to ProfileActivity but need to open MainActivity, you can follow one of the 4 approaches.
NOTE: you should be checking when you use getExtra, that the returned value isn't null, and deal with it accordingly.
send the data first to the MainActivity, and then when you launch ProfileActivity from MainActivity, send the data that was previously passed in.
Put the data in a public static field in ProfileActivity. Public static variables can lead to issues, so I would recommend against this.
Save the data to a sharedPreferences file and read it when you need it in ProfileActivity.
SubClass Application, and you can set / access many variables there. The below was copied from Are static fields in Activity classes guaranteed to outlive a create/destroy cycle?:
public class MyApplication extends Application{
private String thing = null;
public String getThing(){
return thing;
}
public void setThing( String thing ){
this.thing = thing;
}
}
public class MyActivity extends Activity {
private MyApplication app;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = ((MyApplication)getApplication());
String thing = app.getThing();
}
}
On MainActivity:
String user = this.getIntent().getStringExtra("loginName");
And when you create the tabhost on MainActivity pass the string the same way:
Intent intent = new Intent().setClass(this, ProfileActivity.class);
intent.putExtra("loginName", user);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = mTabHost.newTabSpec("profile").setIndicator("Profile").setContent(intent);
mTabHost.addTab(spec);
Something like this.
But if you need the user name across the entire application use a Helper Class to store the user name.

Categories

Resources