android 23 uri permission denial - uri

i have a code that doing the following:
i got READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE in manifest
i m getting photos uri from phone you choose and put it into fragment and insert into viewpager.
it works fine on sdk 22 below.
but as on android 23 it keep on saying
permission denial java.lang.SecurityException: Permission Denial: opening provider com.google.android.apps.photos.contentprovioder.MediaContentProvider from ProcessRecord
which is refer to my code on line in fragment page
/*********************
bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, option);
which i put inside reSize() method
**********************/
i have trying to read develop console documents and notice we need to check permission and ask user for it.
my questions is
1. which permission should i ask, i have tried READ and WRITE
2. where should i surround the check permission for, it is outside the method? or just surround the line.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasPermission = checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
RESULT_PERMS_INITIAL);
} else {
bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, option);
}
} else {
bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, option);
}
and on request for result
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
if (requestCode == RESULT_PERMS_INITIAL) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
bitmap = resizeBitmap(uri, getActivity().getApplicationContext());
}
else {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
}
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

For API-23 Android introduced new permission types. You should read this.
For the example please follow these page
RuntimePermissionsBasic
RuntimePermissions
I hope, it will work for you.

Related

Obscure Unity Firebase Realtime Database Error: "Custom Run loops are not supported"?

I am currently attemping to build a custom Editor tool for Unity that utilizes the Firebase Realtime Database. This tool would allow someone to right-click on a scene asset in the inspector and select to 'lock' or 'unlock' the scene. Within our Firebase Database, this locking is represented by a dictionary, with each scene name as a key and each value being either "locked" or "unlocked". This funcitonality will be expanded later, but for now, I'm just trying to get things set up so that I can actually connect to and use the Firebase Realtime Database.
I had looked at the Firebase Quickstart Unity project for the Realtime Database (the one that functions like a leaderboard) and saw that it worked fine. I could replace the database URL in the project with the URL for my app's database, and when I entered in values, they appeared inside my realtime database.
So, I based the code for my custom editor script on the code from the quickstart. In fact, I copy-pasted most of it. I will post the script itself, and then describe the errors I receive, as well as the lines that give the errors:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Firebase;
using Firebase.Unity.Editor;
using Firebase.Database;
[CustomEditor(typeof(SceneAsset))]
[ExecuteInEditMode]
public class SceneLockingEditor : Editor
{
static string sceneName;
DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;
protected virtual void OnEnable()
{
Debug.Log("OnEnable Called");
sceneName = target.name;
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available)
{
InitializeFirebase();
}
else
{
Debug.LogError(
"Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
// Initialize the Firebase database:
protected virtual void InitializeFirebase()
{
Debug.Log("Initializing Firebase");
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl(CENSORING MY DATABASE SORRY);
if (app.Options.DatabaseUrl != null) app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
}
static TransactionResult SceneLockTransaction(MutableData mutableData)
{
List<object> sceneLocks = mutableData.Value as List<object>;
if (sceneLocks == null)
{
sceneLocks = new List<object>();
}
if(mutableData.ChildrenCount > 0)
{
//Look at every child in the scene locks directory.
foreach (var child in sceneLocks)
{
Debug.Log("Checking next child.");
if (!(child is Dictionary<string, object>))
continue;
//If we find the scene we're looking for...
Debug.Log("Checking if the scene has the name we want");
foreach(string key in ((Dictionary<string, object>)child).Keys)
{
Debug.Log("Key: " + key);
}
if(((Dictionary<string, object>)child).ContainsKey(sceneName))
{
string childLockStatus = (string)((Dictionary<string, object>)child)["lockStatus"];
//If the scene is already locked, just abort.
if (childLockStatus == "locked")
{
Debug.Log("Scene is already locked. Abort.");
return TransactionResult.Abort();
}
else
{
Debug.Log("Scene existed in the database and was not locked. Locking it.");
// If the scene existed in the database but was not locked, we will lock it.
((Dictionary<string, object>)child)[sceneName] = "locked";
// You must set the Value to indicate data at that location has changed.
mutableData.Value = sceneLocks;
return TransactionResult.Success(mutableData);
}
}
}
}
Debug.Log("Scene did not exist in the database. Adding it as locked.");
// If the scene didn't exist in the database before, we will add it as locked.
Dictionary<string, object> newSceneLock = new Dictionary<string, object>();
newSceneLock[sceneName] = "locked";
sceneLocks.Add(newSceneLock);
// You must set the Value to indicate data at that location has changed.
mutableData.Value = sceneLocks;
return TransactionResult.Success(mutableData);
}
static TransactionResult SceneUnlockTransaction(MutableData mutableData)
{
List<object> sceneLocks = mutableData.Value as List<object>;
if (sceneLocks == null)
{
sceneLocks = new List<object>();
}
if (mutableData.ChildrenCount > 0)
{
//Look at every child in the scene locks directory.
foreach (var child in sceneLocks)
{
Debug.Log("Checking next child.");
if (!(child is Dictionary<string, object>))
continue;
//If we find the scene we're looking for...
Debug.Log("Checking if the scene has the name we want");
foreach (string key in ((Dictionary<string, object>)child).Keys)
{
Debug.Log("Key: " + key);
}
if (((Dictionary<string, object>)child).ContainsKey(sceneName))
{
string childLockStatus = (string)((Dictionary<string, object>)child)["lockStatus"];
//If the scene is already locked, just abort.
if (childLockStatus == "unlocked")
{
Debug.Log("Scene is already unlocked. Abort.");
return TransactionResult.Abort();
}
else
{
Debug.Log("Scene existed in the database and was locked. Unlocking it.");
// If the scene existed in the database but was not locked, we will lock it.
((Dictionary<string, object>)child)[sceneName] = "unlocked";
// You must set the Value to indicate data at that location has changed.
mutableData.Value = sceneLocks;
return TransactionResult.Success(mutableData);
}
}
}
}
Debug.Log("Scene did not exist in the database. Adding it as unlocked.");
// If the scene didn't exist in the database before, we will add it as locked.
Dictionary<string, object> newSceneLock = new Dictionary<string, object>();
newSceneLock[sceneName] = "unlocked";
sceneLocks.Add(newSceneLock);
// You must set the Value to indicate data at that location has changed.
mutableData.Value = sceneLocks;
return TransactionResult.Success(mutableData);
}
static public void AddSceneLock()
{
Debug.Log("Attempting to add scene lock to database.");
DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("SceneLocks");
Debug.Log("Running Transaction...");
// Use a transaction to ensure that we do not encounter issues with
// simultaneous updates that otherwise might create more than MaxScores top scores.
reference.RunTransaction(SceneLockTransaction)
.ContinueWith(task => {
if (task.Exception != null)
{
Debug.Log(task.Exception.ToString());
}
else if (task.IsCompleted)
{
Debug.Log("Transaction complete.");
}
});
}
static public void RemoveSceneLock()
{
Debug.Log("Attempting to add scene lock to database.");
DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("SceneLocks");
Debug.Log("Running Transaction...");
// Use a transaction to ensure that we do not encounter issues with
// simultaneous updates that otherwise might create more than MaxScores top scores.
reference.RunTransaction(SceneUnlockTransaction)
.ContinueWith(task => {
if (task.Exception != null)
{
Debug.Log(task.Exception.ToString());
}
else if (task.IsCompleted)
{
Debug.Log("Transaction complete.");
}
});
}
[MenuItem("CONTEXT/SceneAsset/Lock Scene", false, 0)]
public static void LockScene()
{
Debug.Log("LockScene Called for scene " + sceneName + ".");
AddSceneLock();
}
[MenuItem("CONTEXT/SceneAsset/Unlock Scene", false, 0)]
public static void UnlockScene()
{
Debug.Log("UnlockScene Called for scene " + sceneName + ".");
RemoveSceneLock();
}
}
The errors always come from this line:
FirebaseDatabase.DefaultInstance.GetReference("SceneLocks");
Any line that has to do with "FirebaseDatabase.DefaultInstance" will throw one of the following two errors
Error 1:
InvalidOperationException: SyncContext not initialized.
Firebase.Unity.UnitySynchronizationContext.get_Instance ()
Firebase.Platform.PlatformInformation.get_SynchronizationContext ()
Firebase.FirebaseApp.get_ThreadSynchronizationContext ()
Firebase.Database.DotNet.DotNetPlatform+SynchronizationContextTarget..ctor ()
Firebase.Database.DotNet.DotNetPlatform.NewEventTarget (Firebase.Database.Internal.Core.Context c)
Firebase.Database.Internal.Core.Context.EnsureEventTarget ()
Firebase.Database.Internal.Core.Context.InitServices ()
Firebase.Database.Internal.Core.Context.Freeze ()
Firebase.Database.Internal.Core.RepoManager.CreateLocalRepo (Firebase.Database.Internal.Core.Context ctx, Firebase.Database.Internal.Core.RepoInfo info, Firebase.Database.FirebaseDatabase firebaseDatabase)
Firebase.Database.Internal.Core.RepoManager.CreateRepo (Firebase.Database.Internal.Core.Context ctx, Firebase.Database.Internal.Core.RepoInfo info, Firebase.Database.FirebaseDatabase firebaseDatabase)
Firebase.Database.FirebaseDatabase.EnsureRepo ()
Firebase.Database.FirebaseDatabase.get_RootReference ()
SceneLockingEditor.OnInspectorGUI () (at Assets/Bitloft/SCRIPTS/Editor/SceneLockingEditor.cs:37)
UnityEditor.InspectorWindow.DrawEditor (UnityEditor.Editor[] editors, Int32 editorIndex, Boolean rebuildOptimizedGUIBlock, System.Boolean& showImportedObjectBarNext, UnityEngine.Rect& importedObjectBarRect) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1242)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
Error 2:
Exception: Custom Run loops are not supported!
Firebase.Database.Internal.Core.Context.GetExecutorService ()
Firebase.Database.Internal.Core.Context.GetConnectionContext ()
Firebase.Database.Internal.Core.Context.NewPersistentConnection (Firebase.Database.Internal.Connection.HostInfo info, IDelegate delegate_)
Firebase.Database.Internal.Core.Repo..ctor (Firebase.Database.Internal.Core.RepoInfo repoInfo, Firebase.Database.Internal.Core.Context ctx, Firebase.Database.FirebaseDatabase firebaseDatabase)
Firebase.Database.Internal.Core.RepoManager.CreateLocalRepo (Firebase.Database.Internal.Core.Context ctx, Firebase.Database.Internal.Core.RepoInfo info, Firebase.Database.FirebaseDatabase firebaseDatabase)
Firebase.Database.Internal.Core.RepoManager.CreateRepo (Firebase.Database.Internal.Core.Context ctx, Firebase.Database.Internal.Core.RepoInfo info, Firebase.Database.FirebaseDatabase firebaseDatabase)
Firebase.Database.FirebaseDatabase.EnsureRepo ()
Firebase.Database.FirebaseDatabase.get_RootReference ()
SceneLockingEditor.OnInspectorGUI () (at Assets/Bitloft/SCRIPTS/Editor/SceneLockingEditor.cs:37)
UnityEditor.InspectorWindow.DrawEditor (UnityEditor.Editor[] editors, Int32 editorIndex, Boolean rebuildOptimizedGUIBlock, System.Boolean& showImportedObjectBarNext, UnityEngine.Rect& importedObjectBarRect) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1242)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
It's always one error or the other, and I can't determine what causes one error to appear rather than the other. Both errors stop whatever operation I'm trying to do on the database, which means I can't interact with my database at all.
I've taken a look at the quickstart projects and watched some videos of people setting up Firebase to work with their projects, and I can't seem to determine what I have messed up during the process. I have imported my google-services.json into the unity project. The quickstart projects worked just fine interacting with my database. It's just this particular script that won't work. I cannot find any mention of these two errors anywhere on Google. I even contacted the official Firebase support and they couldn't give me any advice on what the errors mean or what could be causing them.
I considered one problem might be in my initialization function. Instead of doing:
FirebaseApp app = FirebaseApp.DefaultInstance;
I figured that maybe I am supposed to use FirebaseApp.Create() with a custom name passed in, but that resulted in the same errors being thrown on the same line. I am at a loss for how to proceed with this problem. I don't know of anyone else who has had these particular errors, and I've done very much experimentation with different ways to access the database over the past several days. If anybody has an idea of what I am doing wrong here, or what causes these errors (and, how to fix them), I would really appreciate it.
At first you should initialize firebase with new instance of FirebaseApp with unique name. I do it like this:
FirebaseApp firebaseApp = FirebaseApp.Create(
FirebaseApp.DefaultInstance.Options,
"FIREBASE_EDITOR");
The second is setup references (DatabaseReference, StorageReference etc.) with this firebaseApp instance and use it only after FirebaseApp.CheckAndFixDependenciesAsync()
Overall code will look like this:
public static void Initialize(bool isEditor = false)
{
if (isEditor)
{
FirebaseApp firebaseApp = FirebaseApp.Create(
FirebaseApp.DefaultInstance.Options,
"FIREBASE_EDITOR");
firebaseApp.SetEditorDatabaseUrl("https://project.firebaseio.com/");
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
if (task.Result == DependencyStatus.Available)
{
database = FirebaseDatabase.GetInstance(firebaseApp).RootReference;
storage = FirebaseStorage.GetInstance(firebaseApp).RootReference;
auth = FirebaseAuth.GetAuth(firebaseApp);
}
else
{
Debug.LogError(
"Could not resolve all Firebase dependencies: " + task.Result);
}
});
}
else
{
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://project.firebaseio.com/");
database = FirebaseDatabase.DefaultInstance.RootReference;
storage = FirebaseStorage.DefaultInstance.RootReference;
auth = FirebaseAuth.DefaultInstance;
}
IsInitialized = true;
}
I had the same errors. I spent several hours solving this and it worked for me

Fixed a bug that KAA-1594: error after attaching endpoint to user

The bug in kaa 0.10 have Influenced my application development. So I try to fix it.Then I Compared the code of the kaa 0.9 and kaa 0.10. I have found the differences in class EndpointServiceImpl of Kaa DAO interface modular:there are two methods of attachEndpointToUser in it
1,
public EndpointProfileDto attachEndpointToUser(String endpointUserId, String
endpointAccessToken) throws KaaOptimisticLockingFailureException {
LOG.info("Try to attach endpoint with access token {} to user with {}", endpointAccessToken,
endpointUserId);
validateString(endpointUserId, "Incorrect endpointUserId "
+ endpointUserId);
EndpointUser endpointUser = endpointUserDao.findById(endpointUserId);
LOG.trace("[{}] Found endpoint user with id {} ", endpointUserId, endpointUser);
if (endpointUser
!= null) {
EndpointProfile endpoint = endpointProfileDao.findByAccessToken(endpointAccessToken);
LOG.trace("[{}] Found endpoint profile by with access token {} ", endpointAccessToken,
endpoint);
if (endpoint
!= null) {
if (endpoint.getEndpointUserId()
== null
|| endpointUserId.equals(endpoint.getEndpointUserId())) {
LOG.debug("Attach endpoint profile with id {} to endpoint user with id {} ", endpoint
.getId(), endpointUser.getId());
List<String> endpointIds = endpointUser.getEndpointIds();
**/*if (endpointIds
!= null
&& endpointIds.contains(endpoint.getId())) {
LOG.warn("Endpoint is already assigned to current user {}.", endpoint
.getEndpointUserId());
return getDto(endpoint);
}*/**
if (endpointIds
== null) {
endpointIds = new ArrayList<>();
endpointUser.setEndpointIds(endpointIds);
}
endpointIds.add(endpoint.getId());
endpointUser = endpointUserDao.save(endpointUser);
while (true) {
try {
endpoint.setEndpointUserId(endpointUser.getId());
LOG.trace("Save endpoint user {} and endpoint profile {}", endpointUser, endpoint);
endpoint = endpointProfileDao.save(endpoint);
break;
} catch (KaaOptimisticLockingFailureException ex) {
LOG.warn("Optimistic lock detected in endpoint profile ", Arrays.toString(endpoint
.getEndpointKey()), ex);
endpoint = endpointProfileDao.findByKeyHash(Sha1HashUtils.hashToBytes(endpoint
.getEndpointKey()));
}
}
return getDto(endpoint);
} else {
LOG.warn("Endpoint is already assigned to different user {}. Unassign it first!.",
endpoint.getEndpointUserId());
throw new DatabaseProcessingException("Endpoint is already assigned to different user.");
}
} else {
LOG.warn("Endpoint with accessToken {} is not present in db.", endpointAccessToken);
throw new DatabaseProcessingException("No endpoint found for specified accessToken.");
}
} else {
LOG.warn("Endpoint user with id {} is not present in db.", endpointUserId);
throw new DatabaseProcessingException("Endpoint user is not present in db.");
}
}
2,
public EndpointProfileDto attachEndpointToUser(String userExternalId, String tenantId,
EndpointProfileDto profile) {
validateString(userExternalId, "Incorrect userExternalId "
+ userExternalId);
EndpointUser endpointUser = endpointUserDao.findByExternalIdAndTenantId(userExternalId,
tenantId);
if (endpointUser
== null) {
LOG.info("Creating new endpoint user with external id: [{}] in context of [{}] tenant",
userExternalId, tenantId);
EndpointUserDto endpointUserDto = new EndpointUserDto();
endpointUserDto.setTenantId(tenantId);
endpointUserDto.setExternalId(userExternalId);
endpointUserDto.setUsername(userExternalId);
endpointUser = endpointUserDao.save(endpointUserDto);
}
List<String> endpointIds = endpointUser.getEndpointIds();
if (endpointIds
== null) {
endpointIds = new ArrayList<>();
endpointUser.setEndpointIds(endpointIds);
} **/*else if (endpointIds
!= null
&& endpointIds.contains(profile.getId())) {
LOG.warn("Endpoint is already assigned to current user {}.", profile.getEndpointUserId());
return profile;
}*/**
endpointIds.add(profile.getId());
endpointUser = endpointUserDao.save(endpointUser);
profile.setEndpointUserId(endpointUser.getId());
while (true) {
try {
LOG.trace("Save endpoint user {} and endpoint profile {}", endpointUser, profile);
return saveEndpointProfile(profile);
} catch (KaaOptimisticLockingFailureException ex) {
LOG.warn("Optimistic lock detected in endpoint profile ", Arrays.toString(profile
.getEndpointKey()), ex);
profile = findEndpointProfileByKeyHash(profile.getEndpointKeyHash());
profile.setEndpointUserId(endpointUser.getId());
}
}
}
The code above is in kaa 0.10 .Compared with the Kaa 0.9, it Added a judgment condition that in Bold code above:(
if(endpointIds!=null&&endpointIds.contains(endpoint.getId())) )
and
else if (endpointIds
!= null
&& endpointIds.contains(profile.getId())).
I have made a test that Commented the judgment condition codes. The result is OK. I want to know that the fix method is available .
You can contribute to kaa.
Description on this procedure you can find here.
In few words about it:
fork kaa repository here.
crete new branch with the content of branch you want to fix(release-0.10)
commit (commit message must begin with "KAA-1594:") and push changes into your fork.
create a pull request on kaa page (compare original kaa branch release-0.10 and your new edited branch)
allow changes from owners
you are done!
UPD: would be great if you describe the problem and your solution in issue on github it will help us to make official fix faster.

Intent returns null onActivityResult in Fragment

Android 4.4 tested in Eclipse.
I've followed the lines as developers said. So in my fragment I put:
public void tomarfoto() {
// Check Camera
if (MainActivity.if_cam) {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
this.startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} else {
//Toast.makeText(getActivity(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
After that, I set this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(getActivity(), "Image saved to:\n" +data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == Activity.RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
The problem is that data intent is null and provokes this:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=android:fragment:0, request=1888, result=-1, data=null}
to activity {com.myapp.MainActivity}: java.lang.NullPointerException
I don't understand so much but apparently the onActivityResult is disconnected from the fragment who has called it so, it can't receive data results. How can I solve this?. The launchMode="singleTask" or singleInstance is not my problem, I didn't settled this.
The pictures are saved properly in the directory held by fileUri. Help.

Link to Sql Update Row

Ok i need to update field Active to True this is code
public static bool FirstLogin(Guid ActivationCode)
{
using (InfinityNightDataContext data = new InfinityNightDataContext())
{
User user = data.Users.Single(User => User.EmailActivation == ActivationCode);
if (user != null)
{
user.Active = true;
user.Exp = "i HAs here";
data.SubmitChanges();
InstallMembershipCookie(user.UserId, user.Email, user.Password, user.UserType, user.FirstName, user.UserImg, "", true);
return true;
}
else
{
return false;
}
}
}
and after data.SubmitChanges(); i can see the changes on the object user but not in DataBase in other function this works but in this case it's don't work ..
any one know what is the problem?
One possible option (as you haven't said much about your setup): Are you using a local database, or a user instance, i.e. does your connection string contain AttachDbFileName? If so is there another copy of the database in your active bin folder (bin\debug, for instance)? If there is can you attach that to SQL express and see if your change has appeared?

Using webdriver, I am able to run successfully for the first user & for next user it is failing at if condition. If condition is not working properly

If condition is not working properly. I have some set of user id to login to my application, using webdriver, I am able to run successfully for the first user & for next user it is failing at if condition. Please find the code below and it has to check the more if conditions to run successfully.
for (int i = 1; i < sh.getRows(); i++)
{
while(iter.hasNext())
{
System.out.println("Main Window ID :"+iter.next());
}
driver.findElement(By.id("lgnLogin_UserName")).clear();
driver.findElement(By.id("lgnLogin_UserName")).sendKeys(sh.getCell(0,
i).getContents());
driver.findElement(By.id("lgnLogin_Password")).clear();
driver.findElement(By.id("lgnLogin_Password")).sendKeys(sh.getCell(1,
i).getContents());
driver.findElement(By.id("lgnLogin_LoginButton")).click();
Thread.sleep(5000L);
if(driver.findElements(By.linkText("Logout")) != null)
{
driver.findElement(By.id("ctl00_Header_Lbtn_Logout")).click();
msg ="Valid User Login";
System.out.println(msg);
}
else
if(driver.getTitle().contains("700Dealers Inc."))
{
driver.findElement(By.xpath("//table[#id='lgnLogin']/tbody
/tr/td/table/tbody/tr[4]/td")).getText();
System.out.println(msg);
}
else
if(driver.getTitle().contains("Security Question And Answers"))
{
driver.findElement(By.xpath("//table[#id='Table_01']/tbody
/tr[5]/td/table/tbody/tr/td/table/tbody/tr/td/span/span[1]")).getText();
System.out.println(msg);
}
else
if(driver.getTitle().contains("700 credit Change Password"))
{
driver.findElement(By.xpath("//div[#id='panelscreen']/table
/tbody/tr/th/span")).getText();
System.out.println(msg);
}
Please help me out in this issue. Help will be appreciated.
Thread.sleep(5000L); is probably the root of your problems.
So, you may want to replace that :
Thread.sleep(5000L);
if(driver.findElements(By.linkText("Logout")) != null)
with an explicit wait :
try {
WebElement logout = (new WebDriverWait(driver, 5))
.until(new ExpectedCondition<WebElement>(){
#Override
public WebElement apply(WebDriver d) {
return d.findElement(By.linkText("Logout"));
}});
//Logout found, do stuff
} catch(TimeoutException e) {
//No logout element, do stuff
}

Resources