I have created a small application to check whether the password entered by user is valid or not. it is being able to check , but its not displaying the toast and as soon as i click the button , it shows "Unfortunately , your app has stopped working". I am using my device for deployment. Please help me find out , why the toast is not working. I have used a command which sets the value of variable a,b,c in the edit text field , to check whether it is coming correct. And yes it was coming correct. So the problem lies in the toast as per i think.
public class second extends AppCompatActivity {
public EditText fname ;
public EditText lname ;
public EditText email ;
public EditText pass ;
public EditText blood;
public EditText cpass;
public EditText add ;
public EditText mob ;
public Toast t ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
fname = (EditText) findViewById(R.id.fname);
lname = (EditText) findViewById(R.id.lname);
email = (EditText) findViewById(R.id.email);
pass = (EditText) findViewById(R.id.pass);
add = (EditText) findViewById(R.id.add);
cpass = (EditText) findViewById(R.id.cpass);
mob = (EditText) findViewById(R.id.mob);
blood = (EditText) findViewById(R.id.blood);
Button sign = (Button) findViewById(R.id.sign);
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sfname = fname.getText().toString();
String spass = pass.getText().toString();
String scpass = cpass.getText().toString();
validate(spass, scpass);
}
});
}
public void validate(String spass ,String scpass){
int a =0;
int b =0;
int c =0;
t = new Toast(this);
int len = spass.length();
for(int i =0;i<len;i++){
char d = spass.charAt(i);
if(d>=48 && d<=57){
a++;
}
if(d>=65 && d<=90){
b++;
}
if(d>=33 && d<=47){
c++;
}
}
email.setText(a+" "+b+" "+c);
if(a==0 || b==0 || c==0){
t.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG);
t.show();
} else {
if(spass.equals(scpass)){
t.makeText(this,"login succesful",Toast.LENGTH_SHORT);
t.show();
} else {
t.makeText(this,"passwords dont match",Toast.LENGTH_SHORT).show();
}
}
}
}
try this
Toast toast = Toast.makeText(context, text, duration);
toast.show()
or
Toast.makeText(context, text, duration).show();
From the Docs, it says
Toast (Context context) Construct an empty Toast object. You must call
setView(View) before you can call show().
So when you create Toast object from its constructor, it is considered that you are trying to create Custom Toast
If you are not creating any, then use like:
public Toast t; // Global variable
Now inside your validate method:
t = Toast.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG);
t.show();
I have made some changes to you method , try using this one .
You can find more details on https://stackoverflow.com/a/21963343
public void validate(String spass ,String scpass){
int a =0;
int b =0;
int c =0;
// Toast t = new Toast(this);
int len = spass.length();
for(int i =0;i<len;i++){
char d = spass.charAt(i);
if(d>=48 && d<=57){
a++;
}
if(d>=65 && d<=90){
b++;
}
if(d>=33 && d<=47){
c++;
}
}
email.setText(a+" "+b+" "+c);
if(a==0 || b==0 || c==0){
/*
* updated
* */
Toast.makeText(this, "Password should contain atleast one special character , one capital letter and one number", Toast.LENGTH_LONG).show();
} else {
if(spass.equals(scpass)){
/*Updated*/
Toast.makeText(this,"login succesful",Toast.LENGTH_SHORT).show();
} else {
/*Updated*/
Toast.makeText(this,"passwords dont match",Toast.LENGTH_SHORT).show();
}
}
}
Related
I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
I am trying to build a Bengali calculator. Here is the layout of English calculator :
By editing layout I can easily replace English digits with Bengali digits. But when it comes to the calculation i am unable to do it. Like i want it to calculate in Bengali too. e.g it will perform in Bengali like this (২+২=৪) instead of (2+2=4). I have tried the replacing method but it didn't work.
Bengali digits(০ ১ ২ ৩ ৪ ৫ ৬ ৭ ৮ ৯)
English digits(1 2 3 4 5 6 7 8 9)
Thank you for your time.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(result);
}
}
}
Your code tries to extract numerical values from the text on buttons.
You should write custom Double parser which parses Bengali number text to numerical value.
Also you should write a method which converts numerical double value to Bengali number text. You have to use this method while setting screen text.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = BengaliUtils.toDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = BengaliUtils.toDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(BengaliUtils.toString(result));
}
}
}
class BengaliUtils {
static String toString(double value) {
//TODO implement logic
// You can convert value to regular number text, and then replace each char with the Bengali version. The performance could be improved with better logic.
return text;
}
static double toDouble(String text) {
//TODO implement logic
//You can do that, first replace each Bengali char with normal number char. The use Double.parse on new text. The performance could be improved with better logic.
return value;
}
}
#Override
public void onClick(View view) {
String num = editText.getText().toString();
//split the num
char[] charArray = num.toCharArray();
StringBuilder stringBuilder = new StringBuilder(charArray.length);
// loop and convert using switch case
for (int i=0; i<charArray.length; i++ ){
char character = charArray[i];
switch (character){
case '.':
stringBuilder.append(".");
break;
case '0':
stringBuilder.append("০");
break;
case '1':
stringBuilder.append("১");
break;
}
}
//Final result..
textView.setText(stringBuilder);
}
Try above code...
Here is the output
NOTE
I am taking English numbers from EditText on Button click. You will
have to change that in your code.
Currently, switch can handle 0,1,.(decimal) only. You can easily
add cases for other numbers too.
Please Check this answer too. Convert String to another locale in java
I'm doing basic demo of android related to login, update user
I used user's id from login page to load user's information to update page
username = (EditText) findViewById(R.id.txtUsername);
age = (EditText) findViewById(R.id.txtAge);
weight = (EditText) findViewById(R.id.txtWeight);
height = (EditText) findViewById(R.id.txtHeight);
username.setText(db_username);
age.setText(db_age);
weight.setText(db_weight);
height.setText(db_height);
and update button
update.setOnClickListener(new View.OnClickListener() {
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
#Override
public void onClick(View v) {
if (weight.equals("")) {
Toast.makeText(getApplicationContext(), "Please input weight!",
Toast.LENGTH_LONG).show();
return;
}else if(height.equals("")){
Toast.makeText(getApplicationContext(), "Please input height!",
Toast.LENGTH_LONG).show();
return;
}else if(age.equals("")){
Toast.makeText(getApplicationContext(), "Please input age!",
Toast.LENGTH_LONG).show();
return;
}else{
dbHandler.updateUser(sid,sweight,sheight,sage);
Toast.makeText(getApplicationContext(),
"User's information updated! ", Toast.LENGTH_LONG)
.show();
Toast.makeText(getApplicationContext(),
sid+sweight+sheight+sage+" and test", Toast.LENGTH_LONG)
.show();
Intent i = new Intent(UserUpdate.this, MainActivity.class);
startActivity(i);
finish();
}
}
});
For exam: weight: 70,height:1,65,age:21
when i changed it to: weight:50,height:1,65,age:21
the 2nd Toast show me that weight : 70 but not 50
You need to move these top three lines inside of the click method, not declare them as member variables of the anonymous class.
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
#Override
public void onClick(View v) {
// Move them here
put this :
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
in onclick method , before -> if (weight.equals(""))
Can someone point me on using Regular Expressions in android (Patterns and Matchers to be specific)
String pass_pattern = "^([A-Za-z0-9][A-Za-z0-9]{4,10})$";
b1= (Button)findViewById(R.id.button1);
et1= (EditText)findViewById(R.id.editText1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
chek = et1.getText().toString();
if(chek.equals(""))
{
Toast.makeText(getApplicationContext(), "Enter password",1000).show();
}
if(chek.matches(pass_pattern))
{
Toast.makeText(getApplicationContext(), "Valid pAssword",1000).show();
}else {Toast.makeText(getApplicationContext(), "InvalidpAssword",1000).show();}
}
});
this is my code currently, i wanna check if the user has entered atleast one small letter and atleast one capital letter and a number and the length should be 4-10 char's.
If i do this via .matches() it only compares only one of the condition in the above said string.
Try this:
String pass_pattern = "^(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])[^\\W_]{4,10}$";
You could do it without using regexp:
boolean lowerCase = false;
boolean upperCase = false;
boolean digit = false;
int length = password.length();
for (char c : password.toCharArray()) {
if (Character.isUpperCase(c))
upperCase = true;
if (Character.isLowerCase(c))
lowerCase = true;
if (Character.isDigit(c))
digit = true;
if (lowerCase && upperCase && digit)
break;
}
I have a function to find an employee's id number from my sqlite database. The function allows the user to look up by id or name (first and/or last); therefore it creates several dialog boxes and finds the data through an If Else Then tree. Here's the code for those who like that sort of thing:
public String getEmployeeID() {
final CharSequence[] items = {"By ID", "By Name", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(LibraryScreen.this);
builder.setTitle("Find Employee");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("Cancel")) {
dialog.cancel();
empid = "";
} else if(items[item].equals("By ID")) {
dialog.cancel();
final Dialog dialog2 = new Dialog(LibraryScreen.this);
dialog2.setContentView(R.layout.peopledialog);
dialog2.setTitle("Employee ID");
dialog2.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog2.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog2.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee ID");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog2.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00000002);//numbers
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 15;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog2.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog2.findViewById(R.id.txtGeneral);
String newemp = "";
db.open();
Cursor c = db.getEmployee(emplid.getText().toString());
if(c.moveToFirst()) {
empid = c.getString(c.getColumnIndex("employeeid"));
} else {
Toast.makeText(LibraryScreen.this, "No ID Match", Toast.LENGTH_LONG).show();
empid = "";
}
c.close();
db.close();
dialog2.dismiss();
}
});
Button buttonCan = (Button) dialog2.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
empid = "";
}
});
dialog2.show();
} else if(items[item].equals("By Name")) {
dialog.cancel();
final Dialog dialog1 = new Dialog(LibraryScreen.this);
dialog1.setContentView(R.layout.peopledialog);
dialog1.setTitle("Employee's Name");
dialog1.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog1.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog1.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee Name");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog1.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00002001);//cap words
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 50;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog1.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog1.findViewById(R.id.txtGeneral);
String firstname = emplid.getText().toString();
String lastname = "";
String matchlist = "";
String temptext = "";
int matchcount = 0;
if(firstname.lastIndexOf(" ") <= 0) {
lastname = firstname;
firstname = "X";
} else {
lastname = firstname.substring(firstname.lastIndexOf(" ") + 1);
firstname = firstname.substring(0, firstname.lastIndexOf(" "));
}
db.open();
Cursor c1, c2;
String titletext = "";
if(firstname.length() > 0) {
c1 = db.getEmployeeByName(lastname, firstname);
if(c1.getCount() == 0) {
c1 = db.getRowByFieldTextOrdered("employees", "lastname", lastname, "lastname, firstname");
if(c1.getCount() == 0) {
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
}
}
if(c1.getCount() > 0) {
do {
c2 = db.getRowByField("orgcodes", "manager", c1.getString(c1.getColumnIndex("employeeid")));
if(c2.moveToFirst()) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(9, 10).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(7, 8).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(5, 6).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(4, 5).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(3, 4).equals("0")) {
titletext = "Top Brass";
} else {
titletext = "Senior VP";
}
} else {
titletext = "VP";
}
} else {
titletext = "Director";
}
} else {
titletext = "Senior Manager";
}
} else {
titletext = "Manager";
}
} else {
titletext = "Employee";
}
matchcount++;
matchlist = matchlist + c1.getString(c1.getColumnIndex("employeeid")) + ": " + c1.getString(c1.getColumnIndex("firstname")) + " " + c1.getString(c1.getColumnIndex("lastname")) + ": " + titletext + "|";
} while(c1.moveToNext());
}
} else {
empid = "";
}
if(matchcount == 0) {
db.close();
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
} else {
final CharSequence[] items = new CharSequence[matchcount + 1];
items[0] = "(Cancel)";
for(int i = 1; i <= matchcount; i++) {
items[i] = matchlist.substring(0, matchlist.indexOf("|"));
matchlist = matchlist.substring(matchlist.indexOf("|") + 1);
}
db.close();
AlertDialog.Builder builder1 = new AlertDialog.Builder(LibraryScreen.this);
builder1.setTitle("Select Employee");
builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("(Cancel)")) {
dialog.cancel();
empid = "";
} else {
String wasted = items[item].toString();
empid = wasted.substring(0, wasted.indexOf(":"));
dialog.cancel();
}
}
});
AlertDialog alert1 = builder1.create();
alert1.show();
}
dialog1.dismiss();
}
});
Button buttonCan = (Button) dialog1.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
empid = "";
}
});
dialog1.show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
return empid;
}
I use the employee id for a variety of functions through multiple activities in my program. Up to now, I've simply pasted the code under each listener that needs the id, but that is such a waste of space IMHO.
My question:
Is there a way to put this function somewhere that can be called from many different activities?
If so:
How do I do that?
How do I set the context for the dialog boxes for multiple activities?
How do I get the employee id back to the function that needs it?
I'm sure this has been asked before, but I haven't been able to find it online: actually, I'm not even sure how to word the query right. My attempts have come up woefully short.
A little late to the party - but recorded for posterity:
Read up on the Application class:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in your
AndroidManifest.xml's tag, which will cause that class
to be instantiated for you when the process for your
application/package is created.
Basically, this would give you the ability to obtain a single object that represents your running application (think of it as a singleton that returns an instance of your running app).
You first start off by creating a class that extends Application base class and defining any common code that is used throughout your application
import android.app.Application;
public class MyApplication extends Application {
public void myGlobalBusinessLogic() {
//
}
}
Then tell your application to use the MyApplication class instead of the default Application class via the <application> node in your app manifest:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="MyApplication">
Finally, when you need to get to your common function just do something like:
MyApplication application = (MyApplication) getApplication();
application.myGlobalBusinessLogic();
If you need to get the context from any part of your application, you can simple return it by calling getApplicationContext() (defined in the base Application class) via a getter method within your custom application class.