#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();
Related
I am completely lost and don't have enough knowledge on coding/android studio.
I have the EditTexts (FoodIncomeCounter, FoodCampX, and FoodUpgradeX) as inputs.
Then the TextView (FoodIncomeResult) as output.
The 1st button (IncomeSubmitButton) Works properly. The 2nd button (FoodCampSubmitButton) does not, I want it to take the input of the FoodCampXs and FoodUpgradeXs then do a calculation and put that into integer TotalFood, then output TotalFood to the FoodIncomeResult TextView.
How the heck do I do this? I feel like I am close but I don't know what is wrong.
Thank you for the help!!!
public class MainActivity extends AppCompatActivity {
// These are the global variables
EditText FoodIncomeCounter;
EditText FoodCamp1Counter, FoodCamp2Counter, FoodCamp3Counter, FoodUpgrade1Counter, FoodUpgrade2Counter, FoodUpgrade3Counter;
TextView FoodIncomeResult;
int FoodIncome;
int FoodCamp1, FoodCamp2, FoodCamp3, FoodUpgrade1, FoodUpgrade2, FoodUpgrade3;
int TotalFood;
Button IncomeSubmitButton, FoodCampSubmitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//to get from user input and into variable form
FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
FoodIncomeResult = (TextView) findViewById(R.id.FoodIncomeResult);
IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);
FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);
//Submit button
IncomeSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to receive the inputted values
Food = Integer.parseInt(FoodIncomeCounter.getText().toString());
//to show the inputted values into the result fields
FoodIncomeResult.setText(FoodIncomeCounter.getText().toString());
}
});
//Submit button
FoodCampSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//receive the inputted values
FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());
//get food income and show
TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);
FoodIncomeResult.setText(String.valueOf(TotalFood));
}
});
}
}
I'm trying to make my button compare the number in the edit text to the random number I'm generating and make a toast if they're the same. the code runs but no matter what i set the bound to the number in the edit text never equals the random number.
Here is my code
Button submit;
EditText etcode;
Random random = new Random();
String generatedPassword = String.format(String.valueOf(random.nextInt(1)));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
mFlower = findViewById(R.id.ivImage);
mDescription = findViewById(R.id.tvDescription);
submit = (Button) findViewById(R.id.btn_submit);
etcode = findViewById(R.id.et_code);
Bundle mBundle = getIntent().getExtras();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etcode.getText().toString().equals(generatedPassword)){
Toast.makeText(getApplicationContext(), "CONGRATS", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "TRY AGAIN", Toast.LENGTH_SHORT).show();
}
}
});
Change this line
String generatedPassword = String.format(String.valueOf(random.nextInt(1)));
Because generatePassword is always 0 . That's why it works with zero.
random.nextInt(1);
Above code will always generate number less than 1.
You should change it to any other number.
Suppose you writerandom.nextInt(5);
Then above line will generate number between 0 to 5 means it can be 0,1,2,3,4.
Check this link https://www.geeksforgeeks.org/java-util-random-nextint-java/
I am attempting to convert an EditText, which is of type number in xml, to an Integer in order to calculate the value in seconds.
hoursIn = (EditText) findViewById(R.id.hoursET);
minIn = (EditText) findViewById(R.id.minET);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
textViewTime = (TextView) findViewById(R.id.timeDisp);
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
hoursMs = hrsToMs(inHr);
minMs = minToMs(inMin);
totalTime = hoursMs + minMs;
When I comment the lines where inHr and inMin are initialized I get no error in runtime, however when I leave the code as it is above I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{dit.assignment3/dit.assignment3.Timer}: java.lang.NumberFormatException: Invalid int: ""
I have also attempted this while getting the same error starting at the same line of code:
final CounterClass timer = new CounterClass(totalTime, 1000);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (hoursIn != null)
{
inHr = Integer.parseInt(hoursIn.getText().toString());
hoursMs = hrsToMs(inHr);
}
if (minIn != null)
{
inMin = Integer.parseInt(minIn.getText().toString());
minMs = minToMs(inMin);
}
else
{
textViewTime.setText("PLEASE GIVE A TIME");
}
totalTime = hoursMs + minMs;
timer.start();
}
});
Thanks in advance :)
I'm certain that this codes blocks are exactly same as you've shown here. That means You are directly initializing EditText and immediately calling getText() method which causes Exception.
There wont be any value immediately after initialization so that you are getting NumberFormatException when calling Integer.parseInt to empty value.
So I suggest you to put these codes inside some event like buttonClicked like here, so that you can be sure that you've entered some texts. And It's better checking if empty as well,
public void buttonClicked(View v){
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
}
You will get an java.lang.NumberFormatException: Invalid int: "" whenever you try to parse an empty string to Integer. Thus you need to check whether the EditText is empty or not.
You could easily do that as below
if (hoursIn.getText().toString().matches("")) {
Toast.makeText(this, "You did not enter a text", Toast.LENGTH_SHORT).show();
return;
}
OR
you can simply do a check as below
if (hoursIn.getText().toString().equals("")) {
Toast.makeText(this, "You did not enter a text", Toast.LENGTH_SHORT).show();
return;
}
First you have to put the lines where you are reading from edittext inside some event like click of a button. Then check whether anything is entered in the edittext or not, then use try/catch clause to convert it into number.
Try this code.
Add a button to your activity xml file:
<Button
android:height="wrap_content"
android:width="wrap_content"
android:onClick="myClickHandler" />
hoursIn = (EditText) findViewById(R.id.hoursET);
minIn = (EditText) findViewById(R.id.minET);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
textViewTime = (TextView) findViewById(R.id.timeDisp);
public void myClickHandler(View v){
if (hoursIn.getText().toString().matches("") || minIn.getText().toString().matches("")){
Toast.makeText(this, "You did not enter a text",Toast.LENGTH_SHORT).show();
return;
} else {
try {
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
hoursMs = hrsToMs(inHr);
minMs = minToMs(inMin);
totalTime = hoursMs + minMs;
Log.i("success");
} catch (NumberFormatException e) {
Toast.makeText(this, "Please enter number only",Toast.LENGTH_SHORT).show();
return;
}
}
}
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.
How do I require the user to input data into an EditText and not allow the application to proceed until the EditText is populated?
Right now, my application continues to progress even after the user acknowledges the error message stating the EditText is empty and is required.
private final static int EMPTY_TEXT_ALERT = 0;
protected Dialog onCreateDialog(int id) {
switch(id) {
case EMPTY_TEXT_ALERT: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("oops!!")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
return null;
}
public void sends(View v) {
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
int year = datePicker.getYear();
int month = datePicker.getMonth();
int day = datePicker.getDayOfMonth();
final EditText phone = (EditText) findViewById(R.id.editText2);
final EditText nameplate = (EditText) findViewById(R.id.editText3);
final EditText issue = (EditText) findViewById(R.id.editText4);
String ph = phone.getText().toString();
if(ph.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
String np = nameplate.getText().toString();
if(np.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
String i = issue.getText().toString();
if(i.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
else
{StringBuilder s= new StringBuilder(100);
s.append(year);
s.append(". ");
s.append(month+1);// month starts from 0 in this
s.append(". ");
s.append(day);
s.append(". ");
s.append(". ");
s.append(ph);
s.append(". ");
s.append(np);
s.append(". ");
s.append(i);
String st=s.toString();
Intent emailIntentt = new Intent(android.content.Intent.ACTION_SEND);
emailIntentt.setType("plain/text");
String aEmailList[] = { "shreyas.t#gmail.com" };
emailIntentt.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
emailIntentt.putExtra(android.content.Intent.EXTRA_SUBJECT, "Feedback");
emailIntentt.putExtra(android.content.Intent.EXTRA_TEXT, st);
startActivity(emailIntentt);
}
}}
You can add return statement after showing the dialog as shown below.
if(i.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
return;
}
It would be better to use Toast messages than showDialog though.
I don't know how you are calling your sends() method, but after any empty error you can just add a return statement immediately after the showDialog(). It means that somehow the sends() method has to get re-invoked via the UI after the user has put in text.
If your sends() method is called from a button via onClick(), then it means the user will see dialog with error, input some text and then, hit the button to send again.
Shreyas Tallani
how to validate the phone number... enters more than 10 digits the
error message should be displayed
If you are just wanting to test the length of the String, just get the String and compare the length to the max length of 10.
In your validate(...) method do something similar to the following:
String ph = phone.getText().toString();
if(ph.trim().equals("")) {
showDialog(EMPTY_TEXT_ALERT);
} else if (ph.length() > 10) {
showDialog(TEXT_TOO_LONG_ALERT);
}
You could also make your EditText only allow numeric values. This would help you validate the numbers. You can do this in the xml file or in code.
xml
android:inputType="TYPE_NUMBER_VARIATION_NORMAL"
code
EditText.setInputType(InputType.TYPE_NUMBER_VARIATION_NORMAL);
First thing you can do, is add a validate(...) method. Inside validate(...), you need to validate all the fields and if anything is left blank then show the error message and stop app progression.
If all the fields are fine, then call your send method. And send(...) should only be sending your data, not checking validation.