Android EditText Value Error? - java

I'm testing out some stuff on android as a beginner and was trying to grab value entered in a EditText when a button was clicked , then compare it to a string value that I defined inside the class, then use if (EditText == stringDefined) else () , but my code always jumps on the else part even if the correct text is entered, any help is appreciated. Here is the code :
Button mButton;
EditText mEdit1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final String user = "admin";
mButton = (Button)findViewById(R.id.BTN_login);
mEdit1 = (EditText)findViewById(R.id.editText1);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
String userEntered = mEdit1.getText().toString().trim();
Intent intent = new Intent(Login.this, Success.class);
if(userEntered == user){
startActivity(intent);
}
else{
AlertDialog.Builder errAlert = new AlertDialog.Builder(Login.this);
errAlert.setTitle("Wrong Credentials");
errAlert.setMessage("Wrong username");
errAlert.setCancelable(true);
errAlert.show();
}
}
});
}

Use equals method :
if(userEntered.equals(user)){
startActivity(intent);
}

== is used to compare primitive types and equals() method of java.lang.String class compares contents.

Related

Opening another activity based on number of filled editTexts

The app has a MainActivity with 6 editText fields, and a button. There are 5 more activities, named Activity2, Activity3, etc. Now, When a user enters names in editText fields, and press a button, the app should find out how many editText fields are filled, and open the activity with a corresponding number in it's name.
Example:
If only one field is filled, a toast should appear, saying More players.
If two fields are filled, app opens Activity2.
If three fields are filled, app opens Activity3, etc.
Now, to the problem. I am missing something out, and can't find out what. Here is MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText editText1,editText2,editText3,editText4,editText5,editText6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btn);
editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
editText3 = findViewById(R.id.editText3);
editText4 = findViewById(R.id.editText4);
editText5 = findViewById(R.id.editText5);
editText6 = findViewById(R.id.editText6);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = MainActivity.class;
switch (filledFileds){
case 1:
Context context = getApplicationContext();
CharSequence text = "You need more players!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
case 2:
newClass = Activity2.class;
System.out.println("Activity2");
break;
case 3:
newClass = Activity3.class;
System.out.println("Activity3");
break;
case 4:
newClass = Activity4.class;
System.out.println("Activity4");
break;
case 5:
newClass = Activity5.class;
System.out.println("Activity5");
break;
case 6:
newClass = Activity6.class;
System.out.println("Activity6");
break;
default:
}
Intent intent = new Intent(MainActivity.this, newClass);
}
});
}
private int countFilledFields() {
ArrayList<EditText> editTexts = new ArrayList<>();
editTexts.add(editText1);
editTexts.add(editText2);
editTexts.add(editText3);
editTexts.add(editText4);
editTexts.add(editText5);
editTexts.add(editText6);
int filledNumber = 0;
for(int i = 0;i < editTexts.size() ;i++){
if(editTexts.get(i).getText()!=null && !editTexts.get(i).getText().toString().matches("")){
filledNumber += 1;
}
}
return filledNumber;
}
}
The log shows the exact number, something is not working...
Here is your click listener, with the switch omitted for brevity:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = MainActivity.class;
switch (filledFileds){
...
}
Intent intent = new Intent(MainActivity.this, newClass);
}
The problem is at the very end: you've created an Intent object ... but you're not doing anything with it. Probably you have just forgotten a startActivity() call:
Intent intent = new Intent(MainActivity.this, newClass);
startActivity(intent);
Also, looking this over, you have a problem with the case where the user only enters one EditText. As written, you'll still try to start a new activity (you'll just start a new copy of the same MainActivity, which is probably a bad idea). A better idea would be to only start the new activity if the user fills out enough EditTexts:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int filledFileds = countFilledFields();
Log.d("filled", String.valueOf(filledFileds));
Class newClass = null;
switch (filledFileds){
...
}
if (newClass != null) {
Intent intent = new Intent(MainActivity.this, newClass);
startActivity(intent);
}
}
You're missing one thing:
startActivity(intent);

Android app crashes when trying to use variable [duplicate]

#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.screenlocked);
//Retrieve stored ID
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
LoginID = unique.getString("identifier", "");
//Retrieve stored phone number
final String phoneNumber = unique.getString("PhoneNumber", "");
phoneView = (TextView) findViewById(R.id.phone);
phoneView.setText(phoneNumber.toString());
//Retrieve user input
input = (EditText) findViewById(R.id.editText1);
userInput = input.getText().toString();
//Set login button
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
compareID();
}
});
}
public void compareID(){
if (userInput.equals(LoginID)){
//phone screen unlocked
//continue
Toast.makeText(ScreenLockActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
else{
count += 1;
input.setText("");
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
}
}
I am developing a login activity and I would like to record down how many times the user tried to login, so every time there is a login attempt the count will increment by one... but when i run the activity, this error appears in my logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1,
Can someone help me solve this problem?
Here is your mistake:
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
the makeText you are trying to invoke here, is the makeText that takes as second parameter a resId. See here for more info. Since you want to print the count value, you have to convert it in a String.
String value = String.valueOf(count);
Toast.makeText(ScreenLockActivity.this, value, Toast.LENGTH_SHORT).show();
This line should be inside onClick() or compareID():
userInput = input.getText().toString();

Android: How can I keep empty EditText fields out of a randomized count?

I am working on this Android app that has five EditText fields in the first activity.
Users can fill out any of the EditText fields they want and after pressing a Button, they'll get a randomized answer on a single TextView in the second activity.
For example, if the user fills out 2 EditText fields, the empty ones are still part of the random count.
Also, whenever a user fills out random EditText fields (an example: choiceThree and choiceFour), nothing gets passed to the second activity.
Can anyone help me? Thanks!
Here's the code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText choiceOne;
EditText choiceTwo;
EditText choiceThree;
EditText choiceFour;
EditText choiceFive;
Button mainButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
choiceOne = (EditText) findViewById(R.id.inputOne);
choiceTwo = (EditText) findViewById(R.id.inputTwo);
choiceThree = (EditText) findViewById(R.id.inputThree);
choiceFour = (EditText) findViewById(R.id.inputFour);
choiceFive = (EditText) findViewById(R.id.inputFive);
mainButton = (Button) findViewById(R.id.inputButton);
mainButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onClick(View view)
{
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
if(choiceOne.getText().toString() != null && !choiceOne.getText().toString().trim().equals(""))
{
intent.putExtra("choiceOne", choiceOne.getText().toString());
}
if(choiceTwo.getText().toString() != null && !choiceTwo.getText().toString().trim().equals(""))
{
intent.putExtra("choiceTwo", choiceTwo.getText().toString());
}
if(choiceThree.getText().toString() != null && !choiceThree.getText().toString().trim().equals(""))
{
intent.putExtra("choiceThree", choiceThree.getText().toString());
}
if(choiceFour.getText().toString() != null && !choiceFour.getText().toString().trim().equals(""))
{
intent.putExtra("choiceFour", choiceFour.getText().toString());
}
if(choiceFive.getText().toString() != null && !choiceFive.getText().toString().trim().equals(""))
{
intent.putExtra("choiceFive", choiceFive.getText().toString());
}
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
SecondActivity.java
public class SecondActivity extends Activity {
TextView answerDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
answerDisplay = (TextView) findViewById(R.id.display);
Intent intent = getIntent();
String[] choice = {intent.getStringExtra("choiceOne"), intent.getStringExtra("choiceTwo"),
intent.getStringExtra("choiceThree"), intent.getStringExtra("choiceFour"),
intent.getStringExtra("choiceFive")};
int choiceRandom = (int) (Math.random()*intent.getExtras().size());
answerDisplay.setText(choice[choiceRandom]);
}
When no input is there in an EditText, it doesnt return getText as null, but as "".
And in MainActivity, work with an ArrayList instead of an array.. gives you the option to use the various methods including add and remove.
String choiceX = intent.getStringExtra("choiceX");
if(!choiceX.equals("")) {
choice.add(choiceX);
}
for each of the choices. This is the best and easiest way i can see.. :)
Just check if the String you are getting from the Intent is not equal to ""
if(!intent.getStringExtra("choiceOne).equals(""))
and add only the Strings that are not empty to your String Array. Then you have to get your random number based on how many Strings there are in your Array, by calling choice.length.
put a check in your onClick method for each choice, only then save the value in intent.putExtra()
if(choiceX.getText().toString() != null && !choiceX.getText().toString().trim().equals("")) {
intent.putExtra("choiceX", choiceX.getText().toString());
}
and then instead of doing Math.random*5, use Math.random*intent.getExtras().size()

Android - Change class variable before onCreate

I am new to Android development. I am trying to call a method of one of my classes when a button on my main activity is pressed.
On my Main Activity I have this button:
public void buttonTest(){
Button b = (Button) findViewById(R.id.test);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String s = "changeText:myText";
Intent in = new Intent(PlusActivity.this, Test.class);
in.putExtra("method",s);
startActivity(in);
}
});
}
And here is is the class (without imports) which that intent above is calling to.
public class Test extends Activity {
static String text = "test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
TextView mTextView = (TextView) findViewById(R.id.textView);
mTextView.setText(text);
}
public void changeText(String s){
this.text = s;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String[] array = intent.getStringExtra("method").split(":");
if(array[0].equals("changeText")){
changeText(array[1]);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}
Basically I want to know if it is possible to change the value of that String text, before onCreate(). Basically each button will have a correspondent text, and I want to be able to modify that text based on which button.
If it is, what should I do/change?
Thanks in advance.
The right way to do it is to send the string you want it to be as an extra in the intent, and to read the extra from the intent and assign it to that variable in the onCreate function.
Use SharedPreference. Save in OnCLick of first class and retrieve in OnCreate of second class.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes
String text;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
text= null;
} else {
text= extras.getString("your default string message");
}
} else {
String s = "your default string message";
text= (String) savedInstanceState.getSerializable(s);
}

Checking username and password in Android

I have a username and password field and now i need to check and redirect him to the next page in Android.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText loginText = (EditText) findViewById(R.id.widget44);
final EditText loginPassword = (EditText) findViewById(R.id.widget47);
final Button button = (Button) findViewById(R.id.widget48);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = null;
if(loginText.getText().equals("admin") &&
loginPassword.getText().equals("admin")) {
System.out.println("Entering");
myIntent = new Intent(view.getContext(), Page1.class);
} else {
}
startActivity(myIntent);
}
});
}
Temp now i am checking by hardcoding the values, but this too does not work for me. Why? I usually check in Java like this, why does it not accept me the same way in Android
I think it's because EditText#getText() returns an Editable object. Try
if(loginText.getText().toString().equals("admin") &&
loginPassword.getText().toString().equals("admin")) {
...
}
Don't you need to put toString() to your textelements?
Like this:
if(loginText.getText().toString().equals("admin") &&
loginPassword.getText().toString().equals("admin")) {
...
Edit: neutrino was faster (+1) :)
I am finding only a small problem. In your code, correct it as shown below, and I think it will work:
if(loginText.getText().**toString()**.equals("admin") &&
loginPassword.getText()**.toString()**.equals("admin")) {
System.out.println("Entering");
myIntent = new Intent(view.getContext(), Page1.class);
} else {
...
}
See the correction in asterisks.

Categories

Resources