How to validate EditText? - android

I am doing one SMS App.. in which i am trying to validate edittext(i.e. if user will not enter the phone number then it will show please enter the number), but it is not executing those part.. Please check it and give me some suggestion....My code is here.. Thank you in advance..
public class MainActivity extends Activity {
Button btnSend;
EditText txtPhoneNo;
EditText txtSMS;
String phoneNo, SMS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend=(Button) findViewById(R.id.buttonSend);
txtPhoneNo=(EditText) findViewById(R.id.editTextPhoneNo);
txtSMS=(EditText) findViewById(R.id.editTextSMS);
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
phoneNo=txtPhoneNo.getText().toString();
SMS=txtSMS.getText().toString();
if(phoneNo.equals(" ") || phoneNo == null) {
Toast.makeText(getBaseContext(), "Please Enter the number !", Toast.LENGTH_LONG).show();
}
else {
MyAsync ma = new MyAsync();
ma.execute();
}
}
});
}
class MyAsync extends AsyncTask<Void,Void,Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Wait!", "Sending...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, SMS, null, null);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.cancel();
Toast.makeText(getApplicationContext(),"Sent",Toast.LENGTH_LONG).show();
}
}
}

You are using the following code to determine whether the user entered anything—
phoneNo.equals(" ") || phoneNo == null
Firstly, when the user keeps the EditText empty, it will be a 0-length string "" and NOT a space " ", which you're testing for.
Secondly, why are you making the null check? Is it possible that your layout won't have that EditText field? And, if that's possible, the null check should be the first thing to check. Because, if it can be null then your app will certainly crash, since you're testing for equals() on a null object before the null check!

If you want to try something more, don't check validation on click button.
Do it before with: TextWatcher
Your activity implements android.text.TextWatcher interface
You add TextChanged listeners to you EditText boxes
txt1.addTextChangedListener(this);
Of the overridden methods, you could use the afterTextChanged(Editable s) method as follows:
#Override
public void afterTextChanged(Editable s) {
// validation code goes here
}
You could directly check the contents of the EditText boxes like
String txt1String = txt1.getText().toString();
// Validate txt1String

To do this no need to take String and pass the content of edit-text into string. You can directly check by following code.
if(txtPhoneNo.length()<=0)
{
Toast.makeText(getBaseContext(), "Please Enter the number !", Toast.LENGTH_LONG).show();
}
else {
MyAsync ma = new MyAsync();
ma.execute();
}

Instead of these code,
if(phoneNo.equals(" ") || phoneNo == null) {
Toast.makeText(getBaseContext(), "Please Enter the number !", Toast.LENGTH_LONG).show();
}
Try following code,
// Trim the variable
phoneNo=txtPhoneNo.getText().toString().trim();
// Then condition part
if(phoneNo.length() == 0 && phoneNo != null) {
Toast.makeText(getBaseContext(), "Please Enter the number !", Toast.LENGTH_LONG).show();
}

Related

Show Toast if there is no Toast already showing

I have several buttons that can be clicked on a fragment. After clicking each button I show a Toast message that is exactly the same for each button. Thus if you press 5 different buttons one after another you will layer up 5 toast messages which will end up showing the same message for a long time. What I want to do is show a Toast if there is no Toast currently running.
The method that I use to show the Toast message
public void showToastFromBackground(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
When a button is pressed I simply call showToastFromBackground("Text to show");.
What I actually want is something like
public void showToastFromBackground(final String message) {
if(toastIsNotAlreadyRunning)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
}
Use:
toast.getView().isShown();
Or:
if (toast == null || toast.getView().getWindowVisibility() != View.VISIBLE) {
// Show a new toast...
}
EDIT:
Toast lastToast = null; // Class member variable
public void showToastFromBackground(final String message) {
if(isToastNotRunning()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
lastToast = Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG);
lastToast.show();
}
});
}
}
boolean isToastNotRunning() {
return (lastToast == null || lastToast.getView().getWindowVisibility() != View.VISIBLE);
}
Try isShown(). It returns a fatal error if no toast is shown. So you can use try and catch the error.
//"Toast toast" is declared in the class
public void showAToast (String st){
try{
toast.getView().isShown(); // true if visible
toast.setText(st);
} catch (Exception e) { // invisible if exception
toast = Toast.makeText(theContext, st, toastDuration);
}
toast.show(); //finally display it
}
From here.
This does not wait if there is toast already, then show. But it does change active toast's text and show new one immediately without toasts overlapping each other.

Issues With login/regstration

*UPDATED*still haveing issues please if you see any errors please let me know, i would like to put my logcat in but i cant access it due to the errors .......I'm having issues with my login and registration mechanism. I'm probably doing something wrong, but when i try to test out the login my app crashes with the message "...has suddenly stopped." msg. Also, my textview that goes to my registration class isnt responding. Can some please help me?
I know there is probably a lot of errors, but be kind I'm new to this :)
If anyone is generous or just bored and wanted to personally help me out with issues please leave your email
Below is the code for my login class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), SignUp.class);
startActivity(i);
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn = (Button) findViewById(R.id.btnLogin);
}
// Methods to handleClick Event of Sign In Button
public void signIn(View V) {
try{
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
Button btnSignIn = (Button) dialog.findViewById(R.id.btnLogin);
}catch(Exception e){
Log.e("tag", e.getMessage());
}
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = loginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
dialog.show();
}
}
#Override
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("tag", e.getMessage());
}
}
#Override
protected void onDestroy() {
try{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
MY registration class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
// Listening to Login Screen link
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
// get Instance of Database Adapter
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get References of Views
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String fullname = reg_fullname.getText().toString();
String username = reg_username.getText().toString();
String password = reg_password.getText().toString();
String email = reg_email.getText().toString();
String confirmPassword = reg_confirmpassword.getText()
.toString();
// check if any of the fields are vacant
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}}
The best way to know your code errors it's, put all your code in a block try-catch in all functions..
try{
//your code here
}catch(Exception e){
Log.e("tag", e.getMessage());
}
in Logcat will be apears in red color the errors of your code, "tag" it's a way to differentiate the erros like:
#Override
protected void onDestroy() {
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
}
I hope this helps...

using method inside asyntask in android

i have created one simple login application which takes user name and password from sqlserver..it works fine...
i want during login process one progeress bar should be displayed using asyntask...
but i am unaware to use parameters in asyntask...if some one plzz tell me how to put my method in doInbackground of asyntask and what param should i use....
my code is;.....
public void save(){
initilize();
ResultSet rs = null;
String mylog=id.getText().toString();
String mypass=pass.getText().toString();
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
Toast.makeText(getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
} else
try {
if(rs.next()){
Intent i=new Intent(getApplicationContext(),Act2.class);
startActivity(i);
}
else if(rs.next()==false){
Toast.makeText(getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if it is possible that same method save() be kept inside doInbackground() of asyntask...
making a fast refactorization (note that this as it stand it's really bad practice and coding, you MUST refactor this code to be more maintanable and to avoid duplication):
public class MyAsyncTask extends AsyncTask<> {
private Activity activity;
boolean result;
private String myLog;
private String myPass;
private Connection connect;
public MyAsyncTask(Activity activity, Connection connect) {
this.activity = activity;
this.connect = connect;
}
#Override
protected void onPreExecute() {
//show your progress dialog
}
#Override
protected Object doInBackground(Object[] objects) {
ResultSet rs = null;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
initilize();
mylog=id.getText().toString();
mypass=pass.getText().toString();
}
});
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "empty fields", Toast.LENGTH_SHORT).show();
}
});
} else
try {
if(rs.next()){
result = true;
}
else if(rs.next()==false){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(activity.getApplicationContext(), "incorrect login", Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
});
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
//hide your progress dialog
if(result == Boolean.TRUE){
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i=new Intent(activity.getApplicationContext(),Act2.class);
activity.startActivity(i);
}
});
}
}
}
then in your Activity you do this:
MyAsyncTask a = new MyAsyncTask(this, connect); //im guessing "connect" is your Connection object
a.execute();
As i said i made this fast refactoring for the code to work but best practice and good implementation is not in consideration here.
Maybe, you could use a timer, to check if your
login is ready. As long as it is not, you Show your progress Bar. If its ready, you can close the Bar and start a new activity or anything. timers run can run on u UI thread.
regards :)

Facebook api and send invite to more than one friend in android

I have a problem with inviting firend by facebook api to my app. This is my method:
private void inviteFromFacebook(Activity activity, List<GraphUser> list) {
for(int i=0; i<list.size(); i++) {
//TODO post invite to friends wall
// Log.v("MainActivity", "user id: " + user.getId());
if(list == null || list.size() == 0)
return;
Bundle parameters = new Bundle();
String friendsIdsInFormat = "";
friendsIdsInFormat = friendsIdsInFormat + list.get(i).getId();
parameters.putString("to", friendsIdsInFormat);
parameters.putString( "message", "Use my app!");
Facebook mFacebook = new Facebook( getResources().getString(R.string.facebook_app_id));
// Show dialog for invitation
mFacebook.dialog(activity, "apprequests", parameters, new Facebook.DialogListener() {
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
}
}
Everyting is ok, but I want to send invitation to many frieds, so in this codes I show one dialog for every person. How can I show only one dialog, but with many friends? This is possible or I must for every friend show dialog?
You can send a comma delimited list in the "to" field, like "123,456,789".
Be careful about sending too many requests though, you don't want to be identified as a spam app.

Progress dialog is not showing while calling a web service

I am new to android. I want to show progress dialog when user click on login button. I tried this but the dialog is not showing
btn_logIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
getUserCredentials();
}
}); //end of anonymous class
private void showProgressDialog() {
if (dialog == null) {
dialog = new ProgressDialog(this);
}
dialog.setMessage("Please Wait. Your authentication is in progress");
dialog.setButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
dialog.dismiss();
}
}); //end of anonymous class
dialog.show();
} //end of showProgressDialog()
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
callWebService(userName, password);
}
} //end of getUserCredentials()
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
} catch (SocketTimeoutException e) {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
} //end of callWebServide()
Am i doing anything wrong. When i click on login button and service is not running then it shows message that Service is not connected, Please make sure your server is running", but the dialog isn't showing...Why? My logic is when user click on login button and fields have values then start showing progress dialog and if anything happens like when result come or server is not running or if any exception happen , then i remove the dialog and show the appropriate message, but dialog isn't showing...Why? What i am doing wrong? Please help..
Thanks
Try this,
Change your getUserCredentials() like this,
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
Thread t=new Thread(new Runnable() {
public void run() {
callWebService(userName, password);
}
}); t.start();
}
}
And your callWebService method like this,
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
} catch (SocketTimeoutException e) {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
}
});
} catch(Exception e) {
e.printStackTrace();
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
});
}
}
Update 1
To answer your questions from your comments,
1)Yes Async Task is more efficient. It has its own methods to do the same task what I have described here.
AsyncTask has the following methods,
i)onPreExecute()-which can be used to start your Dialog
ii)doInBackground()-which acts as the background thread.
iii)onPostExecute()-which gets called at the end where you can dismiss the dialog.
The reason why I didn't mention is that, there are possibilities that you might have to change your working code's structure to adapt to Async task.
2)runonUiThread- as the name indicates, anything inside this will be considered as it is running in the main UI thread. So basically to update the screen you have to use this. There are also other methods available, like Handlers which can also do the same task.
Use AsyncTask for it when ever task started at that time initialise your widget and then call your webservice from run method and close your progress bar on stop method.

Categories

Resources