How can I use savedInstanceState and show text in editText? - android

I want to save text in a editText and when I rotate the cell phone then it's showed again.
but, "it's showed again" this part doesn't work but, Toast is working.
I thought "setText" is the one...
here is the
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
name = editText.getText().toString();
showToast("saved : " + name);
}
});
if (savedInstanceState != null){
name = savedInstanceState.getString("name");
showToast("restore : " + name);
editText.setText("name");
}
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString("name", name);
super.onSaveInstanceState(outState);
}
public void showToast(String data){
Toast.makeText(this, data, Toast.LENGTH_LONG).show();
}
}

You have wrapped the variable name in "" so you're inputting the actual text name as a string into the edit text, rather than the contents of that variable. Remove the quotation marks like so:
if (savedInstanceState != null) {
String text = savedInstanceState.getString("name");
editText.setText(text);
}
EDIT
I would also suggest that you capture the value of the text inside the edit text at the time of saveInstanceState(), incase the global 'name' variable happens to be null. Like so:
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
String text = editText.getText().toString();
outState.putString("name", text);
}

Related

Android save and restore TextView text ViewPager fragments

In my ViewPager i have some fragments which i change some TextView texts dynamically, after switch between pages texts of TextViews clear, and i can't save and restore them from instance
this is my code and dont work
private String value1;
private String value2;
private String value3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//#formatter:off
context = getActivity().getBaseContext();
activity = getActivity();
//#formatter:on
}
#Override
public void onViewStateRestored(#Nullable Bundle inState) {
super.onViewStateRestored(inState);
if (inState != null) {
inState.getString("value1", value1);
inState.getString("value2", value2);
inState.getString("value3", value3);
sahmiyeh_value_1.setText(value1);
sahmiyeh_value_2.setText(value2);
sahmiyeh_value_3.setText(value3);
}
}
#Override
public void onSaveInstanceState(#Nullable Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("value1", sahmiyeh_value_1.getText().toString());
outState.putString("value2", sahmiyeh_value_2.getText().toString());
outState.putString("value3", sahmiyeh_value_3.getText().toString());
}
You can try freezesText
<TextView
...
android:freezesText="true" />
From documentation :
If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. By default this is disabled; it can be useful when the contents of a text view is not stored in a persistent place such as a content provider
You didn't declare the string value.
value1, value2, value3 is empty. That's why there's no value on your TextView or EditText.
#Override
public void onViewStateRestored(#Nullable Bundle inState) {
super.onViewStateRestored(inState);
if (inState != null) {
value1 = inState.getString("value1");
value2 = inState.getString("value2");
value3 = inState.getString("value3");
sahmiyeh_value_1.setText(value1);
sahmiyeh_value_2.setText(value2);
sahmiyeh_value_3.setText(value3);
}
}
Or you can do it like this.
sahmiyeh_value_1.setText(inState.getString("value1"));
sahmiyeh_value_2.setText(inState.getString("value2"));
sahmiyeh_value_3.setText(inState.getString("value3"));

android - Corrected text in EditText not received

I have two date fields (no, not the pickers) as fromDate and toDate. When I click on my Submit button, in the onResume(), I have validations in place for both date fields. When I enter an invalid value (not from syntax, locale, etc. point of view) for toDate and click Submit, I correctly see the toast. Then, I enter the correct the value and click Submit. The toast still appears ! In other words, the corrected date value is not being received.
I guess, I am missing the activity life-cycle w.r.t. toasts. (Each Toast is immediately followed by a return.) Can you please suggest what should be the correct flow to handle this error followed by correction ?
public class MainActivity extends Activity {
private Locale l ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set locale;
l = getResources().getConfiguration().locale;
}
#Override
protected void onResume() {
super.onResume();
addButtonListener();
}
private void addButtonListener() {
Button submitButton = (Button) findViewById(R.id.buttonSubmit);
submitButton.setOnClickListener(new OnClickListener() {
EditText fromDateText = (EditText) findViewById(R.id.fromDate);
EditText toDateText = (EditText) findViewById(R.id.toDate);
#Override
public void onClick(View v) {
String s;
if (fromDateText.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.err_fromDate_1, Toast.LENGTH_SHORT).show();
return;
}
if (toDateText.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.err_toDate_1, Toast.LENGTH_SHORT).show();
return;
}
}
});
}
}
Edited to add source code.
Make fromDateText and toDateText class variables and init them in onCreate.

SherlockFragmentActivity EditText getText() nullpointerexception

I have this error nullpointerexception, when i do getText().toString() from EditTex:
public class SendMessActivity extends SherlockFragmentActivity {
private EditText tEmail;
private Button sendButton;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_mess_layout);
tEmail = (EditText)findViewById(R.id.editEmailTo);
sendButton = (Button)findViewById(R.id.btn_sendmess);
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String textEmail = tEmail.getText().toString(); //nullpointerexception
Editable textEmail1Editable = tEmail.getText(); //nullpointerexception
String textEmail = textEmail1Editable.toString()
Log.d(DEBUGTAG, "SENDING START:::::::: " + textEmail);
}
});
}}
Please, tell me how to do it
UPDATE Q
David, thank you, for your surmise,the problem was really in the my tangled Layouts
I had all 4 levels of nesting LinearLayouts.
After I left the simplified scheme and only 2 levels I have, all began to work
You need to call setContentView(your_layout.xml) so it knows what layout to use. Without setting the layout, all of your calls to findViewById(...) that try to find the views in your layout will return null.
public class SendMessActivity extends SherlockFragmentActivity {
private EditText tEmail;
private Button sendButton;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(your_layout.xml); //set your activity layout here.
tEmail = (EditText)findViewById(R.id.editEmailTo);
sendButton = (Button)findViewById(R.id.btn_sendmess);
endButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String textEmail = tEmail.getText().toString(); //nullpointerexception
Log.d(DEBUGTAG, "SENDING START:::::::: " + textEmail);
}
});
}}
If you have no assigned text then I would assume that the EditText retrieval of the text would be a null entry and you are attempting to make a string of that null entry.

EditText Not Reading Input in Android

The problem in EditText is, it is not returning the input value.I am using that input value to check condition.
I am giving the correct input so that i checks the if condition and go to next activity but
it always goes to else condition.
Please check the code below, i had commented the problem.
Here is the snippet
public class BuildWord extends Activity
{
String word = "word";
String finished = "Word Built";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.buildword);
EditText get = (EditText)findViewById(R.id.dataToSend);
String getdata = get.getText().toString(); //Here i am getting Data from EditText
displayIntentData();
if (getdata.equals("word"))
//Here i am checking with "word" but it goes to else condition.I am typing "word" only
{
findViewById(R.id.sendButton1).setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(BuildWord.this,MainActivity.class);
intent.putExtra("key", word);
startActivity(intent);
}
});
}
else
{
findViewById(R.id.sendButton1).setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(BuildWord.this,DropCard.class);
intent.putExtra("key", finished);
startActivity(intent);
}
});
}
}
#Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
setIntent(intent);
displayIntentData();
}
private void displayIntentData()
{
Intent intent = getIntent();
TextView tv = (TextView)findViewById(R.id.intentData1);
Bundle extras=intent.getExtras();
if(extras!=null)
{
tv.setText("Data received: "+extras.getString("key"));
}
else
{
tv.setText("No extradata received");
}
}
}
After displayIntentData(); declare String getdata = get.getText().toString();
you are getting the value in the EditText field ("get") immediately after inflating the view. you couldn't have time to enter any text yet, so it is empty. you then check if "getData" contains "word" (it doesn't!) therefore you're hitting the ELSE.
We will get the text when any click event is happened ....
String getdata = get.getText().toString(); //Here i am getting Data from EditText
above code always return empty string ...
try put the code in on click event and process so that you can get the string and compare it easily
You are getting input data right after when the view is being created.
Instead try to take input data inside your click listener

Don't run function on onRestoreInstanceState

I am working on an app that when you go to a screen you select your location from a dialog which is created within onCreate. Once the location is selected it writes it into a predined TextView. A problem that I am having is when the screen orientation changes it recreates the dialog and I'm trying to have it not fire the dialog function.
Here is the basics of what I have within the class file.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emergpolice);
form_location = (TextView) findViewById(R.id.input_location);
if(form_location == null || form_location.getText().equals("")){
setLocation();
}
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putString("LOCATION", (String)form_location.getText());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
form_location.setText(savedInstanceState.getString("LOCATION"));
}
public void setLocation(){
db = new DatabaseHandler(this);
db.open();
final CharSequence[] locOpt = {getString(R.string.dialog_items_current_location),getString(R.string.dialog_items_home),getString(R.string.dialog_items_enter_manually)};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.header_choose_location));
builder.setSingleChoiceItems(locOpt, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item){
if(locOpt[item].equals(getString(R.string.dialog_items_home))){
Cursor cur = db.userInfo();
String address = cur.getString(cur.getColumnIndex("address"));
String city = cur.getString(7);
String county = cur.getString(8);
String state = cur.getString(9);
String zip = cur.getString(10);
db.close();
form_location.setText(address + ", " + city + ", " + county + ", " + state + ", " + zip);
}
if(locOpt[item].equals(getString(R.string.dialog_items_current_location))){
Toast.makeText(getApplicationContext(), locOpt[item], Toast.LENGTH_SHORT).show();
}
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
And the TextView in my layout is
<TextView
android:id="#+id/input_location"
android:layout_width="wrap_content"
android:layout_below="#+id/text_location"
android:layout_height="wrap_content"
android:text="" />
As far as firing setLocation() is have tried several scenarios to check the string length, whether null or not. When the screen changes it shows the original chosen location, but still fires the dialog.
You always call the method setLocation because each time the onCreate method of the Activity is called form_location.getText().equals("") will be true(because the TextView is recreated(and most likely you don't set text on it in the layout file)).
To avoid this, use the savedInstanceState of the onCreate method:
if (savedInstanceState == null){
// if savedInstanceState is null the activity is created for the first time
setLocation();
} else {
// if not null then the activity is recreated so restore the TextView text
form_location.setText(savedInstanceState.getString("LOCATION"));
}
You can set in the manifest file in the activity tag an attributed of configchange. If you set. The flag orientation than your activity will not be destroyed on every orientation change. So onceate will only be called once.

Categories

Resources