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.
Related
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;
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 an android main activity showing some data which are taken from the database. Now I have a PreferenceActivity which is shown when the user wants to change some preference, or delete the content of the database. But if this is the case, how do I force a 'reload' or something of the main activity from a class outside the main activity?
Set a OnSharedPreferenceChangeListener listener in your MainActivity to automatically detect any changes in the preferences.
SharedPreferencesListener
MainActivity.java
public class MainActivity extends ... {
private SharedPreferences settings;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Refresh display
refreshDisplay();
}
};
// Register the listener on the SharedPreferences
settings.registerOnSharedPreferenceChangeListener(listener);
// Other code
}
public void refreshDisplay() {
// Retrieve entries from sharedPreferences & display them, e.g
String prefValue1 = settings.getString("key1", "default value 1");
String prefValue2 = settings.getString("key2", "default value 2");
// Update UI with these values
}
}
EDIT:
Here is how your PreferenceActivity should be:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// R.xml.settings refers to the XML layout file named "settings"
// in your res/xml directory
addPreferencesFromResource(R.xml.settings);
}
}
If you just want to recharge an activity, you can do something like this:
finish();
startActivity(getIntent());
Here i want to send the value of "ourpassword" to say in myclass.java so how can i do this??
public class SetPassword extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.set_password);
final EditText ed=(EditText)findViewById(R.id.setpass);
Button submit=(Button)findViewById(R.id.button1);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String ourpassword=ed.getText().toString();
}
});
}
To pass data between activities use intents.
Intent i= new Intent("com.example.myclass");
i.puExtra("mypassword",ourpassword);
startActivtiy(i);
In myclass
Bundle extras = getIntent().getExtras();
if (extras != null) {
String password = extras.getString("mypassword");
}
You can also pass value to another class by passing value to the constructor of the class
myClass mc= new myClass(ourPassword);
mc.doSomething(); //call some method in another class
In your myclass
class myClass{
String pwd;
public myclass(String password)
{
pwd =password;
}
publidc void doSomething()
{
}
}
Say you want pass value to a class like asynctask
//pass value as a parameter to the class constructor
MyAsyncTask my= new MyAycTask(ourpassword).execute();
In My AsyncTask
class MyAsyncTask extends AsyncTask<Void,Void,Void>
{
public M(String password)//receive value here
{
}
other methods....
}
Create object of this class and get the value as
Define string as static
Object.String;
You can also use Use database. thats better way to store and retrieve passwords
If myclass.java is another Activity class, you can just set the password as a parameter in the intent. For example:
Intent intent = new Intent(getApplicationContext(),myclass.class);
intent.putExtra("password", ourpassword);
startActivity(intent);
... and then you can get the value from within the myclass.java in the onCreate() method like this:
String password = "";
if (getIntent().getStringExtra("password") != null) password = getIntent().getStringExtra("password");
EDIT: You place the Intent code in the onClick() method of the submit button.
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.