I am using following function which uses boolean value.
int recFound=0;
public Boolean CheckUser(String uName,String password)
{
try
{
statement=conn.createStatement();
resultSet=statement.executeQuery("select count(*) from UserMaster where username LIKE'"+uName+"' and password LIKE'"+password+"'");
if(resultSet.getRow()>0)
{
recFound=1;
}
else
{
recFound=0;
}
}
catch (Exception e) {
e.printStackTrace();
recFound=0;
}
if(recFound == 0)
{
return false;
}
else
{
return true;
}
}
I am calling this function through:
boolean isValidUser=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString());
if(isValidUser)
{
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
When i pass this function proper values its not making recFound=1;
And in last condition although recFound==0 it enters in else condition and returns true.
But while assigning this value to caller functions return value it assigns false.
Means it makes , boolean isValidUser=con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString()); to be false.
isValidUser should get true in such case.
Please help me.
Hi Shrimant Bajirao Peshawe - I,
change the statement "if(resultSet.getRow()>0)" to "if(resultSet. next ())" then try it.
Reference : Refer
you are calling a boolean function in your CheckUser method so its returns true or false value..
Jo just returns true value in that function.
you can also check it with:
if(isValidUser==true)
{
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
and print a value isValidUser in log that which value it is getting
Try Follwing code...
int recFound = 0;
public boolean CheckUser(String uName, String password) {
try {
statement = conn.createStatement();
resultSet = statement.executeQuery("select count(*) from UserMaster where username LIKE '" + uName + "' and password LIKE '" + password + "'");
if (resultSet.getRow() > 0) {
recFound = 1;
} else {
recFound = 0;
}
if (recFound > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
and
if(con.CheckUser(etLoginID.getText().toString(), etPassword.getText().toString())) {
Intent i= new Intent(getApplicationContext(),Messages.class);
startActivity(i);
}
Change:
if(resultSet.getRow()>0)
{
recFound=1;
}
else
{
recFound=0;
}
to:
if(resultSet.getRow()>0)
{
return true;
}
else
{
return false;
}
Remove conditions checking recFound in catch()
This should solve your problem.
Replace code
if(resultSet.getRow()>0){
recFound=1;
} else {
recFound=0;
}
to
if(resultSet.next()){
return true;
} else {
return false;
}
Try to initialize the
isValidUser to false at the begining
also log the value of resultSet.getRow() and recFound before returning it caller.
you can also try to use cusrsor like below
int recFound=0;
private SQLiteDatabase mDb;
public Boolean CheckUser(String uName,String password)
{
try
{
String sql="select count(*) from UserMaster where username LIKE'"+uName+"' and password LIKE'"+password+"'";
Log.i(TAG,"Executing Query : "+sql);
mCur = mDb.rawQuery(sql, null);
Log.i(TAG,"Query Executed Successfully");
if(mCur!=null)
{
recFound=1;
}
else
{
recFound=0;
}
}
catch (Exception e) {
e.printStackTrace();
recFound=0;
}
if(recFound == 0)
{
return false;
}
else
{
return true;
}
}
Related
What I aim with my program is to make a profile page with details that are blank for the first time use then these details can be editable and retained after clicking an update button. However, I tried many different ways like sharedprefs and firebase. It's just doesn't work to me.
The firebase way is after the update button has been clicked, it's just going to the main activity then it doesn't update or change anything.
here is the firebase code
showAllUserData();
//DB
reference = FirebaseDatabase.getInstance("https://backend-d820a-default-rtdb.firebaseio.com/").getReference("user");
private void showAllUserData(){
Intent intent = getIntent();
_NAME = intent.getStringExtra("name");
_NUMBER = intent.getStringExtra("num");
_ADDRESS = intent.getStringExtra("add");
_AGE = intent.getStringExtra("age");
_BDAY = intent.getStringExtra("bday");
_BTYPE = intent.getStringExtra("btype");
_COMORB = intent.getStringExtra("comorb");
editName.setText(_NAME);
editNum.setText(_NUMBER);
editAdd.setText(_ADDRESS);
editAge.setText(_AGE);
editBday.setText(_BDAY);
editBType.setText(_BTYPE);
editComorb.setText(_COMORB);
}
public void update(View view){
if (isNameChanged() || isNumberChanged() || isAddChanged() || isAgeChanged() ||
isBdayChanged() || isBTypeChanged() || isComorbChanged()) {
Toast.makeText(this, "Data has been updated", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Data his same and cannot be updated", Toast.LENGTH_LONG).show();
}
}
private boolean isComorbChanged() {
if(_COMORB.equals(editComorb.getText().toString())){
reference.child(_COMORB).child("COMORB").setValue(editComorb.getText().toString());
return true;
}else{
return false;
}
}
private boolean isBTypeChanged() {
if(_BTYPE.equals(editBType.getText().toString())){
reference.child(_BTYPE).child("btype").setValue(editBType.getText().toString());
return true;
}else{
return false;
}
}
private boolean isBdayChanged() {
if(_BDAY.equals(editBday.getText().toString())){
reference.child(_BDAY).child("bday").setValue(editBday.getText().toString());
return true;
}else{
return false;
}
}
private boolean isAgeChanged() {
if(_AGE.equals(editAge.getText().toString())){
reference.child(_AGE).child("age").setValue(editAge.getText().toString());
return true;
}else{
return false;
}
}
private boolean isAddChanged() {
if(_NUMBER.equals(editNum.getText().toString())){
reference.child(_NUMBER).child("address").setValue(editNum.getText().toString());
return true;
}else{
return false;
}
}
private boolean isNumberChanged() {
if(_NUMBER.equals(editNum.getText().toString())){
reference.child(_NUMBER).child("numBER").setValue(editNum.getText().toString());
return true;
}else{
return false;
}
}
private boolean isNameChanged() {
if(_NAME.equals(editName.getText().toString())){
reference.child(_NAME).child("name").setValue(editName.getText().toString());
return true;
}else{
return false;
}
Is there a simpler way to implement this?
Help me please to run rxJava code sample for android. Here is what I want to do:
I have a function, which gives me redirects one by one. I need to take that redirect (if it's not empty) and try to startActivity of external app with it. If redirect empty - I need to break and return some Result data with last redirect found. If this app started successfully - I need to return some Result object that tells that app have been opened, if not opened - I need to try to get next redirect. Here is code that I have:
public Observable<Result> getStartAppResult(String url, AppOpeningRule shopOpeningRule) {
return getSingleHttpRedirectUrl(url, appOpeningRule)
.flatMap(redirect -> {
if(Strings.isNullOrEmpty(redirect)){
return isAppStarted(redirect, appOpeningRule.getPackageName());
} else {
return getDataSourceWithParams(redirect);
}
})
.flatMap(appStarted -> {
if(appStarted){
return getDataSourceWithParams(redirect);
} else {
return getSingleHttpRedirectUrl(url, appOpeningRule);
}
});
}
private ObservableSource<Result> getDataSourceWithParams(String finalUrl) {
Result result = new Result(finalUrl, lastRedirectUrl);
return Observable.just(result);
}
public Observable<Boolean> isAppStarted(String url, String appPackageName) {
return Observable.create(emitter -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_REQUIRE_NON_BROWSER);
intent.setPackage(appPackageName);
boolean hasActivityNotFoundException = false;
try {
context.startActivity(intent);
} catch (ActivityNotFoundException exception) {
hasActivityNotFoundException = true;
} finally {
emitter.onNext(!hasActivityNotFoundException);
emitter.onComplete();
}
});
}
private Observable<String> getSingleHttpRedirectUrl(String url,
final ShopOpeningRule appOpeningRule) {
return httpService.goToWebSiteLink(url)
.compose(rxTransformers.applyUnauthorizedHandlerCustomError())
.onErrorResumeNext(throwable -> {
if (throwable instanceof RetrofitException) {
RetrofitException error = (RetrofitException) throwable;
if (error.getKind() == Kind.HTTP) {
if (error.getHttpExceptionCode() >= REDIRECT_START && error.getHttpExceptionCode() <= REDIRECT_END) {
String redirectUrl = error.getResponse().headers().get(KEY_HEADER_REDIRECT_LOCATION);
if (!Strings.isNullOrEmpty(redirectUrl)) {
lastRedirectUrl = redirectUrl;
if (appOpeningRule.hasRedirectLinkPatterns()) {
if (LinkParser.urlContainsPattern(redirectUrl, appOpeningRule.getRedirectLinkPatterns())) {
String modifiedLink = LinkParser.modifyRedirectLinkIfNeeded(redirectUrl, shopOpeningRule);
return Observable.just(modifiedLink);
} else {
return Observable.just(redirectUrl);
}
} else {
return Observable.just(redirectUrl);
}
}
}
}
}
return Observable.just("");
});
}
always returning the wrong value, before the request has been finish. The validation will already return the value without waiting for the response. I'am using retrofit for request then i put it on listener.
Thankyou for the help, suggestion is much accepted!.
this is my code, i have validation for the screen when it's true it will goes to another screen.
#Override
public boolean isValid() {
if (NetworkUtils.isConnected(getActivity())) {
final AtomicBoolean pass = new AtomicBoolean(false);
Thread simpleThread = new Thread() {
public void run() {
new ReprintOnlineHelper(rType, receiptNoEditText.getText().toString(), issuedDate, etTotalAmtPaid.getText().toString(), new ReprintOnlineHelper.ReceiptNoSearchListener() {
#Override
public boolean onServiceResponse(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.get(0).getTPAYRECEIPTNO());
if (receiptNumbers.isEmpty()) {
returnValue = "eReceipt Number not found!";
val = true;
} else {
String pdates = null, ddates;
try {
if (!receiptNumbers.get(0).getTPAYISSUEDDATE().isEmpty()) {
Date periodFormat = df.parse(receiptNumbers.get(0).getTPAYISSUEDDATE());
pdates = sdf.format(periodFormat);
}
} catch (ParseException e) {
e.printStackTrace();
Log.e("ddd", "" + e.getMessage());
}
String tinNo = receiptNumbers.get(0).getTPTIN();
if (tinNo.contains("-")) {
tinNo = receiptNumbers.get(0).getTPTIN().replace("-", "");
}
Log.e("JAC", "" + receiptNumbers.get(0).getTPAYRECEIPTNO() + "---" + AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)) + "---" + MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) + "--" + AlfonzoUtils.formatDate(issuedDate) + "--" + receiptNoEditText.getText().toString() + "--" + tinNo + "--"+revenueCollection.getTpTin().replace("-", ""));
if (receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString()) &&
AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))
&& MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) == MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) && tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
pass.set(true);
returnValue = "success";
val = true;
showMessagePrompt(rType,returnValue);
return true;
} else if (!tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
returnValue = "eReceipt Number was not issued to this TIN " + revenueCollection.getTpTin();
val = false;
} else if (!AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))) {
returnValue = "Issued date is not valid";
val = false;
} else if (MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) != MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString())) {
returnValue = "Total amount paid is not valid";
val = false;
} else if (!receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString())) {
returnValue = "ReceiptNo is not valid";
val = false;
}
}
return false;
}
#Override
public void onErrorResponse(int err) {
}
}).reprintReceiptNo();
}
};
if (!receiptNoEditText.getText().toString().isEmpty() && issuedDate != 0 /*&& MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) > 0*/) {
try {
simpleThread.start();
simpleThread.join();
pass.get();
Log.e("pass", "" + pass + "-" + pass.get() + val);
} catch (InterruptedException e) {
e.printStackTrace();
}
return pass.get();
}
}
return false;
}
this is my request in retrofit:
public void reprintReceiptNo() {
JSONObject jO = new JSONObject();
JSONObject result = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jO.put("xReceipt", receiptTypeNo);
jO.put("xType", receipttype);
jsonArray.put(jO);
result.put("dataArray", jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("dataArray", "----- " + result.toString());
ServiceInterface si = BaseRestClient.getClient();
Observable<List<ReceiptNumber>> call = si.getreprintReceiptNumber(result.toString());
call.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<ReceiptNumber>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.toString());
onReceiptNoSearchListener.onServiceResponse(receiptNumbers);
}
});
}
Its not possible for the isValid() method to wait for the service reponse if you have code outside the Thread you've created.
The method will execute the Thread, but while that Thread is executing, the rest of the code will be read, meaning the return pass.get(); or the return false; statments will be read, causing the the method to return before the server response.
The solution its to change the way this was done. You should check if you can call the server and then created your logic in the methods onServiceResponse() and onErrorResponse() based on how you want to proceed.
I wrote following code for login but when I type "\" after email-id, it accepts and log in successfully (it doesn't accepts any other symbols or characters only accepts "\").
I don't want that it login with "\".`
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.main);
WiztangoBaseApplication.InitDialogBox(WiztangoActivity.this);
this.pref = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.login_status);
register = (Button) findViewById(R.id.btnregister);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RegisterIntent();
}
});
login = (Button) findViewById(R.id.btlogin);
password = (EditText) findViewById(R.id.txtPwd);
username = (EditText) findViewById(R.id.txtemail);
saveLoginCheckBox = (CheckBox)findViewById(R.id.saveLoginCheckBox);
pref = getSharedPreferences(Constants.PREFS_NAME,
MODE_PRIVATE);
String usernamestr = pref.getString(Constants.PREF_USERNAME, "");
String passwordsharestr = pref.getString(Constants.PREF_PASSWORD,
"");
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLogin = pref.getBoolean("saveLogin", false);
if (saveLogin == true) {
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLoginCheckBox.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
//Constants.clearInfo();
getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(Constants.PREF_USERNAME,
username.getText().toString())
.putString(Constants.PREF_PASSWORD,
password.getText().toString())
.putString(Constants.PREF_CHECKED, "TRUE")
.commit();
if (username.getText().toString().trim().equals("")) {
username.setError(Html
.fromHtml("Please Enter Username"));
username.requestFocus();
} else if (password.getText().toString().trim()
.equals("")) {
password.setError(Html
.fromHtml("Please Enter Password"));
password.requestFocus();
} else {
if (Constants
.checkInternetConnection(WiztangoActivity.this)) {
Constants.userpass = password.getText()
.toString();
new AuthenticData().execute();
} else {
WiztangoBaseApplication.ShowThisDialog("Error",
"Please check internet connection.");
}
if (saveLoginCheckBox.isChecked()) {
prefEditor.putBoolean("saveLogin", true);
prefEditor.putString(Constants.PREF_USERNAME,
username.getText().toString());
prefEditor.putString(Constants.PREF_PASSWORD,
password.getText().toString());
saveLoginCheckBox.setChecked(true);
prefEditor.commit();
} else {
SharedPreferences mPreferences = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove(Constants.PREF_USERNAME);
editor.remove(Constants.PREF_PASSWORD);
editor.commit();
}
}
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
Inbuilt Patterns Provides Email Validation like:
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailStr).matches() && !TextUtils.isEmpty(emailStr)) {
emailEditText.setError("Invalid Email");
emailEditText.requestFocus();
}
Heyy, check this answer here: https://stackoverflow.com/a/7882950/1739882
It says:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
You can use this code for check is Valid Email or not:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Best Approach
Validate email and isEmpty in one method.
public final static boolean isValidEmail(CharSequence target)
{
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
Try out the below method to validate the Email address.
private boolean validateEmail(EditText editText, String p_nullMsg, String p_invalidMsg)
{
boolean m_isValid = false;
try
{
if (p_editText != null)
{
if(validateForNull(editText,p_nullMsg))
{
Pattern m_pattern = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Za-z]{2,4})");
Matcher m_matcher = m_pattern.matcher(editText.getText().toString().trim());
if (!m_matcher.matches() && editText.getText().toString().trim().length() > 0)
{
m_isValid = false;
editText.setError(p_invalidMsg);
}
else
{
m_isValid = true;
}
}
else
{
m_isValid = false;
}
}
else
{
m_isValid = false;
}
}
catch(Throwable p_e)
{
p_e.printStackTrace(); // Error handling if application crashes
}
return m_isValid;
}
Try this code:--
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
in Android i want to set EditTextprefernce value i tried
EditTextPreference etp = (EditTextPreference)getPreferenceScreen().findPreference("mykey");
etp.setText("123");
tell me how can i set EditTextpreference value in program dont suffest me in xml/preference.xml to write android:default="123" want to do programmatically
Try this
EditTextPreference myEditTextPreference = (EditTextPreference) findPreference("myPrefKey");
myEditTextPreference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
try {
String input = newValue.toString();
if (containsOnlyNumbers(input)) {
int result = Integer.parseInt(input);
if (result < 0) {
result = 0;
}
// Parsing was successful. Use the result..
// TODO
} else {
Log.e(TAG, "Invalid value input '" + input
+ "', using old one");
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
});
private boolean containsOnlyNumbers(String s) {
if(s.length()<1) {
return false;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}