How to save activity state after navigating? - android

I have an app with 3 activities,home,calculationResult and help.What I'm trying to do is save the details of the calculations on calculationResult when the user navigates to help.So when the user is in help and presses the action bar back icon,the results of the calculation will still be there in calculationResult.
I have tried to implement this so far by following this guide: Recreating an activity,But when I implemented it the variable I'm wanting to store is not recognized when using with savedInstanceState.Below is how I have tried to do this in the result class.Can someone point out where I have gone wrong with this or if this is the correct way to accomplish saving the activity state?
public class CalcResult extends Activity implements OnClickListener{
TextView result1;
static final String MARK1 = "marking1";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
if (savedInstanceState != null) {
// Restore value of members from saved state
//not recognizing this variable mark1 which I'm setting to the variable that stores the result of the calculation.
mark1 = savedInstanceState.getDouble(MARK1);
}
final Intent intent1=new Intent(this,AboutActivity.class);
final Intent intent2=new Intent(this,MainActivity.class);
final Intent intent3=new Intent(this,MainActivity.class);
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
R.layout.a,
null);
// Set up your ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
final Button actionBarHome = (Button) findViewById(R.id.action_bar_title);
actionBarHome.setBackgroundResource(R.drawable.ic_action_back);
actionBarHome.setOnClickListener(this);
actionBarHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent2);
}
});
final Button actionBarInfo = (Button) findViewById(R.id.action_bar_staff);
actionBarInfo.setBackgroundResource(R.drawable.ic_action_help);
actionBarInfo.setOnClickListener(this);
actionBarInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent1);
}
});
final Button actionBarHoome = (Button) findViewById(R.id.action_bar_home);
actionBarHoome.setBackgroundResource(R.drawable.appicon);
actionBarHoome.setOnClickListener(this);
actionBarHoome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent3);
}
});
result1 = (TextView)findViewById(R.id.markOne);
Intent intent = getIntent();
double markOne = intent.getDoubleExtra("number1", 0);
DecimalFormat df = new DecimalFormat("#.##");
result1.setText(String.valueOf(df.format(markOne)+"mm"));
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
//Also doesn't recognise markOne here ->
savedInstanceState.putDouble(MARK1, this.markOne);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}

Instead of this
double markOne = intent.getDoubleExtra("number1", 0);
You should write
markOne = intent.getDoubleExtra("number1", 0);
by declaring it again you are not assigning the value to the class level markOne
Also you can try setting the lauchmode of your calculateResult activity as singleTop
android:launchMode="singleTop"
This will use the same instance of the activity that already exist on the top of the stack so will have the same state as before.
Try calling finish in your Help activity when you move to CalculationResult activity.
for ex:
StartActivity(<Intent>);
finish();

onRestoreInstanceState() is called when Activity was killed by the OS. "Such situation happen when:
•orientation of the device changes (your activity is destroyed and recreated)
•there is another activity in front of yours and at some point the OS kills your activity in order to free memory.
Next time when you start your activity onRestoreInstanceState() will be called."
But in your case, this might not happen.

Approach i followed
I set a global varibale to act as a flag if i am launching this activity for the first time. If the global varibale is the same as what i had set, i leave the editText untouched. (in your case, result1). If the value is changed, i set the editText for this value. If the user clicks the editText even once, i track the change and store the value. When you think, the mark1 is no longer needed, you can set the value of flag again as "FIRSTENTRY". This would work.
Kindly try and let us know if you still face issues.
Step 1
Created a class to store a static Global variable.
public class Constants {
public static String sFlag= "FIRSTENTRY";
}
Step 2
Add this piece of code after "setContentView(R.layout.result);" line in your oncreate method. Instead of TextView, i have declared result1 as EditText.
if(!Constants.sFlag.equalsIgnoreCase("FIRSTENTRY"))
{
result1.setText(Constants.sFlag);
}
result1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
Constants.sFlag = result1.getText().toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Constants.sFlag = result1.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Constants.sFlag = result1.getText().toString();
}
});

Related

App is crashing when I click the button - two intents in a button - using Enum

I need help with my code. Let me try to explain the problem:
At the first activity I have two fields where I'll set values from an Enum, for this I made a button for each field that basically shows me another activity, calls the value and brings it to the main activity. Still in the first activity I have a button that starts another activity and (at the same time) take all the values from the enum end sends to another activity. The point is, everything is working, but this last button no, when I click it the app crashes. What is happening and how can I solve it?
Here goes the code of the first activity:
public class MenuInicial extends AppCompatActivity {
public static final int CONSTANTE_BANZO = 1;
Button escolherM;
Button escolherB;
Button next;
TextView campoM;
TextView campoB;
Intent intent1;
Intent intent2;
Intent intentBundle;
Intent intentNext;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_inicial);
intent1 = new Intent(MenuInicial.this, Montante.class);
campoM = (TextView) findViewById(R.id.fieldM);
escolherM = (Button) findViewById(R.id.chooseM);
String perfilM = getIntent().getExtras().getString("nameM");
campoM.setText(perfilM);
escolherM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivity(intent1);
}
});
intent2 = new Intent(MenuInicial.this, Banzo.class);
campoB = (TextView) findViewById(R.id.fieldB);
escolherB = (Button) findViewById(R.id.chooseB);
escolherB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivityForResult(intent2, CONSTANTE_BANZO);
}
});
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
}
protected void onActivityResult(int codigo, int resultado, Intent intent){
if(codigo == CONSTANTE_BANZO){
Bundle bundleB = intent.getExtras();
if(bundleB != null){
String perfilB = bundleB.getString("nameB");
campoB.setText(perfilB);
}
}
}
}
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
Which activity do you want to go to? choose one. When you do, you can get those extras then when you need to goto the other activity, you can put those extras there too.
A better way to do it is to create a model (constructor with setters and getters) and put these in a list. At that point you can loop through the list and take what you need. It all depends on what you are doing though as the list will not be instantiated like intent extras would be.
Or, you can use SharedPref which is similar to a HashMap (which is also similar to the Intent Extras). SharedPref will store the key and value on the phones cache and then you can pull from that when you need it. Again, keep in mind that if the user clears the cache on the app, then it'll delete those shared pref.
Finally, you can also use a database such as Parse Server or Firebase.

Using Intent while saving data of previous Activity

I'm currently trying to guess how do I save a data from a previous Activity.
An example is:
At the startPage.class, I have a few options to choose from(Animation Mode, Image Mode, Text Mode) so if I choose for example Text Mode so the it'll be the RadioButton3 and when I press next it goes to the another Activity. So lets say in that new Activity it has this Intent command. How do I retain the data from the previous activity when I press the backSelection3?
Meaning, when I press the back, I want the RadioButton3 to be the selection still instead of it resetting to the default choice.
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent backSelection3 = new Intent(imagemode64by64.this, startPage.class);
startActivity(backSelection3);
}
});
You can use onSaveInstanceState
void onSaveInstanceState(Bundle out) {
String val = ...
out.putString("MYVALUE", val);
super.onSaveInstanceState(val);
}
Then
void onCreate(Bundle savedState) {
if(savedState != null) {
String val = savedState.getString("MYVALUE");
}
}
Or do you mean how to put data for another activity? Then you can do
Intent i = new Intnet(this, OtherActivity.class);
String val = ...
i.putExtra("MYVALUE", val);
startActivity(i);
Then in the other activity
void onCreate(Bundle savedState) {
...
Intent i = getIntent();
String val = i.getStringExtra("MYVALUE");
}
Here is an age old example of passing data between classes:
class A{
static int num = 0;
public void setNum(int number){
num = number
}
}
class B{
public static void main(){
A obja = new A();
obja.setNum(3);
}
}
As soon as you do the operation in class B you can use the num variable in class A.

Android: putExtras and Intents

I am having a problem with passing strings from a fragment to another activity.
I have tried numerous methods of passing them using intents (eg normal extras, bundles) , but the extras are always null in the activity.
I have looked at
http://www.vogella.com/articles/AndroidIntent/ But no change
http://developer.android.com/training/basics/firstapp/starting-activity.html This method of passing the data also doesn't work
Other similar questions on stackoverflow - but these are not quite the same
What I'm trying to do is get the text that was input in the two EditTexts in the fragment, and then pass that text to the activity where the two EditTexts there are filled with the same text. The problem is that nothing appears in the the two EditTexts in the activity. I know that the EditTexts in the fragments are working because a can create a notification using them.
My code: I have removed things I think are unneccessary eg adding the fragment to a navigation drawer layout. Please excuse missing brackets - I have removed a lot of code and some may have been removed accidentally! :-)
This is the fragment where I create an intent:
// Package declaring and importing stuff
public class QuickNoteFragment extends Fragment implements OnClickListener {
// Removed some stuff
EditText body;
EditText title;
Button create;
int counter = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quicknote, container, false);
body = (EditText) rootView.findViewById(R.id.qn_et_body);
title = (EditText) rootView.findViewById(R.id.qn_et_title);
create.setOnClickListener(this);
// Removed stuff
getActivity().setTitle(noter_activity); // Part of navigation drawer?
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.qn_b_create:
String content_text = body.getText().toString();
String content_title = title.getText().toString();
if (content_title.length() >=1){
Context context = v.getContext();
// This intent does not seem to work
Intent eIntent = new Intent(context, QuickNoteEdit.class);
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
PendingIntent EditPendingIntent = PendingIntent.getActivity(context, 0, eIntent, 0);
// This intent works comletely. This is called when a notification action button is pressed
Intent qnCancel = new Intent();
qnCancel.setAction("com.RiThBo.noter.qnCancelBroadcast");
Bundle extras = new Bundle();
extras.putInt("valueOfCounter", counter);
qnCancel.putExtras(extras);
startBroadcast(qnCancel);
PendingIntent pQnCancel = PendingIntent.getBroadcast(this.getActivity(), 0, qnCancel, 0);
// Creates Notification
} else {
// Do something
}
case R.id.*** // Does something else
}
}
private void startBroadcast(Intent qnCancel) { // This is part of the correctly working intent
// TODO Auto-generated method stub
}
}
This is the activity where I'm trying to get the extras
// Removed package and imports
public class QuickNoteEdit extends Activity implements OnClickListener {
EditText body;
EditText title;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quicknote_edit);
variableConnector(); // This gets the id for all the items in the xml
Intent intent = getIntent();
String gotTitle = intent.getStringExtra("content_title"); // This is where I think it equals null. Because the
String gotBody = intent.getStringExtra("content_text");
title.setText(gotTitle);
body.setText(gotBody);
}
private void variableConnector() {
// TODO Auto-generated method stub
body = (EditText) findViewById(R.id.qne_et_body);
title = (EditText) findViewById(R.id.qne_et_title);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Thank you
You're putting:
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
and when you read them:
String gotTitle = intent.getStringExtra("content_title");
String gotBody = intent.getStringExtra("content_text");
You need to match the keys ... put "eTitle" and read "eTitle", not "*content_title*"!
You're tagging your extras with "eTitle" and "eText" and trying to retrieve them with "content_title" and "content_text".
Switch to
String gotTitle = intent.getStringExtra("eTitle");
String gotBody = intent.getStringExtra("eText");
it should work.

How to retain EditText data on orientation change?

I have a Login screen which consists of 2 EditTexts for Username and Password. My requirement is that on orientation change , input data(if any) in EditText should remain as it is and a new layout should also be drawn. I have 2 layout xml files- one in layout folder and other in layout-land folder. I am trying to implement following 2 approaches but none of them is perfect:
(1) configChanges:keyboardHidden - In this approach, I don't provide "orientation" in configChanges in manifest file. So I call setContentView() method in both onCreate() and onConfigurationChanged() methods. It fulfills both my requirements. Layout is changed and input data in EditTexts also remains as it is. But it has a big problem :
When user clicks on Login button, a ProgressDialog shows until server-response is received. Now if user rotates the device while ProgressDialog is running, app crashes. It shows an Exception saying "View cannot be attached to Window." I have tried to handle it using onSaveInstanceState (which DOES get called on orientation change) but app still crashes.
(2) configChanges:orientation|keyboardHidden - In this approach, I provide "orientation" in manifest. So now I have 2 scenarios:
(a) If I call setContentView() method in both onCreate() and onConfigurationChanged(), Layout is changed accordingly but EditText data is lost.
(b) If I call setContentView() method in onCreate() , but not in onConfigurationChanged(), then EditText data is not lost but layout also not changes accordingly.
And in this approach, onSaveInstanceState() is not even called.
So I am in a really intimidating situation. Is there any solution to this problem? Please help. Thanx in advance.
By default, Edittext save their own instance when changing orientation.
Be sure that the 2 Edittexts have unique IDs and have the same IDs in both Layouts.
That way, their state should be saved and you can let Android handle the orientation change.
If you are using a fragment, be sure it has a unique ID also and you dont recreate it when recreating the Activity.
A better approach is to let android handle the orientation change. Android will automatically fetch the layout from the correct folder and display it on the screen. All you need to do is to save the input values of the edit texts in the onSaveInsanceState() method and use these saved values to initialize the edit texts in the onCreate() method.
Here is how you can achieve this:
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
...
...
String userName, password;
if(savedInstanceState!=null)
{
userName = savedInstanceState.getString("user_name");
password= savedInstanceState.getString("password");
}
if(userName != null)
userNameEdtTxt.setText(userName);
if(password != null)
passEdtTxt.setText(password);
}
>
#Override
protected void onSaveInstanceState (Bundle outState)
{
outState.putString("user_name", userNameEdtTxt.getText().toString());
outState.putString("password", passEdtTxt.getText().toString());
}
Give the element an id and Android will manage it for you.
android:id="#id/anything"
in onConfigurationChanged method, first get the data of both the edit texts in global variables and then call setContentView method. Now set the saved data again into the edit texts.
There are many ways to do this. The simplest is 2(b) in your question. Mention android:configChanges="orientation|keyboardHidden|screenSize" in your manifest so that Activity doesn't get destroyed on Orientation changes.
Call setContentView() in onConfigChange(). but before calling setContentView() get the EditText data into a string and set it back after calling setContentView()
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mEditTextData = mEditText.getText().tostring();//mEditTextData is a String
//member variable
setContentView(R.layout.myLayout);
initializeViews();
}
private void initializeViews(){
mEditText = (EditText)findViewById(R.id.edittext1);
mEdiText.setText(mEditTextData);
}
The following should work and is standard to the activities and fragments
#Override
public void onSaveInstanceState (Bundle outState)
{
outState.putString("editTextData1", editText1.getText().toString());
outState.putString("editTextData2", editText2.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate();
... find references to editText1, editText2
if (savedInstanceState != null)
{
editText1.setText(savedInstanceState.getString("editTextData1");
editText2.setText(savedInstanceState.getString("editTextData2");
}
}
Im restoring instance to restore values and it works fine for me :)
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtask2);
if(savedInstanceState!=null)
onRestoreInstanceState(savedInstanceState);
}
Remove android:configChanges attribute from the menifest file and let android handle the orientation change your data in edittext will automatically remain.
Now The problem you mentioned is with the progress dialog force close this is because when the orientation is changed the thread running in backgroud is trying to update the older dialog component whihc was visible. You can handle it by closing the dialog on savedinstancestate method and recalling the proceess you want to perform onRestoreInstanceState method.
Below is a sample hope it helps solving your problem:-
public class MyActivity extends Activity {
private static final String TAG = "com.example.handledataorientationchange.MainActivity";
private static ProgressDialog progressDialog;
private static Thread thread;
private static boolean isTaskRunnig;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new EditText.OnClickListener() {
#Override
public void onClick(View v) {
perform();
isTaskRunnig = true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void perform() {
Log.d(TAG, "perform");
progressDialog = android.app.ProgressDialog.show(this, null,
"Working, please wait...");
progressDialog
.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
//isTaskRunnig = false;
}
});
thread = new Thread() {
public void run() {
Log.d(TAG, "run");
int result = 0;
try {
// Thread.sleep(5000);
for (int i = 0; i < 20000000; i++) {
}
result = 1;
isTaskRunnig = false;
} catch (Exception e) {
e.printStackTrace();
result = 0;
}
Message msg = new Message();
msg.what = result;
handler.sendMessage(msg);
};
};
thread.start();
}
// handler to update the progress dialgo while the background task is in
// progress
private static Handler handler = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG, "handleMessage");
int result = msg.what;
if (result == 1) {// if the task is completed successfully
Log.d(TAG, "Task complete");
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
isTaskRunnig = true;
}
}
}
};
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, "onRestoreInstanceState" + isTaskRunnig);
if (isTaskRunnig) {
perform();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState");
if (thread.isAlive()) {
thread.interrupt();
Log.d(TAG, thread.isAlive() + "");
progressDialog.dismiss();
}
}
As pointed out by Yalla T it is important to not recreate the fragment. The EditText will not lose its content if the existing fragment is reused.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_frame);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Display the fragment as the main content.
// Do not do this. It will recreate the fragment on orientation change!
// getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new Fragment_Places()).commit();
// Instead do this
String fragTag = "fragUniqueName";
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = (Fragment) fm.findFragmentByTag(fragTag);
if (fragment == null)
fragment = new Fragment_XXX(); // Here your fragment
FragmentTransaction ft = fm.beginTransaction();
// ft.setCustomAnimations(R.xml.anim_slide_in_from_right, R.xml.anim_slide_out_left,
// R.xml.anim_slide_in_from_left, R.xml.anim_slide_out_right);
ft.replace(android.R.id.content, fragment, fragTag);
// ft.addToBackStack(null); // Depends on what you want to do with your back button
ft.commit();
}
Saving state = Saving (Fragment State + Activity State)
When it comes to saving the state of a Fragment during orientation change, I usually do this way.
1) Fragment State:
Save and Restore EditText value
// Saving State
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("USER_NAME", username.getText().toString());
outState.putString("PASSWORD", password.getText().toString());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.user_name_fragment, parent, false);
username = (EditText) view.findViewById(R.id.username);
password = (EditText) view.findViewById(R.id.password);
// Retriving value
if (savedInstanceState != null) {
username.setText(savedInstanceState.getString("USER_NAME"));
password.setText(savedInstanceState.getString("PASSWORD"));
}
return view;
}
2) Activity State::
Create a new Instance when the activity launches for the first time
else find the old fragment using a TAG and the FragmentManager
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
fragmentManager = getSupportFragmentManager();
if(savedInstanceState==null) {
userFragment = UserNameFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.profile, userFragment, "TAG").commit();
}
else {
userFragment = fragmentManager.findFragmentByTag("TAG");
}
}
You can see the the full working code HERE
Below code is work for me. Need to care two things.
Each Input Field (Edit Text or TextInputEditText) assign unique id.
Manifest activity declaration should have on configuration change attribute with below values.
android:configChanges="orientation|keyboardHidden|screenSize"
Sample activity declaration in manifest.
<activity
android:name=".screens.register.RegisterActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:exported="true"
android:label="Registration"
android:theme="#style/AppTheme.NoActionBar" />
Sample declaration of
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/inputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:boxCornerRadiusBottomEnd="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusBottomStart="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusTopEnd="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusTopStart="#dimen/boxCornerRadiusDP">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/inputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:fontFamily="#font/proxima_nova_semi_bold"
android:inputType="textCapWords"
android:lines="1"
android:textColor="#color/colorInputText"
android:textColorHint="#color/colorInputText" />
</com.google.android.material.textfield.TextInputLayout>
this may help you
if your android:targetSdkVersion="12" or less
android:configChanges="orientation|keyboardHidden">
if your android:targetSdkVersion="13" or more
android:configChanges="orientation|keyboardHidden|screenSize">

how to get one class transparent variable value into another class in android

hi i am doing one app here.user click button once means in another activity i need to perform one action,user again come back to same page agian click that same button means i need to perform different action. i take 2 activities in activity1 i have 1 button ,i treid using one count variable in activity1 button click that time i incremented count variable,using putextra i get that count value into acticity2 here based on count i perform actions,but count one time is in incresed,if i come back to same activty1 then i click button that also count is '1'only,it is not incresed to 2.so how to solve that issue any one having idea suggest me.
Activity1 .class:
public class Activity1 extends Activity implements OnClickListener{
Button b1,b2;
int countk4=0;
SharedPreferences share;
String bol3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home1);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==b1)
{
countk4++;
share=getSharedPreferences("shared", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor=share.edit();
editor.putInt("roll", countk4);
editor.commit();
show();
Intent i=new Intent(Activity1 .this,Activity2.class);
i.putExtra("k", 1);
i.putExtra("k1", 13);
i.putExtra("ks", val1);
startActivity(i);
}
}
Integer val1,val2;
private void show() {
// TODO Auto-generated method stub
share=getSharedPreferences("shared", MODE_WORLD_READABLE);
val1=share.getInt("roll",0);
}
}
Activity2 .class:
public class Activity2 extends Activity implements OnClickListener{
Button back;
int countkv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home2);
back=(Button)findViewById(R.id.button1);
back.setOnClickListener(this);
countkv = getIntent().getIntExtra("ks", 0);
if(countkv =1)
{
Toast.makeText(getApplicationContext(), "hai.......i am first", Toast.LENGTH_LONG).show();
}
if(countkv =2)
{
Toast.makeText(getApplicationContext(), "hai.......1 am second", Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==back)
{
Intent i=new Intent(Activity2.this,Activity1.class);
startActivity(i);
}
}
}
}
but above every time first toast message displayed becz countkv is every time 1 only..
At Receiving side make an object of Bundle.
Bundle myBundle = new Bundle(); // Declare above
String temp;
myBundle = getIntent().getIntExtra();
temp = myBundle.getString("ks"); // temp will have the val1.
Hope you can get it now.

Categories

Resources