I just figured out how to use intent to pass variables to other activity ,but I found out that it has a limit , it can only pass one variable to one activity .
I want to know how to share the variable in multiple activity like I have this variable in activity 1 and I want to use it in activity 2 and activity 3.
this is my activity 1 , the variable I want to use in other activity is this
(double ans=(90+4.8*nh+13.4*nw-5.7*na);)
I figured out how to pass it to activity 2 but I can't pass it to activity 3. Is there an easy way to pass the variable in multiple activity , because I'm kinda new to Android and OOP there's a lot of stuff I don't really get just from searching. Thank you so much!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_male);
age =(TextView)findViewById(R.id.age);
height=(TextView)findViewById(R.id.heigth);
weight =(TextView)findViewById(R.id.weigth);
result =(TextView)findViewById(R.id.result);
eage=(EditText)findViewById(R.id.eage);
eheight=(EditText)findViewById(R.id.eheight);
eweight=(EditText)findViewById(R.id.eweight);
calculate=(Button)findViewById(R.id.calculate);
back =(Button)findViewById(R.id.back);
next =(Button)findViewById(R.id.next);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double na=Double.parseDouble(eage.getText().toString());
double nh=Double.parseDouble(eheight.getText().toString());
double nw=Double.parseDouble(eweight.getText().toString());
double ans=(90+4.8*nh+13.4*nw-5.7*na);
result.setText("Your BMR is "+ans);
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(MALE.this,MainActivity.class);
startActivity(i);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MALE.this, MALERUN.class);
double na=Double.parseDouble(eage.getText().toString());
double nh=Double.parseDouble(eheight.getText().toString());
double nw=Double.parseDouble(eweight.getText().toString());
double ans=(90+4.8*nh+13.4*nw-5.7*na);
result.setText("Your BMR is "+ans);
i.putExtra("answer",ans);
i.putExtra("age",na);
i.putExtra("height",nh);
i.putExtra("weight",nw);
startActivity(i);
}
});
}
Use SingleTon Pattern.
public class SingletonClass {
private double yourValue;
private static SingletonClass sSoleInstance;
private SingletonClass() {
} // private constructor.
public static SingletonClass getInstance() {
if (sSoleInstance == null) {
sSoleInstance = new SingletonClass();
}
return sSoleInstance;
}
public void setValue(double val) {
yourValue = val;
}
public double getValue() {
return yourValue;
}
}
Set Variable from Activity1
SingletonClass.getInstance().setValue(yourValue);
Now you can access this value across application.
SingletonClass.getInstance().getValue();
For more details click here
Using SharedPreferences you can get it.here is examples
next.setOnClickListener{
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("answer",ans);
editor.putString("age",""+na);
editor.putString("height",""+nh);
editor.putString("weight",""+nw);
editor.commit();
Intent i=new Intent(MALE.this,MainActivity.class);
startActivity(i);
}
Any Another Activity you can get it below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);
String answer = sharedPref.getString("answer",null);
String age = sharedPref.getString("age",null);
Log.e("resultsss",""+answer + " age : "+age);
}
Solution 2:
Either you have to use Sqlite database
suggestion: if you have very less fields better to use
SharedPreferences if you have little hug data better go with Sqlite
database
You can declare a varible :
public class MainActivity extends AppCompatActivity {
// Like below
public static double ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
}
And call it from everywhere like this:
MainActivity.ans;
You can declare a different variable anytime you want and it will change in every Activity.
just do this :
MainActivity.ans = 123.123;
Related
I have Act_01 (where I put value) and Act_02 (where I get value) but have declared these methods in a Extras class, getting value from Act_02 returns null value:
Act_01: (Where I want to pass the value Name to Act_02)
public class Act_01 extends Activity {
Extras cc_Extras;
Button btn1;
Intent intent;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
cc_Extras = new Extras();
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cc_Extras.putExtras();
startActivity(intent);
}
});
}
}
Act_02: (Where I want ot receive value Name from Act_01 but the app crashes with null value)
public class Act_02 extends Activity {
Extras cc_Extras;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
cc_Extras = new Extras();
if(getIntent() != null && getIntent().getExtras() != null)
{
cc_Extras.getExtras();
}
Toast.makeText(getApplicationContext(), "Name: "+str_Name, Toast.LENGTH_SHORT).show();
}
}
Extras: (Where I define the methods to put and get Extras)
public class Extras extends Activity {
String str_Name;
Intent intent;
public void putExtras() {
// TODO Auto-generated method stub
intent.putExtra("KEY_Name", str_Name);
}
public void getExtras() {
// TODO Auto-generated method stub
str_Name = getIntent().getExtras().getString("KEY_Name");
}
}
EDIT: I do not want to pass and get data directly between activities, I want to use the 3rd class (Extras.java) because I have too many activities having too many values between each other and want to sort of define them globally in Extras so that all my other activities can just call one method instead of getting and putting too many values in my activities.
Your app crashes not with a null value, but a null pointer reference because you created a new Activity manually
cc_Extras = new Extras();
Then called a lifecycle method on it
cc_Extras.getExtras()
Which calls getIntent(), but the Intent was never setup by the Android framework, and cc_Extras.getExtras() wouldn't have any of the data you wanted anyway in the second Activity because it was just created there, not from the first Activity.
Briefly, you should never make a new Activity, and your Extras class does not need to be an Activity in the first place (nor does it provide much benefit).
Just use the Intent object provided by the first Activity to start the second Activity, and get extras like normal. Don't overcomplicate your code. Regarding the title of the question, Intent and Bundle are already "another class" designed by Android for you to transfer data.
On both activities you are creating a new instances of Extras class means they dont hold the same value you can do this to transfer data from A to B
public class Act_01 extends Activity {
Button btn1;
Intent intent;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intent = new Intent(Act_01.this, Act_02.class);
intent.putExtra("data", str_Name)
startActivity(intent);
}
});
}
}
And receieve data like this
public class Act_02 extends Activity {
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
// cc_Extras = new Extras();
if(getIntent() != null)
{
if (getIntent().getStringExtra("data") != null) {
Toast.makeText(Act_02.this, "Name: "+getIntent.getStringExtra("data"), Toast.LENGTH_SHORT).show();
}
}
}
}
Also you should consider using Activity Context instead of the application context
Ok! so here are the few things I might wanna suggest you to correct.
Changes needs to be done in the code.
You are not assigning anything to "intent" object , and you have passed a intent without assigning anything to it.
Your instance cc_Extra isn't doing anything in the activity1. You might wanna pass the "intent" object in your constructor of class like cc_Extras= new Extras(intent); and in the Extras class do the following- Intent intent;
Extras(Intent i)
{
this.intent=i;
}
In the activity2 you are creating the new Instance of Extras(). So according to your code it is going to be NULL by default. If you have done the changes from the previous step, you can create new instance by doing cc_Extras(getIntent());
Corrections in the code
1) In Extras class getExtras() method instead of str=getIntent() use str=intent.getExtras.getString().
2) In the activity2 you are not assigning anything to your String str_Name, so you need to return the string you got in getExtras() method. You can do it by changing the return type to String. Below is the sample code.
public String getExtras()
{
str_Name=intent.getExtras().getString("KEY_Name");
//OR
//str_Name=intent.getStringExtra("KEY_Name");
return str_Name;
}
3) By the doing this you need to catch this string in the activity2 by doing `
if(getIntent() != null && getIntent().getExtras() != null)
{
str_Name=cc_Extras.getExtras();
}`
4) Another thing is you must create intent like this-
Intent intent=new Intent(currentActivityName.this,anotherActivity2.class);
//then use the intent object
EDIT- Your code must look like this in the end...
Act1
public class Act_01 extends Activity {
Extras cc_Extras=null;
Button btn1;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//changes to do
Intent intent= new Intent(Act01.this,Act02.class);
cc_Extras= new Extras(intent);
cc_Extras.putExtras(str_Name);
//end
startActivity(intent);
}
});
}
}
Act02
public class Act_02 extends Activity {
Extras cc_Extras;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
cc_Extras = new Extras(getIntent());
if(getIntent() != null && getIntent().getExtras() != null)
{
str_Name=cc_Extras.getExtras();
}
Toast.makeText(getApplicationContext(), "Name: "+str_Name, Toast.LENGTH_SHORT).show();
}
}
Extras class
public class Extras { //remove "extends Activity" because it is a class not a activity
String str_Name;
Intent intent;
Extras(Intent i)
{
this.intent=i;
}
public void putExtras(String str) {
// TODO Auto-generated method stub
str_Name=str;
intent.putExtra("KEY_Name", str_Name);
}
public String getExtras() {
// TODO Auto-generated method stub
str_Name = intent.getExtras().getString("KEY_Name");
return str_Name;
}
}
Above code will work just on String. You can extend the functionality if you want.
I hope this must work to get your code working!
I have three Activities. MainActivity,ActivityB and ActivityC. In activity A and B there are two buttons source and destination in both activities. in Activity C there is a list of data. when button is clicked (either Source or destination) from activity A and B. both Activities are calling Activity C
code for Activity A is following
public class MainActivity extends Activity {
TextView source,destination;
Button sendSource,sendDestination,btnTob;
String src,des,activity,checksrc,checkdes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
source=(TextView)findViewById(R.id.tv_rcvDataA);
destination=(TextView)findViewById(R.id.tv_rcvDataAa);
sendSource=(Button)findViewById(R.id.btn_sendA);
sendDestination=(Button)findViewById(R.id.btn_sendAa);
btnTob=(Button)findViewById(R.id.btn_toB);
sendSource.setText("source");
sendDestination.setText("destination");
src=sendSource.getText().toString();
des=sendDestination.getText().toString();
activity=getClass().getSimpleName();
sendSource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent send= new Intent(MainActivity.this,ActivityC.class);
send.putExtra("source",src);
send.putExtra("Activity",activity);
startActivity(send);
}
});
sendDestination.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent senda= new Intent(MainActivity.this,ActivityC.class);
senda.putExtra("destination",des);
senda.putExtra("Activity",activity);
startActivity(senda);
}
});
btnTob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent movetoB= new Intent(MainActivity.this,ActivityB.class);
startActivity(movetoB);
finish();
}
}); }}
and code for Activity B is
public class ActivityB extends Activity {
TextView sourceB,destinationB;
Button sendSourceB,sendDestinationB;
String src,des,activity,checksrc,checkdes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
sourceB=(TextView)findViewById(R.id.tv_rcvDataB);
destinationB=(TextView)findViewById(R.id.tv_rcvDataBa);
sendSourceB=(Button)findViewById(R.id.btn_sendB);
sendDestinationB=(Button)findViewById(R.id.btn_sendDataBa);
activity=getClass().getSimpleName();
sendDestinationB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent senda= new Intent(ActivityB.this,ActivityC.class);
senda.putExtra("destination",src);
senda.putExtra("Activity",activity);
startActivity(senda);
}
});
sendSourceB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent send= new Intent(ActivityB.this,ActivityC.class);
send.putExtra("source",src);
send.putExtra("Activity",activity);
startActivity(send);
}
});}}
now how to check in activityC which activity is calling this activity and which buttonclicklistener is calling the intent
You need to send the value for determine what value and what activity via Intent.putExtra(). Please be remember that you need to set the key as the first parameter for Intent.putExtra(), like
intent.putExtra(THIS_IS_THE_KEY, THIS_IS_YOUR_VALUE);
You need to create something like this:
// This is the key for your putExtra
// you need to create this as global variable.
public static final String FROM_KEY = "FROM";
public static final String ACTIVITY_KEY = "ACTIVITY";
public static final boolean IS_FROM_SOURCE = true;
// This is a sample to send data to Activity C
// where the activity caller is B and from source
Intent senda= new Intent(ActivityB.this,ActivityC.class);
senda.putExtra(FROM_KEY, IS_FROM_SOURCE);
senda.putExtra(ACTIVITY_KEY,"activity_a");
Then in your Activity C, you need to receive the Intent Extra.
You can get the value in Activity onCreate(), something like this:
Bundle extras = getIntent().getExtras();
boolean from = extras.getBoolean(FROM_KEY);
String act = extras.getString(ACTIVITY_KEY);
// do something here if from activity a
if(act.equals("activity_a")) {
if(IS_FROM_SOURCE) {
// do something if from source
} else {
// do something if from destination.
}
} else { // if from activity a
if(IS_FROM_SOURCE) {
// do something if from source
} else {
// do something if from destination.
}
}
In onCreate or anytime after that method is called in Activity-C, you should do the following:
Intent intent = getIntent();
if (intent != null) {
String activity = intent.getStringExtra("Activity");
String src = intent.getStringExtra("source");
// Do something with those values
}
I don't know why, but this isn't working. Can anyone see anything wrong with my code.
I have two activities and I'm passing data from two
public class InputActivity extends AppCompatActivity {
EditText number1EditText;
EditText number2EditText;
Button addButton;
InputActivity code looks like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input);
number1EditText = (EditText)findViewById(R.id.editText);
number2EditText = (EditText)findViewById(R.id.editText2);
addButton = (Button)findViewById(R.id.button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(getApplicationContext(), AddActivity.class);
mIntent.putExtra("number1", number1EditText.getText().toString());
mIntent.putExtra("number2", number2EditText.getText().toString());
startActivity(mIntent);
}
});
}
AddActivity code looks like this
public class AddActivity extends AppCompatActivity {
TextView answer;
double y=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
answer =(TextView)findViewById(R.id.textView);
String value1 = getIntent().getExtras().getString("number1");
String value2 = getIntent().getExtras().getString("number2");
answer.setText((int) (Double.parseDouble(value1)+Double.parseDouble(value2)));
}
Just looking quickly:
answer.setText((int) (Double.parseDouble(value1)+Double.parseDouble(value2)));
You're passing a int to the method setText() which happens to have an overload that receives a int argument for the cases when you pass the reference from a String in some xml. You may be getting a ResourceNotFoundException.
If you want to show a text with the sum between your values:
answer.setText(String.valueOf((int) (Double.parseDouble(value1)+Double.parseDouble(value2))));
Just keep in mind that there are a lot of checks you have to do first, you may get another exceptions doing this kind of parse, like NumberFormatException for instance.
I have a login page for my project.Here my requirement is,that login page always want to be logged-in,if once i log in.I have got some ideas through Google,ie., it recommended me to use shared-preference concept,right now i am following this concept and i have tried some code.
In my project the problem is after giving the proper username and password,it does not switch to another screen,at the same i am getting nothing on my log-cat too.How to achieve this concept?
Suggestions please..
please find my sources for reference
class SaveSharedPreferece
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, boolean userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}}
MainActivity.java
public class MainActivity extends Activity
{
Button btn;
EditText edt1,edt2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void loginpage()
{
edt1 = (EditText)findViewById(R.id.editText_username);
edt2 = (EditText)findViewById(R.id.editText_password);
btn = (Button)findViewById(R.id.button_login);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(edt1.getText().toString().length()!=0 && edt1.getText().toString().length()!=0)
{
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
else
{
Toast.makeText(getApplicationContext(), "oops! empty..", Toast.LENGTH_SHORT).show();
}
}
});
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
loginpage();
}
else
{
// Call Next Activity
}
if (getIntent().getBooleanExtra("EXIT", false))
{
finish();
}
}
}
ResultActivity.java
public class ResultActivity extends Activity
{
Button btn_exit;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
btn_exit = (Button)findViewById(R.id.button_exit);
btn_exit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
});
}}
thanks for your precious time!..
You are saving boolean to SharedPreferences and getting String. How that is possible.
Better to save and get either boolean or String.
Change your setUserName() code in SaveSharedPreference class as below and it works
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
First add another field in SharedPrefernce file as password. Do same whatever you have done foe username(make it string instead of boolean in setter method) like setter and getter methods.
Create one method which will fetch values from sharedPrefernce like this :
private void validateUser(){
String username = SaveSharedPreference.getUserName(MainActivity.this);
String password = SaveSharedPreference.getPassword(MainActivity.this);
if (check_for_any_condition){
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
}
Call this method in your oncreate method.
Hope it will help you.
Bassicly my aim is too extend a activity so when the user presses Next how many times he wants to , i want to be able to display the value in the Activity2.
I want to somehow still keep the values stored into the variables even when i go into a new activity - im not too sure if thats possible. Any help would be appreciated
1st class
public class Activity extends Activity1 implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.Next:
if (value==0) {
value=1;
}
else if(value==1){
value=2
break;
}
case R.id.one:
Intent i1 = new Intent(this, Form.class);
startActivity(i1);
}
}
}
2nd Class
public class Activityv2 extends Activity1 implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button:
if(value==1){
display.setText("1");
}
else if(value==2)
{
display.setText("2");
}
}
}
}
you can store the value in a public static field.
Edit: or you can save it in SharedPreferences, or pass this value through the activity using the bundle
For instance you can save it in this way:
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private String loadPreferences(String key, String value){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
return settings.getString("silentMode", "");
}
You can pass values between Activities and Fragment via a Bundle or an Extra in the Intent class.
To retrieve these back, in an Activity you would call getIntent() and either get the Extra out of this, or call getExtras() on the returned Intent to get the Bundle. In a Fragment you would call getArguments() which returns a Bundle.
Bundles are very handy, allowing you to pass primitive data easily between Activities.
Another option is to store these values in your own class which extends from Application, which you can then access anywhere and at any time.