Though I controlled it with an if statement I'm getting ''Given string empty or null'' error and my app is closing.
fun kayitOl ( view : View) {
val email =findViewById<EditText>(R.id.emailText).text
val password = findViewById<EditText>(R.id.passwordText).text
if (email != null && password != null ) {
auth.createUserWithEmailAndPassword(email.toString(), password.toString())
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val intent = Intent(this, haber_akisi::class.java)
startActivity(intent)
finish()
}
}.addOnFailureListener { exception ->
Toast.makeText(this, exception.localizedMessage, Toast.LENGTH_LONG).show()
}
}else {
Toast.makeText(this,"Lütfen E-mail ve Password alanlarını doldurunuz",Toast.LENGTH_LONG).show()
}
}
You check just for null, but not for empty string ""
You can change your checking with email.isEmpty() or better email.isBlank() for checking strings like " "
Related
I am using BiometricPromt in my application.
Now I need to implement way for user to enter the PIN when Biometric is not available or enrolled.
I can use .setDeviceCredentialAllowed(true) but problem with it is when Biometric is not available or enrolled it won't show any dialog, and even if user use PIN if Biometric is available it doesn't registrate it in onAuthenticationSucceeded.
So now I am trying to implement negative button so user can enter PIN and I can catch it and see if user entered it correctly but I can't find anywhere if it is possible to do with default android PIN manager, so I don't have to implement any 3rd party library?
My current code is:
fun biometricCheck(context: Context, fragment: FragmentActivity){
val executor = ContextCompat.getMainExecutor(context)
val biometricManager = BiometricManager.from(context)
init(fragment)
when {
biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS -> {
authUser(executor, context, fragment)
}
biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
//No hardware
}
biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
//Hardware unvailable
}
biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
//NONE ENROLLED
}
}
}
private fun init(fragment: FragmentActivity){
//Some code
}
private fun authUser(executor: Executor, context: Context, fragment: FragmentActivity) {
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Authentication")
//.setSubtitle("Owner confirmation")
.setDescription("Scan fingerprint or enter PIN")
//.setDeviceCredentialAllowed(true)
.setNegativeButtonText("TEST")
.build()
val biometricPrompt = BiometricPrompt(fragment, executor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(
result: BiometricPrompt.AuthenticationResult
) {
super.onAuthenticationSucceeded(result)
val intent = Intent(context, MainActivity::class.java)
context.startActivity(intent)
}
override fun onAuthenticationError(
errorCode: Int, errString: CharSequence
) {
super.onAuthenticationError(errorCode, errString)
//Error auth
if (errorCode == BiometricConstants.ERROR_USER_CANCELED) {
//Some long code
}
}
if(errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON) {
Log.e(TAG, "User clicked")
//loginWithPassword() // I don't know what to implement here
}
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
//Failed auth
}
})
biometricPrompt.authenticate(promptInfo)
}
We have an issue that occurs at every method call for limited periods of time. Then it works as expected. The issue is that the code produces double WHERE clauses.
We're using Servicestack 4.5.14
The method we have:
protected static void InsertOrUpdate<T>(
IDbConnection connection,
T item,
Expression<Func<T, bool>> singleItemPredicate,
Expression<Func<T, object>> updateOnlyFields = null)
{
var type = item.GetType();
var idProperty = type.GetProperty("Id");
if (idProperty == null)
{
throw new Exception("Cannot insert or update on a class with no ID property");
}
var currentId = (int)idProperty.GetValue(item);
if (currentId != 0)
{
throw new Exception("Cannot insert or update with non-zero ID");
}
var query = connection.From<T>().Where(singleItemPredicate).WithSqlFilter(WithUpdateLock);
T existingItem;
try
{
existingItem = connection.Select(query).SingleOrDefault();
Log.Verbose(connection.GetLastSql);
}
catch (SqlException)
{
Log.Verbose(connection.GetLastSql);
throw;
}
if (existingItem == null)
{
Insert(connection, item);
return;
}
var existingId = (int)idProperty.GetValue(existingItem);
idProperty.SetValue(item, existingId);
try
{
var affectedRowCount = connection.UpdateOnly(item, onlyFields: updateOnlyFields, where: singleItemPredicate);
Log.Verbose(connection.GetLastSql);
if (affectedRowCount != 1)
{
throw new SwToolsException("Update failed");
}
}
catch (SqlException)
{
Log.Verbose(connection.GetLastSql);
throw;
}
}
When it all works, an example output from the logs could be:
SELECT "Id", "Application", "Hostname", "LastContact", "Version", "ToolState", "ServerState"
FROM "ca"."ExecutionHost"
WITH (UPDLOCK) WHERE ("Hostname" = #0)
UPDATE "ca"."ExecutionHost" SET "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE ("Hostname" = #0)
When it fails, the output (same session, only seconds later) was:
SELECT "Id", "Application", "Hostname", "LastContact", "Version", "ToolState", "ServerState"
FROM "ca"."ExecutionHost"
WITH (UPDLOCK) WHERE ("Hostname" = #0)
UPDATE "ca"."ExecutionHost" SET "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE "LastContact"=#LastContact, "Version"=#Version, "ToolState"=#ToolState, "ServerState"=#ServerState WHERE ("Hostname" = #0)
Marked in bold is the addition to the SQL that makes the call to fail. It seems that it adds an additional WHERE clause with the content from the SET clause.
We've been debugging this for a while and don't really know if the issue is on "our" side or in Servicestack.
Any ideas on where to continue?
This program accesses a text file with text elements separated by commas. The elements register in the variables I created. Except for the last one. The error then occurs. The program works fine with the default whitespace delimitor for the scanner class (the text file is adjusted accodingly) but fails when I use a comma as the delimitor. Could someone please supply some insight.
Text Data:
smith,john,10
stiles,pat,12
mason,emrick,12
Code:
public void openFile(String f)
{
try{
x = new Scanner(new File(f));
x.useDelimiter(",");
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNext())
{
String lName = x.next().trim();
**String fName = x.next().trim();**
String grade = x.next().trim();
if(fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}
The problem relies on the fact that you called x.useDelimiter(","); on your Scanner in function openFile().
Since your text data is:
smith,john,10
stiles,pat,12
mason,emrick,12
the Scanner sees it as:
"smith,john,10\nstiles,pat,12\nmason,emrick,12"
So what happens when you execute your code is:
1: x.hasNext() ? Yes
x.next().trim() => "smith"
x.next().trim() => "john"
x.next().trim() => "10\nstiles"
2: x.hasNext() ? Yes
x.next().trim() => "pat"
x.next().trim() => "12\nmason"
x.next().trim() => "emrick"
3: x.hasNext() ? Yes
x.next().trim() => "12"
x.next().trim() => Error!
To fix this you can either edit the file and change all the \n with ,, or use a first Scanner to get all the lines, and another one to get the tokens, as shown here:
public void openFile(String f)
{
try{
x = new Scanner(new File(f)); // Leave default delimiter
} catch(Exception e){
System.out.println("File could not be found please check filepath");
}
}
public boolean checkNameRoster()
{
openFile(file);
boolean b = false;
while(x.hasNextLine()) // For each line in your file
{
Scanner tk = new Scanner(x.nextLine()).useDelimiter(","); // Scan the current line
String lName = x.next().trim();
String fName = x.next().trim();
String grade = x.next().trim();
if (fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
{
b = true;
}
}
closeFile();
return b;
}
I want to intercept hardware back buttion in my Xamarin Forms Portable app, At First I have login page,You have to login and it will navigate to my Homepage2.. after going to my homepage2, when i click on my hardware backbutton...It goes to my login page or the pages i opened previously.. I want to Prevent it. Can anyone please resolve me this issue..
here is my login page
public LoginPage()
{
InitializeComponent();
}
public async void LoginBtn_Clicked(object sender, EventArgs e)
{
if (UserName.Text == null || password1.Text == null)
{
DisplayAlert("Alert ! ", "Please Enter UserName Or/Password!", "OK");
}
else
{
string uname = UserName.Text;
string pswd = password1.Text;
LoginService objservice = new LoginService();
LoginTokenModel result = await objservice.GetLogin(uname, pswd);
LoginTokenModel logintokenmodel = new LoginTokenModel();
logintokenmodel.User_Id = result.User_Id;
var Login_Token = result.Login_Token;
int user_Id = result.User_Id;
if (uname == result.User_Nmae)
{
// HomePage2 HOMEPge = new HomePage2();
await Navigation.PushModalAsync(new HomePage2(user_Id));
}
else
{
DisplayAlert("Alert ! ", "Invalid Credentials!", "OK");
}
}
}
Replace the App's MainPage with your Homepage2.
as you are not coming back on Login page you don'n want it in the NavigationStack.
This is what I do on successful Login:
if (uname == result.User_Nmae)
{
App.Current.MainPage = new HomePage2(user_Id);
}
In addition you can also keep this user_Id stored for the second time when the user enters again in application properties and check if the user_Id exists or not, if it does just navigate to Homepage2
Application.Current.Properties["id"] = user_Id;
in App.cs onStart
if (Application.Current.Properties.ContainsKey("id"))
{
var user_Id = Application.Current.Properties["id"] as string;
MainPage.Navigation.PushModalAsync(new Views.Homepage2(user_Id ));
}
else
{
MainPage.Navigation.PushModalAsync(new Views.Login());
}
I have the following piece of code for which I'm writing the unit test using Mockito
if (user != null) {
LDAPCustomer cust = getLDAPCustomer();
LDAPAuthorization auth = getLDAPAuthorization();
cust = getCustomerData( new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.CUSTOMER_MAIL, user));
if (cust != null)
auth = getAuthorizationData(new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.AUTHORIZATION_GUID, cust.getCstAuthGuid()));
if (cust != null && auth!= null && cust.getCstManageeGuids().size() == 1) {
String custGuid = cust.getCstCustGuid();
if (cust.getCstManageeGuids().get(0).equals(custGuid)) {
//No secondary user
try
{
deleteUserAssociations(cust.getCstCustGuid());
resetAuthorization(auth.getCstAuthGuid());
logger.info(cust.getCstCustGuid()+" user successfully perged.");
} catch (Exception e) {
logger.error("Error occured whie try to purging user: "+MiscUtility.getStackTrace(e));
throw new Exception("Error occured whie try to purging user: "+e.getMessage());
}
}
}
}
and here's the mockito code
int size = 1;
//Define the Stub
Mockito.doReturn(mockCustomer).when(ldap).getLDAPCustomer();
Mockito.doReturn(mockAuthorization).when(ldap).getLDAPAuthorization();
Mockito.doReturn(mockCustomer).when(ldap).getCustomerData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.doReturn(mockAuthorization).when(ldap).getAuthorizationData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.when(mockCustomer.getCstManageeGuids().size()).thenReturn(size);
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn("mockCust");
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Mockito.doNothing().when(ldap).deleteUserAssociations(Mockito.anyString());
Mockito.doNothing().when(ldap).resetAuthorization(Mockito.anyString());
I'm getting a ClassCastException as below
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$1ebf8eb1 cannot be cast to java.lang.String
at the line
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Appreciate any help.
Solved it by breaking down the chain.
List<String> lst = new ArrayList<String>();
lst.add("mockVal");
Mockito.when(mockCustomer.getCstManageeGuids()).thenReturn(lst);