.setChecked() isn't setting the state of radio button - java

I'm creating a security settings part in my app.
There are 3 radio buttons that allow the user to choose between a passcode, TouchID or nothing. All radio buttons are unchecked by default. When clicking on a radio button (e.g. to use passcode), the code checks to see if the user has set up a passcode. If the user hasn't, a dialog is shown and the radio button remains unchecked. The user then goes and sets up a passcode (setUpPasscode button).
Once set up, the passcode activity closes with the return case '2' and the radio button with the passcode option should be checked. It isn't however. When I re-launch the application, the button is checked though. It somehow isn't checked immediately after finishing the previous activity but it is technically checked. What am I doing wrong?
public class SecuritySettings extends AppCompatActivity
{
TextView goBackToSettings;
Button setUpPasscode;
Button setUpTouchID;
RadioButton usePasscodeSelection;
RadioButton useTouchIDSelection;
RadioButton useNeitherSelection;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Dialog myDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.security_settings);
goBackToSettings = (TextView) findViewById(R.id.closeSettingsButtonID);
setUpPasscode = (Button) findViewById(R.id.setUpPasscodeButtonID);
setUpTouchID = (Button) findViewById(R.id.setUpTouchIDButtonID);
usePasscodeSelection = (RadioButton) findViewById(R.id.usePasscode);
useTouchIDSelection = (RadioButton) findViewById(R.id.useTouchID);
useNeitherSelection = (RadioButton) findViewById(R.id.useNothing);
myDialog = new Dialog(this);
//load state of radio buttons
loadRadioButtons();
// go back to main settings page
goBackToSettings.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent goBackToMainSettings = new Intent(getApplicationContext(), AppSettings.class);
goBackToMainSettings.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goBackToMainSettings);
finish();
}
});
//Open new activity for setting passcode
setUpPasscode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setUpPasscodeActivity = new Intent(getApplicationContext(), SetupPasscode.class);
startActivityForResult(setUpPasscodeActivity, 2);
}
});
// Open new activity for setting up TouchID
setUpTouchID.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setupTouchIDActivity = new Intent(getApplicationContext(), SetupTouchID.class);
startActivityForResult(setupTouchIDActivity, 1);
}
});
// when clicked, all other buttons become unchecked and the state of the buttons are saved
usePasscodeSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForPasscode = doesUserHavePasscode();
// If true, user has a passcode setup
if (bCheckForPasscode)
{
usePasscodeSelection.setChecked(true);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up a passcode to enable this option.");
}
}
});
useTouchIDSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForTouchID = doesUserHaveTouchIDSetup();
// If true, user has TouchID setup
if (bCheckForTouchID)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(true);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up TouchID to enable this option.");
}
}
});
useNeitherSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(true);
saveRadioButtons();
}
});
}
// Open sharedpreferences and get the value that was saved there after setting up passcode using the same key 'string'
public boolean doesUserHavePasscode()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
String checkHashString = sharedPreferences.getString("hashed_password", null);
if (checkHashString == null)
{
return false;
}
else
{
return true;
}
}
// Open sharedpreferences and get the value that was saved there after setting up TouchID using the same key 'string'
public boolean doesUserHaveTouchIDSetup()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
boolean bDoesUserHaveTouchIDSetup = sharedPreferences.getBoolean("doesUserHaveTouchIDSetup", false);
return bDoesUserHaveTouchIDSetup;
}
public void NoOptionSetPopup(View v, String message)
{
TextView closePopup;
TextView contents;
myDialog.setContentView(R.layout.no_option_setup_popup);
closePopup = (TextView) myDialog.findViewById(R.id.closePopupButtonID);
contents = (TextView) myDialog.findViewById(R.id.theMessageID);
contents.setText(message);
closePopup.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Close popup
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
myDialog.show();
}
// Callback method to get the boolean from SetupPasscode/SetupTouchID activity & override the method
// What is being done here is that after a passcode/TouchID has been setup, we automatically assume that the newly set-up authentication will want to be used by the user.
// The values being returned from the activities only happen when they're successfully done (passed all validation checks).
// We then automatically make the corresponding radio button selected (if passcode setup, then select the 'use passcode on startup' radio button)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
// Case for returning from SetupPasscode class
case 2:
// fetch the boolean value
boolean isDone = data.getBooleanExtra("isDone", false);
usePasscodeSelection.setChecked(isDone);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
// Case for returning from SetupTouchID class
case 1:
// fetch the boolean value
boolean isTouchIDSetup = data.getBooleanExtra("isTouchIDDone", false);
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(isTouchIDSetup);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
default:
throw new IllegalStateException("Unexpected value: " + requestCode);
}
}
public void saveRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = sharedPreferences.edit();
editor.putBoolean("usePasscodeOption", usePasscodeSelection.isChecked());
editor.putBoolean("useTouchIDOption", useTouchIDSelection.isChecked());
editor.putBoolean("useNeitherOption", useNeitherSelection.isChecked());
}
public void loadRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
usePasscodeSelection.setChecked(sharedPreferences.getBoolean("usePasscodeOption", false));
useTouchIDSelection.setChecked(sharedPreferences.getBoolean("useTouchIDOption", false));
useNeitherSelection.setChecked(sharedPreferences.getBoolean("useNeitherOption", false));
}
}

I would suggest to overload the onResume method and checking the state of your radio buttons as that will be the last control where the flow will leave your activity.

Related

How to save background color from another acivity in android java

I want to let users choose background colors with animation in BackgroundActivity and saving that changed background color into MainActivity.
When a user clicks backgroundChange button on MainActivity, it moves to BackgroundActivity. Then there are a few different colors to choose. After a user click Save button after choosing color on BackgroundActivity, it is going back to MainAcitivity. My problem is I don't know how to save that changed background color from BackgroundAcivity to MainAcivity.
As a beginner, I cannot understand well how to use SharedPreferences.
I checked several videos and searching many questions for hours about it, but still, I cannot figure out how to use SharedPreferences correctly on my own code.
BackgroundAcivity is really long that I will only put the first part. Could you tell me how to save this background change?
MainActivity
public class MainActivity extends AppCompatActivity {
Button backgroundChange;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backgroundChange = findViewById(R.id.backgroundChange);
backgroundChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BackgroundActivity.class);
startActivity(intent);
}
});
}
}
BackgroundActivity
public class BackgroundActivity extends AppCompatActivity {
Button btn_blue, btn_purple, btn_orange, btn_save;
View holderBg, dynamicBg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_background);
btn_save = findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BackgroundActivity.this, MainActivity.class);
startActivity(intent);
}
});
btn_blue = findViewById(R.id.btn_blue);
btn_purple = findViewById(R.id.btn_purple);
btn_orange = findViewById(R.id.btn_orange);
holderBg = findViewById(R.id.holderBg);
dynamicBg = findViewById(R.id.dynamicBg);
//set the first-time background
holderBg.setBackgroundResource(R.drawable.bg_blue);
holderBg.setScaleY(3);
holderBg.setScaleX(3);
//set the scale of button clicked
btn_blue.setScaleY(1.5f);
btn_blue.setScaleX(1.5f);
btn_blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//scale animation
btn_blue.animate().translationY(20).scaleX(1.5f).scaleY(1.5f).setDuration(800).start();
//default the scale buttons
btn_purple.animate().translationY(0).scaleX(1).scaleY(1).setDuration(350).start();
btn_orange.animate().translationY(0).scaleX(1).scaleY(1).setDuration(350).start();
//change the background
dynamicBg.animate().scaleX(3).scaleY(3).setDuration(800).start();
dynamicBg.setBackgroundResource(R.drawable.bg_blue);
//change color of button
btn_save.setTextColor(Color.parseColor("#3498db"));
//timer for change the holderbg
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
holderBg.setScaleX(3);
holderBg.setScaleY(3);
holderBg.setBackgroundResource(R.drawable.bg_blue);
dynamicBg.setScaleX(0);
dynamicBg.setScaleY(0);
}
}, 850);
}
});
}
}
You can use a bundle to transfer your data across Activity.
Saving data
Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, "your value here");
startActivity(intent);
Then to retrieve data.
Intent intent = getIntent();
if (intent != null ) { //Null Checking
String strData= intent.getStringExtra(KEY);
// do your work with `strData`
}

How can I persist the string/int value in EditText when i relaunch my application?

In my Android activity, I have one EditText, a '+' button, a '-' button, 'Save' button and 'Load' button. When I press '+', the value in EditText increases by 1, similarly on pressing '-' value decreases by 1. I used SharedPreferences to save the data when I click on 'Save'. When I click 'Load', I want to reload this data onto the EditText field.
Now the problem is, when I completely exit the application (even from recently used apps), and click 'Load' on relaunching it, the saved number doesn't appear. I included the onClick() action for the 'Load' method in onRestart() method. It still doesn't work. What am I missing here? I even tried out all other suggestions for the similar questions asked previously here.
Also, is it really onRestart() or onRestoreInstanceState() ?
public class MainActivity extends Activity {
Button btn1;
Button btn2;
Button btn3;
Button btn4;
EditText scoreText;
int counter = 0;
TextView textTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.add);
btn2 = (Button)findViewById(R.id.subtract);
btn3 = (Button)findViewById(R.id.save);
btn4 = (Button)findViewById(R.id.load);
scoreText = (EditText)findViewById(R.id.total);
textTitle = (TextView)findViewById(R.id.title);
btn1.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter=counter-1;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
//store data using sharedprefernces
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
//Edit method allow to write the data in sharedpreferences
editor.putString("count",scoreText.getText().toString());
//For commit changes commit() method is used
editor.commit();
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
}
});
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
// scoreText.setText(strcount);
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
#Override
protected void onRestart(Bundle savedInstanceState){
super.onRestart(savedInstanceState);
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
if (strcount.equals(""))
{
Toast.makeText(getApplicationContext(), "Data Was Not Found", Toast.LENGTH_SHORT).show();
}
else
{
scoreText.setText(strcount);
}
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
You using using count as key to save the value
editor.putString("count",scoreText.getText().toString());
but using name as key to retrieve the value so you need to use count key while getting the previously stored data so use
sharedPreferences.getString("count",scoreText.getText().toString());
instead of
sharedPreferences.getString("name",scoreText.getText().toString());
You are using different keys to save and retrieve the data from SharedPrefernces.
editor.putString("count",scoreText.getText().toString());
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
You should be using the same key in both the cases otherwise it would return default value which is the text in TextView and that would be empty at the start of the app, you just need to change the key and that would do the trick for you.
Just change the below line like it is mentioned
String strcount=sharedPreferences.getString("count",scoreText.getText().toString());

setText on button from another activity android

I have a problem, I want to click on the list, calling a new activity and rename the button to another name.
I tried several things, nothing worked, can someone please help me?
My class EditarTimes:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
CadastroTimes cad = new CadastroTimes();
CadastroTimes.salvar.setText("Alterar");
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
public class CadastroTimes extends AppCompatActivity {
private Time t;
private timeDatabase db;
private EditText edID;
private EditText edNome;
public Button salvar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro_times);
edID = (EditText) findViewById(R.id.edID);
edNome = (EditText) findViewById(R.id.edNome);
db = new timeDatabase(getApplicationContext());
salvar = (Button) findViewById(R.id.btnCadastrar);
salvar.setText("Cadastrar");
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("Alterar");
}
} else {
newString= (String) savedInstanceState.getSerializable("Alterar");
}
//button in CadastroTimes activity to have that String as text
System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
salvar.setText(newString);
}
public void salvarTime(View v) {
t = new Time();
t.setNome(edNome.getText().toString());
if (salvar.getText().equals("Alterar")) {
db.atualizar(t);
exibirMensagem("Time atualizado com sucesso!");
} else {
db.salvar(t);
exibirMensagem("Time cadastrado com sucesso!");
}
Intent intent = new Intent(this, EditarTimes.class);
startActivity(intent);
}
private void limparDados() {
edID.setText("");
edNome.setText("");
edNome.requestFocus();
}
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
public class EditarTimes extends AppCompatActivity {
private Time t;
private List<Time> times;
private timeDatabase db;
private ListView lvTimes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editar_times);
lvTimes = (ListView) findViewById(R.id.lvTimes);
lvTimes.setOnItemClickListener(selecionarTime);
lvTimes.setOnItemLongClickListener(excluirTime);
times = new ArrayList<Time>();
db = new timeDatabase(getApplicationContext());
atualizarLista();
}
private void excluirTime(final int idTime) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Excluir time?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Deseja excluir esse time?")
.setCancelable(false)
.setPositiveButton(getString(R.string.sim),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (db.deletar(idTime)) {
atualizarLista();
exibirMensagem(getString(R.string.msgExclusao));
} else {
exibirMensagem(getString(R.string.msgFalhaExclusao));
}
}
})
.setNegativeButton(getString(R.string.nao),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create();
builder.show();
atualizarLista();
}
private void atualizarLista() {
times = db.listAll();
if (times != null) {
if (times.size() > 0) {
TimeListAdapter tla = new TimeListAdapter(
getApplicationContext(), times);
lvTimes.setAdapter(tla);
}
}
}
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
t = times.get(pos);
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
String strName = "Alterar";
intent.putExtra("Alterar", strName);
startActivity(intent);
}
};
private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
excluirTime(times.get(pos).getId());
return true;
}
};
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public void telaCadastrar(View view) {
Intent intent = new Intent(this, CadastroTimes.class);
startActivity(intent);
}
public void botaoSair(View view) {
Intent intent = new Intent(this, TelaInicial.class);
startActivity(intent);
}
}
You can pass the button caption to CadastroTimes with intent as
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("buttontxt","Changed Text");
startActivity(intent);
Then in CadastroTimes.java set the text of the button to the new value that you passed. The code will look like:
button = (Button)findViewById(R.id.button); // This is your reference from the xml. button is my name, you might have your own id given already.
Bundle extras = getIntent().getExtras();
String value = ""; // You can do it in better and cleaner way
if (extras != null) {
value = extras.getString("buttontxt");
}
button.setText(value);
Do remember to do it in onCreate after setContentView
//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("change_tag", "text to change");
startActivity(intent);
//To Activity
public void onCreate(..){
Button changeButton = (Button)findViewById(R.id.your_button);
// Button to set received text
Intent intent = getIntent();
if(null != intent &&
!TextUtils.isEmpty(intent.getStringExtra("change_tag"))) {
String changeText = intent.getStringExtra("change_tag");
// Extracting sent text from intent
changeButton.setText(changeText);
// Setting received text on Button
}
}
1: Use intent.putExtra() to share a value from one activity another activity, as:
In ActivityOne.class :
startActivity(
Intent(
applicationContext,
ActivityTwo::class.java
).putExtra(
"key",
"value"
)
)
In ActivityTwo.class :
var value = ""
if (intent.hasExtra("key")
value = intent.getStringExtra("key")
2: Modify button text programatically as:
btn_object.text = value
Hope this will help you
For changing the button text:
Use a static method to call from the other activity to directly modify the button caption.
Use an intent functionality, which is preferable.
Use an Interface and implement it, which is used for communicating between activities or fragment in a manner of fire and forget principle.
Now, i got you:
Your EditarTimes activity with listview:
//set setOnItemClickListener
youtListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(EditarTimes.this, CadastroTimes.class);
//text which you want to display on the button to CadastroTimes activity
String strName = "hello button";
i.putExtra("STRING_I_NEED", strName);
}
});
In CadastroTimes activity,
under onCreate() method, get the text string as:-
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
//button in CadastroTimes activity to have that String as text
yourButton.setText(newString);
Ok, so the first step would be to take the button you want and make it a public static object (and put it at the top of the class).
public static Button button;
Then you can manipulate that using this in another class:
ClassName.button.setText("My Button");
In your case it is
CadastroTimes.salvar.setText("Alterar");
if you want to change value from that do not do not go the activity via intent you can use file to save value to file or you have multiple values the use database and access
the value oncreate to set the value of text....
In my case, I had to send an EditText value from a Dialog styled Activity, which then got retrieved from a Service.. My Example is similar to some of the above answers, which are also viable.
TimerActivity.class
public void buttonClick_timerOK(View view) {
// Identify the (EditText) for reference:
EditText editText_timerValue;
editText_timerValue = (EditText) findViewById(R.id.et_timerValue);
// Required 'if' statement (to avoid NullPointerException):
if (editText_timerValue != null) {
// Continue with Button code..
// Convert value of the (EditText) to a (String)
String string_timerValue;
string_timerValue = editText_timerValue.getText().toString();
// Declare Intent for starting the Service
Intent intent = new Intent(this, TimerService.class);
// Add Intent-Extras as data from (EditText)
intent.putExtra("TIMER_VALUE", string_timerValue);
// Start Service
startService(intent);
// Close current Activity
finish();
} else {
Toast.makeText(TimerActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
}
}
And then inside my Service class, I retrieved the value, and use it inside onStartCommand.
TimerService.class
// Retrieve the user-data from (EditText) in TimerActivity
intent.getStringExtra("TIMER_VALUE"); // IS THIS NEEDED, SINCE ITS ASSIGNED TO A STRING BELOW TOO?
// Assign a String value to the (EditText) value you retrieved..
String timerValue;
timerValue = intent.getStringExtra("TIMER_VALUE");
// You can also convert the String to an int, if needed.
// Now you can reference "timerValue" for the value anywhere in the class you choose.
Hopefully my contribution helps!
Happy coding!
Accessing view reference of another Activity is a bad practice. Because there is no guarantee if the reference is still around by the time you access it (considering the null reference risk).
What you need to do is to make your other Activity read values (which you want to display) from a data source (e.g. persistence storage or shared preferences), and the other Activity manipulates these values. So it appears as if it changes the value of another activity, but in reality it takes values from a data source.
Using SharedPreferences:
Note: SharedPreferences saves data in the app if you close it but it will be lost when it has been deleted.
In EditarTimes.java:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
SharedPreferences.Editor editor = getSharedPreferences("DATA", MODE_PRIVATE).edit();
editor.putString("btnText", "Your desired text");
editor.apply();
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
In CadastroTimes.java
public Button salvar;
salvar.setText(getSharedPreferences("DATA", MODE_PRIVATE).getString("btnText", ""));
//note that default value should be blank
As far as my thoughts go, I can realize that the problem is not with the code you provided as it seems to be implemented correctly. It is possible that you have saved the activityState somewhere in your actual code and because it is not implemented properly, the savedInstanceState found in the onCreate method is not null but the required information is missing or not correct. That's why newString is getting null and salvar textview is getting blank.
Here, I need to know which one is more useful to you - information from getIntent() or from savedInstanceState? The code you provided insists me to assume that savedInstanceState has got the preference.
If you prefer savedInstanceState, then you may use SharedPreferences like this to get the same value you want:
private SharedPreferences mPrefs;
private String newString;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from preference
mPrefs = getSharedPreferences("MyData", MODE_PRIVATE);
newString = mPrefs.getString("alterarValue", "");
if (newString.equals("")){
// we have not received the value
// move forward to get it from bundle
newString = getIntent().getStringExtra("Alterar");
}
// now show it in salvar
salvar.setText(newString);
}
protected void onPause() {
super.onPause();
// you may save activity state or other info in this way
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("alterarValue", newString);
ed.commit();
}
Or if you don't need to get it from savedInstanceState, please use it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from bundle
String newString = getIntent().getStringExtra("Alterar");
// now show it in salvar
salvar.setText(newString);
}
That's all I know. Hope it will help. If anything goes wrong, please let me know.

How to clear the intent text?

I have a reset button in Activity A and it works fine since it can clear all the text and display null when the save button in Activity B is clicked. But this only works if there are nothing in the textView before pass to B.
It does not works in below cases.
In Activity A, type " Project 123', click next button go to B. Then I back to Activity A again and click the reset button to clear "Project 123". After done go to Activity B and click submit button. It shows "Project 123" instead of "null"...
Activity A
private TextView c;
String result; // 123
String name; // project
reset=(Button)claims.findViewById(R.id.button14); // reset button
Button button = (Button) claims.findViewById(R.id.button8); //next button
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.setText("");
d.setText("");
e.setText("");
f.setText("");
g.setText("");
h.setText("");
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), B.class);
if(c!=null){
intent.putExtra("name", name);
intent.putExtra("result", result);
}
});
return A;
}
Activity B
Name=getIntent().getExtras().getString("name");
Result=getIntent().getExtras().getString("result");
save=(Button)findViewById(R.id.button8);
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if((Name!=null)&&(Result!=null)){
Toast.makeText(getApplicationContext(), Name+Result, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"null", Toast.LENGTH_LONG).show();
}
}
});
This is because you only clear the setText but not the string.
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.setText("");
name="";
result="";
}
});
You have to add name="" and result="" in your reset method. It should works.
Kindly refer clear a value from a string android
Actually, the name is not null but with empty string ""
Try to take replace the Name != null with !TextUtils.isEmpty() in B activity.

I am not allowed to pass a string from resource file within a switch case [Android]

I have few buttons and I have the following click listener for the same:
private View.OnClickListener onclick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.home:
break;
case R.id.contact:
break;
case R.id.terms:
break;
case R.id.touch:
show(R.string.about_us); //Error here
break;
}
}
};
On each button click I display the same popup, only the text differs. I have text in strings.xml file
below is my dialog function:
public void show(String message){
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.terms);
//dialog.setTitle("Terms & Conditions");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText(message);
text.setTypeface(helv_light);
ImageButton dialogButton = (ImageButton) dialog.findViewById(R.id.button1);
// dialogButton.setTypeface(helv_light);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
in case R.id.touch: My IDE complains with the following message:
show(java.lang.string) cannot be applied to (int).
If I replace show(R.string.about_us); with show(""+R.string.about_us); The error goes away, what do I miss here?
Use getResources().getString for getting string from strings.xml :
show(v.getContext().getResources().getString(R.string.about_us));
R.string.about_us is an int value, is not a string. To keep both you can overload show, providing the integer parameter, and call
public void show(final int messageId) {
sendMessage(getResources().getString(messageId));
}
The R.string.* values are ints. You need to use getResources().getString(R.string.str_id) to get the actual string value.

Categories