How to clear the intent text? - java

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.

Related

Android Studio back button activity

I've been trying to find out the back navigation button to lead to another activity.
Every time when I pressed the back button, it goes to the previous activity which is not what I want. I would like to set the back button that goes to another activity I want, instead of previous one.
For example, I have Activity 1, 2 and 3. I was in Activity 2 and just moved to Activity 3. But when I press the back button, it goes automatically to the previous activity which is Activity 2. I want to make it to Activity 1 and not Activity 2. Can anyone suggest me a solution please?
You can make the button to go to a specific activity, instead of having the default behavior that you described.
It can be something like this:
#Override
public void onClick(View v) {
Intent intent = new Intent(Activity2.this, Activity3.class);
intent.putExtra("variable", information); //this is optional, but can be useful if you need to send a specific info to the next activity
startActivity(intent);
}
Activity 2 is parliamonar, and Activity 3 is federalparliamentary. I replaced parliamonar with Activity 1, but it still didn't solve the problem.
public class federalparliamentary extends AppCompatActivity {
Button federal;
private Object parliamonar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_federalparliamentary);
federal = findViewById(R.id.back160);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), parliamonar.class);
startActivity(reserve);
}
});
federal = findViewById(R.id.next164);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), sar.class);
startActivity(reserve);
}
});
}
public void onClick(View V) {
Intent back = new Intent((Context) parliamonar, federalparliamentary.class);
startActivity(back);
}
}
public class federalparliamentary extends AppCompatActivity {
Button federal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_federalparliamentary);
federal = findViewById(R.id.back160);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), parliamonar.class);
startActivity(reserve);
}
});
federal = findViewById(R.id.next164);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), sar.class);
startActivity(reserve);
}
});
}
public void Onclick(View v) {
Intent intent = new Intent(federalparliamentary.this, politicalsystem.class);
startActivity(intent);
}
}
Activity 1 is "politicalsystem".
I added with #Override method, but it says that I have to remove the method, so I added outside, then it says that I have to extract interface, so clicked on it, then it gave me a bunch of list. So I chose onClick(v:View ):void, but it still didn't solve the issue. I tried in another way without #Override, but nothing changed when I tested my app. I also tried inside onCreate method which did not modified the navigation as I desired.

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

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.

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());

Password - String comparison

My app consists of an Activity, which asks for a String password, in order to launch a second Activity. I am using an EditText for input and a Button for verification. If the Button is pressed, the app should check whether the inserted password, (let's assume it's "ABC") matches the password in the array. If not, set the inserted password to a red color.
public class Login extends AppCompatActivity{
Button mButton;
EditText mEdit;
String [] mArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mButton = (Button)findViewById(R.id.anmelden_button);
mEdit = (EditText)findViewById(R.id.password);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
String [] mArray = getResources().getStringArray(R.array.password);
if (mArray.equals(mEdit.getText().toString())){
Intent intent = new Intent(this, secondactivity.class);
startActivity(intent);
}else{
mEdit.setTextColor(Color.RED);
}
}
}
My problem is, that when I insert "ABC" and press the Button, nothing happens at all.
You need to loop through all the passwords first, then check to see if you found what you wanted.
Your onclick listener should something look like this:
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String [] mArray = getResources().getStringArray(R.array.password);
// loop to check all passwords
for (String s : mArray) {
if (s.equals(mEdit.getText().toString())) {
// found the password
Intent intent = new Intent(this, secondactivity.class);
startActivity(intent);
return;
}
}
mEdit.setTextColor(Color.RED);
}
});
Put your password checking code inside the onClickListener
Loop through each element of the array, checking it against the value in your EditText

How to get information about a button click on 1st activity and use it in the 3rd activity? - android

well there are 3 activities say Act1, Act2 and Act3.
in Act1 there are three buttons say But1, But2 and But3.
if we click any of the 3 three buttons it will end up showing Act2.
in Act2 there is only one button say Done.
my problem is when i click on the button Done in Act2 i should get the information about the button which is clicked in Act1 to show Act2 in a TextView in Act3.
i think i have made it clear..
i just need to know how to pass the information of the button click in Act1 to Act3
should i use bundles or something else? pls help me out with the logic and if possible a sample code? :)
You have a few options.
1) The Hardcore option would be to create a database and save / query the information.
2) You could also write to sharedPreferences.
SharedPrefExample
3) As was mentioned in the comment, if your only talking from one activity to another you can just intent.putExtra("key", value)
4) Lastly you can extend Application
Here is a good post that deals with global variables. How to declare global variables in Android?
Try to Use Intent
public void onClick(View arg0) {
Bundle bundle = new Bundle();
bundle.putInt("BtnAID", ID);
Intent It = new Intent();
It.setClass(A.this, B.class);
It.putExtras(bundle);
startActivity(It);
}
You can use SharedPreferences to store which button was pressed.
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
prefsEditor.putString("buttonPressed", "Button1");
prefsEditor.commit();
}
});
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
prefsEditor.putString("buttonPressed", "Button2");
prefsEditor.commit();
}
});
Button b3 = (Button) findViewById(R.id.button3);
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
prefsEditor.putString("buttonPressed", "Button3");
prefsEditor.commit();
}
});
And in the Activity in which you want to fetch which button was pressed:
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String whichButton = appSharedPrefs.getString("buttonPressed", "");
if(whichButton.equals("Button1")
//do something
if(whichButton.equals("Button2")
//do something
if(whichButton.equals("Button3")
//do something

Categories