I have put a condition in onCreate() method to check if there exist some previous data or not. But it is not working.
please guide me.
And I don't want to use onRestoreSavedState() method for this.d
public class ActivityOne extends Activity {
Use these as keys when you're saving state between reconfigurations
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
String for LogCat documentation
private final static String TAG = "Lab-ActivityOne";
private int mCreate=0, mRestart=0, mStart=0, mResume=0;
You will need to increment these variables' values when their
corresponding lifecycle methods get called.
TODO: Create variables for each of the TextViews
private TextView mTvCreate, mTvRestart, mTvStart, mTvResume;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
TODO: Assign the appropriate TextViews to the TextView variables
mTvCreate=(TextView)findViewById(R.id.create);
mTvRestart=(TextView)findViewById(R.id.restart);
mTvResume=(TextView)findViewById(R.id.resume);
mTvStart=(TextView)findViewById(R.id.start);
Button launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo);
launchActivityTwoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=null;
intent = new Intent(v.getContext(),ActivityTwo.class);
startActivity(intent);
}
});
if(savedInstanceState!=null){
mCreate=savedInstanceState.getInt(String.valueOf(mCreate));
mRestart=savedInstanceState.getInt(String.valueOf(mRestart));
mResume=savedInstanceState.getInt(String.valueOf(mResume));
mStart=savedInstanceState.getInt(String.valueOf(mStart));
}
// Emit LogCat message
Log.i(TAG, "Entered the onCreate() method");
mCreate++;
displayCounts();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Save state information with a collection of key-value pairs
4 lines of code, one for every count variable
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(String.valueOf(mCreate),mCreate);
savedInstanceState.putInt(String.valueOf(mRestart),mRestart);
savedInstanceState.putInt(String.valueOf(mResume),mResume);
savedInstanceState.putInt(String.valueOf(mStart),mStart);
}
Updates the displayed counters
This method expects that the counters and TextView variables use the names specified above
public void displayCounts() {
mTvCreate.setText("onCreate() calls: " + mCreate);
mTvStart.setText("onStart() calls: " + mStart);
mTvResume.setText("onResume() calls: " + mResume);
mTvRestart.setText("onRestart() calls: " + mRestart);
}
}
It looks like the problem is that you attempting to use values that have not been set yet when you try to capture the saved value.
All you need to do to fix it is to use the String constants that you have defined.
So, in onCreate(), you would have:
if(savedInstanceState!=null){
mCreate=savedInstanceState.getInt(CREATE_KEY);
mRestart=savedInstanceState.getInt(RESTART_KEY);
mResume=savedInstanceState.getInt(RESUME_KEY);
mStart=savedInstanceState.getInt(START_KEY);
}
Then, in onSaveInstanceState(), you would have:
savedInstanceState.putInt(CREATE_KEY,mCreate);
savedInstanceState.putInt(RESTART_KEY,mRestart);
savedInstanceState.putInt(RESUME_KEY,mResume);
savedInstanceState.putInt(START_KEY,mStart);
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;
In my code below I am able to edit a text from my first setText() call but not from within the callback.
The error I receive is a NullPointerException for title in the callback.
How do I set this up so I can edit the text from within the callback?
public class ListingActivity extends AppCompatActivity {
final String TAG = "ListingActivity";
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title = (TextView)findViewById(R.id.tvTitle);
Intent intent = getIntent();
final String listingId = intent.getStringExtra("ObjectId");
setContentView(R.layout.listing_activity);
Log.e(TAG, "listingId: " + listingId);
title.setText("listingId");//fine
ListingManager.getListing(listingId, new ListingCB() {
#Override
public void done(String error, Listing listing) {
title.setText("listingId");//null pointer error
}
});
}
}
Your setContentView() method must be called before giving references using findViewById() method, so your code will be -
public class ListingActivity extends AppCompatActivity {
final String TAG = "ListingActivity";
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listing_activity);
title = (TextView)findViewById(R.id.tvTitle);
Intent intent = getIntent();
final String listingId = intent.getStringExtra("ObjectId");
Log.e(TAG, "listingId: " + listingId);
title.setText("listingId");//fine
ListingManager.getListing(listingId, new ListingCB() {
#Override
public void done(String error, Listing listing) {
title.setText("listingId");//null pointer error
}
});
}
}
title.setText("listingId");//fine
That shouldn't be fine...
You must put setContentView before any findViewById. That is number one reason why your TextView is null.
Your callback is fine.
I have two variables to save on device orientation. One is current question number as an integer, another is a boolean value if the user cheated. It working fine when I'm storing and retrieving sinle value while storing both value it swaps.
public class QuizActivity extends ActionBarActivity {
// Logging members
private static final String LOG_TAG = QuizActivity.class.getSimpleName();
// The member of Saving the state for rotation of the device
private static final String KEY_BOOLEAN = "index";
private static final String KEY_INT = "index";
// Adding members
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mBackButton;
private TextView mQuestionTextView;
private ImageButton mImgRightButton;
private ImageButton mImgLeftButton;
private Button mCheatButton;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true)
};
private int mCurrentIndex = 0;
// To save the CheatActivity returning result
private boolean mIsCheater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "QuizActivity onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if(savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INT);
mIsCheater = savedInstanceState.getBoolean(KEY_BOOLEAN);
}
}
// Not to loose activity state when rotating the device
#Override
public void onSaveInstanceState(Bundle saveInstanceState) {
Log.i(LOG_TAG, "onSaveIntanceState");
saveInstanceState.putInt(KEY_INT, mCurrentIndex);
saveInstanceState.putBoolean(KEY_BOOLEAN, mIsCheater);
super.onSaveInstanceState(saveInstanceState);
};
// to get the result from child activity(Cheat activity)
#Override
protected void onActivityResult(int arg0, int arg1, Intent data) {
if(data == null){
return;
}
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);
};
}
You have the same keys!! Change code like this:
private static final String KEY_BOOLEAN = "index_BOOLEAN";
private static final String KEY_INT = "index_INT";
KEY_INT and KEY_BOOLEAN have the same name, the same value. So when setting those in the bundle one might overwrite the other. Use different names:
private static final String KEY_INT="intindex";
private static final String KEY_BOOLEAN="boolindex";
I have an app with two layouts (portrait and landscape). There are 4 int values I want to save so they don't get erased on rotation. For that, I call on save instance and then I recover the state on the onCreate method like this:
private int operando1;
private int operando2;
private int operador;
private int contadorIntentos;
private String operadorTxt;
private static final String CONTADOR_INTENTOS = "contadorIntentos";
private static final String OPERANDO1 = "operando1";
private static final String OPERANDO2 = "operando2";
private static final String OPERADOR = "contadorIntentos";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CONTADOR_INTENTOS, contadorIntentos);
outState.putInt(OPERANDO1, operando1);
outState.putInt(OPERANDO2, operando2);
outState.putInt(OPERADOR, operador);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actividad_principal);
//other random code
Random generador = new java.util.Random();
if (savedInstanceState != null){
contadorIntentos = savedInstanceState.getInt(CONTADOR_INTENTOS);
operando1 = savedInstanceState.getInt(OPERANDO1);
operando2 = savedInstanceState.getInt(OPERANDO2);
operador = savedInstanceState.getInt(OPERADOR);
}else {
contadorIntentos = 0;
operando1 = generador.nextInt(1000);
operando2 = generador.nextInt(1000);
operador = generador.nextInt(4);
}
Well, it turns out that it only saves the state once. after the first rotation (when it saves correctly) if I modify things and rotate again it recovers the state of the first rotation. It's like onsaveinstancestate only works once. Why?
Because savedInstanceState isn't null in all of the subsequent rotations, you are never generating new numbers (ex: never calling this again: operando1 = generador.nextInt(1000)...etc...)
i have problem in this simple code, I declare a String , and want change it inside onCreate but AFTER onCreate i have "VariableDeclaratorId expected after this token" Error !!
And if i put item=222 inside onCreate i get "111null333" when Toast display
here is my code
public class MainActivity extends Activity {
static String item;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), mStrings[0], Toast.LENGTH_SHORT).show();
}
item="222";
private String[] mStrings={
"111"+item+"333",
"test"
};
}
Can you please spend some time and format your question correctly ? i do not see clearly if the item = "222"; is inside a method or not.
But if your formatting is "correct" then your problem is that the assignation of a value to the item variable can not be done outside of a method or the static{} block of code. And so if you use the item variable in another object or class variable before assigning it a value it will be the default value (null for objects and 0 or false for the primitive values).
Hope this helps.
UPDATE:
public class MainActivity extends Activity {
static String item;
private String[] mStrings;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item = "222";
mStrings = new String[2];
mStrings[0] = "111" + item + "333";
mStrings[1] = "test";
Toast.makeText(getApplicationContext(), mStrings[0], Toast.LENGTH_SHORT).show();
}
}