I have the following code which I want to use to make sure that my edittext wont be empty. So if the first drawn 0 (zero) is removed it must revert to 0 when the focus changes, Here is the app so far:
package your.test.two;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class TesttwoActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText edtxt = (EditText)findViewById(R.id.editText1);
// if I don't add the following the app crashes (obviously):
edtxt.setText("0");
edtxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
update();
}
});
}
public void update() {
EditText edittxt = (EditText)findViewById(R.id.editText1);
Integer i = Integer.parseInt(edittxt.getText().toString());
// If i is an empty value, app crashes so if I erase the zero
//on the phone and change focus, the app crashes
}
}
I have tried the following in the update() method:
String str = edittxt.getText().toString();
if (str == "") {
edittxt.setText("0");
}
But it doesn't work. How can I allow the edittext to never be emty, revert to zero when empty but not when a value exists. I have already made sure that the edittext can only allow numerical values.
if(str.equals("")){
edittxt.setText("0");
}
WarrenFaith is right. Refer to this post to learn more about this issue: Java String.equals versus ==
I would recommend surrounding your parseInt call with a try/catch block that catches a NumberFormatException which is probably the error being thrown (since you didn't specify, I can only guess), so it looks like:
public void update() {
EditText edittxt = (EditText)findViewById(R.id.editText1);
Integer i;
try {
i = Integer.parseInt(edittxt.getText().toString());
// do something with i
} catch (NumberFormatException e) {
// log and do something else like notify the user or set i to a default value
}
}
Related
I have set to break on both read and write to a field, as shown below:
The problem is that the code never breaks when the field was access/modified when I know for a fact that the field was being accessed, and that breakpoints set in methods work as intended. How do I make it work?
Maybe you can try this: it's not a perfect solution, but a compromise one.
public class MainActivity extends Activity {
private boolean value = test();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (value) {
// do sth.
value = false;
}
}
private boolean test() {
return false;
}
}
create break point at return false line. But you may want to delete the extra code when the debugging is done.
I've got the following code (it's not the full code, but the rest doesn't matter). I'm trying to set the boolean "ignoreLength" to either true or false based on what the user picks in an Alertdialog. However, when the code is like this, I get this error:
"Cannot refer to a non-final variable ignoreLength inside an inner class defined in a different method"
When I make it final, it changes to this:
"The final local variable ignoreLength cannot be assigned, since it is defined in an enclosing type"
How can I make it so I can change ignoreLength?
package com.grawl.passgen;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class PassGenActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// Interface -- Default
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Interface -- Custom
final Button button_generate = (Button) findViewById(R.id.button_generate);
final EditText text_pass = (EditText) findViewById(R.id.textPassWord);
final EditText edit_length = (EditText) findViewById(R.id.editLength);
// Set up Arrays
final String[] lowerCase;
final String[] upperCase;
final String[] numbers;
final String[] symbols;
// Fill Arrays
createArray characters = new createArray();
lowerCase = characters.getArrayLower();
upperCase = characters.getArrayUpper();
numbers = characters.getArrayNumbers();
symbols = characters.getArraySymbols();
// Pressing the button WOOOSH!
button_generate.setOnClickListener(new View.OnClickListener() {
**boolean ignoreLength = false;**
public void onClick(View v) {
// Set up parameters
boolean lowerCaseEnabled = true; // needs interface option
boolean upperCaseEnabled = true; // needs interface option
boolean numbersEnabled = true; // needs interface option
boolean symbolsEnabled = true; // needs interface option
// Set up length based on input from EditText
int length = 0;
try {
length = Integer.parseInt(edit_length.getText().toString());
} catch(NumberFormatException nfe) {
Toast.makeText(PassGenActivity.this, "Can't parse " + nfe, Toast.LENGTH_LONG).show();
}
if (length < 1) {
length = 1;
edit_length.setText("1");
Toast.makeText(PassGenActivity.this, "Password length can't be less than 1, set it to 1.", Toast.LENGTH_LONG).show();
};
if (length > 100) {
AlertDialog.Builder alert = new AlertDialog.Builder(PassGenActivity.this);
alert.setTitle("Warning");
alert.setMessage("You are trying to create quite a long password, are you sure?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
ignoreLength = true;
}
});
alert.setNegativeButton("No", null);
alert.show();
}
Password password = new Password();
password.fillPassword(lowerCase, upperCase, numbers, symbols);
// Generate password
password.setPassword(lowerCaseEnabled, upperCaseEnabled, numbersEnabled, symbolsEnabled, length);
text_pass.setText(password.getPassword());
}
});
}
}
Firstly as per your question.
"Can't change final variable inside AlertDialog" is wrong.
As making you clear that a final variable can never be changed as it's final and already declared at the time of creation.
Also in you case boolean ignoreLength = false; declare the variable outside and before the click listener and do not make it final. As you need to update ignoreLength value in future.
You can't reassign local variables in java from an inner type. More here.
There are two ways to solve your problem.
1) Make ignore case a field on something--you could actually use the anonymous OnClickListener type, and give it the ignoreLength field, but I think generally you would want it to be a field on the top level class
2)
<superuglyhack>
final boolean[] ignoreLengthHolder= new boolean[]{ false };
...
ignoreLengthHolder[0] = true
</superuglyhack>
You could move the boolean ignoreLength; declaration outside of the onClick to make it a member variable of the anonymous OnClickListener class.
Also, you could put the variable in something that holds it (like an array with one item) and update it that way. ignoreLength[0] = true;
package com.russell.saw;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class learnandroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button landroid_button = (Button) findViewById(R.id.landroid_button); {
landroid_button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.button);
}
});
}
Button back_button = (Button) findViewById(R.id.back_button); {
back_button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.main);
}
});
}
}
}
i'm unsure of what is going wrong, it's just a simple learning tester app, with two buttons, going from one page to another, but i get a crash as soon as i run it on the phone.
Woah! You have your onClickListeners set up all wrong. You are calling setContentView in the onClickListeners. Instead, you need to use an intent to go from one activity to the next. It needs to look like this:
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main.this, MyOtherActivity.class);
startActivity(intent);
}
});
Also, don't use landroid_button to reference your button: that's just the XML ID of the resource. Instead you need to grab hold of your button by doing something like this:
Button myLandroidButton = (Button)findViewById(R.id.landroid_button)
Then when you set up the onClickListener, use that variable: myLandroidButton like myLandroidButton.setOnClickListener and so on..
If you haven't added an activity tag to AndroidManifest.xml, you will need to do so:
<activity android:name="learnandroid" android:label="I am learning Android"></activity>
You need to do this for each activity (underneath the application tag).
Although I doubt that this is causing the crash, your code has a serious problem. When you call setContentView inside onClick in your listeners, the buttons landroid_button and back_button are no longer valid. That is, they are objects that are no longer tied to a window. (If the new content views have "the same" buttons, they no longer have listeners.)
I am trying to set a breakpoint inside an Activity class:
public class MainActivity extends Activity {
private EditText htmlContent = null;
private Button getBtn = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // <<<< this is where I set a breakpoint
htmlContent = (EditText)findViewById(R.id.htmlContent);
getBtn = (Button)findViewById(R.id.get);
// anonymous inner class implementing OnClickListener
getBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// fill htmlContent using HTTP GET
try {
final TestHttpGet thgObj = new TestHttpGet();
thgObj.executeHttpGet();
}
catch (Exception e){
// do something meaningful here
}
}});
// start some activity here?
getBtn.setEnabled(true);
}
}
Now, the funny thing is that this program runs and I can even see its layout screen in the emulator, but when I click the getBtn nothing happens, and so I tried to set a breakpoint inside to see why.
The amazing thing is... No breakpoint is ever reached - even if I set it on the first statement in OnCreate(). How is this possible???
Maybe mine is a stupid question, but... Are you running the program normally? or using the debug button?
I created this Sign-In page. I start by declaring variables for username/password & buttons. If user enters "test" as username & "test" as password and hits the login button, its supposed to go to the DrinksTwitter.class activity, else throw error message I created. To me the code and login makes perfect sense. I'm not sure why it wont go to the next activity I want it to go to
package com.android.drinksonme;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Screen2 extends Activity {
// Declare our Views, so we can access them later
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnSignUp;
private TextView lblResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.username);
etPassword = (EditText)findViewById(R.id.password);
btnLogin = (Button)findViewById(R.id.login_button);
btnSignUp = (Button)findViewById(R.id.signup_button);
lblResult = (TextView)findViewById(R.id.result);
// Check Login
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if(username.equals("test") && password.equals("test")){
final Intent i = new Intent(Screen2.this, DrinksTwitter.class);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(i);
}
// lblResult.setText("Login successful.");
else { /* ERROR- Syntax error on token "else", { expected */
lblResult.setText("Invalid username or password.");
}
}
});
final Intent k = new Intent(Screen2.this, SignUp.class);
btnSignUp.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(k);
}
}); /* ERROR- Syntax error, insert "}" to complete Statement*/
}
}
I only briefly looked at your code, but I don't understand what you're doing (in that order).
You're checking the password & username on the OnCreate method, which, barring any autofilling, the textboxes will be blank.
Then you declare your onClickListeners.
Try restructuring it to be something like this (pseudo-code):
OnCreate
user = usertextbox
pass = passtextbox
login.setOnClick
if user == validUsername && pass == validPass
Intent i = new Intent(blah.this, blah.class)
startActivity(i)
else
Intent i = new Intent(blah.this, login.class)
startActivity(i)
This is how I have my app's login screen.
In short, you have to make the check occur in the OnClickListener of the action button, not in the OnCreate method of the activity. The way it is now, the form is created, and the textboxes are blank. Then immediately afterwards, they're compared against some values. That call will always fail to execute, so all of the code in your If statement scope will be ignored indefinitely.
Also, the reason Eclipse is giving you that error is because you're trying to place an else statement inside of a class definition.
When you declare a new OnClickListener() { }, you're essentially declaring a class. So you're in the class scope, not the if scope.
That would be like trying to do:
class test {
else {
doStuff();
}
}
I'm almost positive your problem is in setting an onClick() call instead of just starting the activity. It seems a bit complex of a call, and I think you're already checking the conditions in the appropriate place. Why do you need another onClick() call?
You should indent your code correctly. That syntax error is because you don't have a closing brace around the btnLogin.setOnClickListener. You then miss at least a couple more closing brackets.
Also, as others have posted, you check the edittext value before the onCreate() method even gives up control to the UI.
You set the button's click listener only if the strings match.
To me the code and login makes perfect
sense
You should slow down and take a look more carefully. It can't possibly make perfect is sense if there's syntax errors.