Populating a listview contents with an array - arrays

I have created a function that would be able to place the array contents into a listview, Here is my progress so far.
<div id="MainPage" data-role="page" >
<div data-role="content">
RENAME
</div>
</div>
<div id="ViewPage" data-role="page" >
<div data-role="content">
<ul id="viewlist" data-role="listview" data-filter="true" data-filter-placeholder="Sample Contents" data-inset="true">
<!-- array contents goes here -->
</ul>
</div>
</div>
<script>
var sampleContent = new Array( );
displayArray( )
{
for(var scan=0; scan<sampleContent.length; detect++)
{
$('#viewlist').append('<li>' + sampleContent[scan] + '</li>');
}
}
</script>
My code works during the first press of the button but when i pressed it the second time, the list view becomes messed up.
Any help or advice will be glady accepted thanks in advance.
edited, i have figured out how to do it but I am having problems during the second press of the button.

First of i don't want to be rude but i think you should start first to read some basics about android.
Like:
Android Activities , life cycle of activities
Layout in Android (how to add button on an activity then respond to a click etc) , different existing Layout in android and android widget (like the listView for example)
of course there are a lot more to read but it s a good way to start.
However i will provide you codes that will do what you are asking for and i will try to explain as much as i can
First of all you need to create the other activity and inside the layout of that activity insert a listview
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
then the java code of the other activity will look like this
public class MainActivity2 extends Activity {
//create the array adapter that will input your array and convert it into a list of view
ArrayAdapter<String> arrayAdapter;
String[] list;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
listView = (ListView)findViewById(R.id.listView);
// get the array from ressource and insert them on an array
list = getResources().getStringArray(R.array.listArray);
// then create the arrayadpater with input your array of string if you dont get //anything here just read android documentation about arrayAdapter
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list );
//then set the adapter to your listView
listView.setAdapter(arrayAdapter);
}
}
res xml file
<resources>
<string-array name="listArray">
<item>Apple</item>
<item>Banana</item>
<item>Cherry</item>
<item>Cranberry</item>
<item>Grape</item>
<item>Grape</item>
</string-array>
</resources
>
Hope it will help

Just add .listview('refresh') after you have added all items.
$('#viewlist').listview('refresh');
If you want to empty the list each time and refill it, call .empty() before the for loop:
$('#viewlist').empty();
To use better jquery mobile coding, structure your code like this:
Take the onclick out of the anchor tag and add an id:
<a id="viewPageBtn" href="#ViewPage" data-role="button" >RENAME</a>
In your script tag, handle pagecreate on the main page, and within it handle the click event of the anchor:
$(document).on("pagecreate", "#MainPage", function(){
var sampleContent = ["item 1", "item 2", "item 3"];
$("#viewPageBtn").on("click", function(){
$('#viewlist').empty();
for(var scan=0; scan < sampleContent.length; scan++)
{
$('#viewlist').append('<li>' + sampleContent[scan] + '</li>').listview('refresh');
}
$('#viewlist').listview('refresh');
});
});

Related

Filter card list with Razor View

Im trying to make a filter like in AngularJS when u use:
ng-repeat="u in users | filter:searchBar">
And your input filter looks like
<input type="text" id="searchBar" placeholder="start typing" ng-model="searchBar">
But the things its that im working on MVC with Razor View and I do not know how to approach this filter.
The list of cards is made with a foreachlike this:
#foreach{ var item in Models){
<div class="card">
<div class="card-container">
some content
</div>
</div>
}
Any ideas?
You can do the filtering with ajax. Here is a server side filtering solution.
First, you should move the code which renders the result to a partial view. Let's say you created a partial view called CustomerList.cshtml. Move the list code to that.
#model IEnumerable<Customer>
#foreach (var item in Model)
{
<div class="card">
<div class="card-container">
#item.Name
</div>
</div>
}
Now in your main view, you can call this partial view and pass the data to it. Wrap the call to the partial view in a container div. Add a input element for user to enter the search key. Assuming your main view is also strongly typed to IEnumerable<Customer>
#model IEnumerable<Customer>
<input type="text" id="search" data-url="#Url.Action("Index")" />
<div id="div-items">
#Html.Partial("CustomerList",Model)
</div>
Now we need to have some javascript code which listen to the keyup event on the search input, read the value of it and make an ajax call to the server where it uses the search key and get the filtered set of data, pass that to the same partial view and return the partial view result.
You can use jQuery $.get method
$(document).ready(function () {
$("#search").keyup(function() {
var v = $(this).val();
$.get($(this).data("url"), { searchKey: v }).done(function(res) {
$("#div-items").html(res);
});
});
});
Now make sure your server action method returns the filtered data like this
public ActionResult Index(string serchKey="")
{
var items = db.Customers.AsQueryable();
if (!String.IsNullOrEmpty(searchKey))
{
items = items.Where(a => a.Name.StartsWith(searchKey));
}
var t = items.ToList();
if (Request.IsAjaxRequest())
{
return PartialView("CustomerList",t );
}
return View(t);
}
Another option is to do client side filtering. on the items. But if i am going that direction, i would choose a client side MVC framework like angular to do that for me

Strange behaviour with ng-bind angular

So wanted to have a spinning cube with pictures on, because that is what all the cool kids want. Then decided that I wanted to have it all in a database and use the mean stack, so set that up.
Here comes the problem. On the index.html version, the cube sometimes messes up and moves to the screen blocking everything else out. Just open the link below and click the menu a few different menu options a few time and you'll see what I mean.
http://v-ghost.port0.org:8081/TESTCube/public/index.html
Worked a long while trying to figure out what was wrong, and it turns out that it is related to how I load the menu, I tried to generate it using ng-bind-html.
<figure class="front"><div id="front-page" ng-bind-html="showpane('front')"></div></figure>
<figure class="back"><div id="front-page" ng-bind-html="showpane('back')"></div></figure>
<figure class="right"><div id="front-page" ng-bind-html="showpane('right')"></figure>
<figure class="left"><div id="front-page" ng-bind-html="showpane('left')"></figure>
<figure class="top"><div id="front-page" ng-bind-html="showpane('top')"></figure>
<figure class="bottom"><div id="front-page" ng-bind-html="showpane('bottom')"></figure>
Strangely, if I change this to just use text (i.e. less fancy way):
<button class="show-front">Front</button><br/>
<button class="show-back">Back</button><br/>
<button class="show-right">Right</button><br/>
<button class="show-left">Left</button><br/>
<button class="show-top">Top</button><br/>
<button class="show-bottom">Bottom</button><br/>
Try it on
http://v-ghost.port0.org:8081/TESTCube/public/index-nobind.html, unbreakable (famous last words).
What I can't understand is why, why does me calling a function in a button break the cubes path?
Also, is there an easier way to get the value of a string in an array then building a function to get it in a ng-bind?
Tried to make it as easy as possible to test around, should be just to copy the html if you want to give it a try.
After much fiddling about I never manage to figure out why ng-bind behaved like this. And without a error message it was pretty hard to identify the problem.
If you have the same problem, one way to get around it is to just change the controller to present the data under an object. So start by defining the controller as app
<body ng-app="DBFScube" ng-controller="AppCtrl as app">
Then call a sub function (getmenuname) for each option.
<button class="show-front">{{app.getmenuname('front')}}</button><br/>
<button class="show-back">{{app.getmenuname('back')}}</button><br/>
<button class="show-right">{{app.getmenuname('right')}}</button><br/>
<button class="show-left">{{app.getmenuname('left')}}</button><br/>
<button class="show-top">{{app.getmenuname('top')}}</button><br/>
<button class="show-bottom">{{app.getmenuname('bottom')}}</button>
The controller looks like this
var app = this;
//
//$http.get("http://localhost:3000").success(function(CubeSides){
// app.CubeSides = CubeSides;
//})
$http.get("http://localhost:3000").success(function(CubeSides){
$scope.sides=CubeSides;
console.log("Loading data");
})
app.getmenuname = function(side) {
if($scope.sides === undefined) {
console.log("Not loaded fside " + side );
} else {
console.log("Got menu pane " + $scope.sides);
var fside = $filter('filter')($scope.sides, function (d) {return d.side === side;})[0];
console.log("Sending: " + fside.menuname);
return fside.menuname;
}
}
This probably isn't the right way of doing it, but if all you need to do is set the name on some buttons, it does the trick:)

Switch to new window only if it opens in new window and verify whether page is loaded properly

I'm trying to click all links in drop down. Some links will open a new browser window where some link will be loaded in the same page.
So, I want to switch to new window only whenever new window is opened and also need to confirm whether the new page is loaded properly.
I have already code to switch windows. But its trying to switch new window even though new window is not opened.
Could someone help me here.
Below is the relevant piece of HTML:
<html>
<div class="column span-8">
<div class="search-container align-center">
<div class="search">
<div class="search-dropdown" onclick="showHideUtilMenu(event, 'SearchMenu');">
<span id="searchoptionValue">Consumer</span>
<span id="dropdownarrow"</span>
<span id="searchurlValue" style="display: none;">http://</span>
<div id="SearchMenu" class="utility-menu combobox visible">
<ul class="menu-list">
<li class="menu-link">
<li class="menu-link divider">
<a onclick="getSearchOption('Consumer','http://');">Consumer</a>
...
Here is the code that I have used so far:
List<WebElement> list = driver.findElements(By.xpath("//*[#class='search-dropdown']/div[1]/ul/li"));
for (WebElement option : list)
{
String strLabel = option.getText();
if(strlabel.equalsIgnoreCase(value1) && country.equals("US"))
{
option.findElement(By.linkText(strLabel)).click();
CommonFunctions.waitForPageLoad();
CommonFunctions.switchWindow();
}
}
I hope you need methods something like below
class CommonFunctions {
/**
* It will wait for an element until it loads completely
*/
public static void waitForPageToLoad() {
int i=0;
while(isElementPresent(By.id("<specifySomeLocator>")))
{
Thread.sleep(100);
if(++i>500)
{
break;
}
}
}
/**
* It will Switch the control to new window if exist.
*/
public static boolean switchToWindow(String mainWindowHandle) {
Set<String> windowhandles=driver.getWindowhandles();
if(windowhandles.size()>1) {
windowhandles.remove(mainWindowHandle);
driver.switchTo().window((String)windowhandles.toArray()[0]);
return true;
} else {
return false;
}
}
}
And you try to implement your code something like below
List<WebElement> list = driver.findElements(By.xpath("//*[#class='search-dropdown']/div[1]/ul/li"));
for (int i=0;i<list.size();i++)
{
String strLabel = driver.findElements(By.xpath("//*[#class='search-dropdown']/div[1]/ul/li")).get(i).getText();
if(strlabel.equalsIgnoreCase(value1) && country.equals("US"))
{
String mainWindowHandle=driver.getWindowHandle();
option.findElement(By.linkText(strLabel)).click();
CommonFunctions.waitForPageToLoad();
if(CommonFunctions.switchToWindow(mainWindowHandle)){
//do your operation in new window
//close new window using ==> driver.close();
//switch back to main window ==> driver.switchTo().window(mainWindowHandle);
} else {
//do your operations in main window itself
}
}
}
FYI : If you iterate list of WebElements like below, it will throw StaleElementReferenceException while trying access second element in that list if page reloads while doing other operations with first element.
for (WebElement option : list)
{
String strLabel = option.getText();
//do some operations
}
For isElementPresent Method implementation click here
This is a general advice, rather than a direct answer to your question.
You can navigate from the current web-page to another web-page, using any of the following options:
driver.get(...);
driver.navigate().to(...);
driver.switchTo().frame(...);
driver.switchTo().window(...);
However, once you do that, any of the elements that you have obtained from the DOM of the previous web-page, may become "stale".
In order to avoid this, it is recommended that you first obtain all the URLs (strings) that you want to go to, and navigate to each one of them only afterwards.
Taking the code in your question as an example, you can change it as follows:
List<String> strLabels = new ArrayList<String>();
List<WebElement> list = driver.findElements(By.xpath("//*[#class='search-dropdown']/div[1]/ul/li"));
for (WebElement option : list)
{
String strLabel = option.getText();
if (strlabel.equalsIgnoreCase(value1) && country.equals("US"))
strLabels.add(strLabel);
}
for (String strLabel : strLabels)
{
driver.findElement(By.linkText(strLabel)).click();
CommonFunctions.waitForPageLoad();
CommonFunctions.switchWindow();
}

Wicket Checkgroupselector not working

my first question here. Hope I don't mess up too bad...
My problem is with the Wicket CheckGroupSelector. It doesn't work!
Here is the relevant code:
CheckGroup<AccountModel> groupMemberRecipients = new CheckGroup<AccountModel>("groupMemberRecipients", new ArrayList<AccountModel>());
groupMemberRecipients.add(new CheckGroupSelector("groupMemberSelector"));
ListView<AccountModel> memberRecipients = new ListView<AccountModel>("memberRecipients", groupParticipants) {
#Override
protected void populateItem(final ListItem<AccountModel> item) {
item.add(new Check<AccountModel>("groupMember", item.getModel()));
item.add(new Label("memberName", item.getModelObject().getFullName()));
}
};
memberRecipients.setReuseItems(true);
groupMemberRecipients.add(memberRecipients);
And the relevant html code:
<span wicket:id="groupMemberRecipients">
<input wicket:id="groupMemberSelector" type="checkbox"><b> Participants</b></input>
<div wicket:id="memberRecipients">
<input wicket:id="groupMember" type="checkbox"/><span wicket:id="memberName"></span>
</div>
</span>
I basically followed the wicket example of a Checkgroup word for word. On the form submit, I can retrieve the selected options just fine. Only the select/deselect all checkbox at the top doesn't work. Anyone know what I'm doing wrong?
Using wicket 6.9.1 btw

how to handle combo boxes of ExtJS in selenium webdriver

Hi i have a ExtJS based UI. I have come to know that in ExtJS the combo box is not a real combo box but a combination of input text field, image of drop down box and a list. Now i am able to identify the control but i am stuck at selecting the value from the list. In the HTML source i see that the list is appearing as a seperate div and gets attached at the end of the source when we click on the drop down. find below the HTML source of the drop down control.
{
<div id="ext-gen678" class="x-form-field-wrap x-form-btn-plugin-wrap" style="width: 556px;">
<div id="ext-gen676" class="x-form-field-wrap x-form-field-trigger-wrap x-trigger-wrap-focus" style="width: 521px;">
<input id="ext-gen677" type="hidden" name="GHVOg:#concat#~inputFld~ISGP_UNIV:ft_t_isgp.prnt_iss_grp_oid:0" value="">
<input id="GHVOg:Mixh8:0" class="x-form-text x-form-field gs_dropDown_input gs_req x-form-invalid x-form-focus" type="text" autocomplete="off" size="24" style="width: 504px;">
<img id="trigger-GHVOg:Mixh8:0" class="x-form-trigger x-form-arrow-trigger" alt="" src="../../ext/resources/images/default/s.gif">
}
find below the HTML source of the drop down list:
<div id="ext-gen726" class="x-layer x-combo-list x-resizable-pinned" style="position: absolute; z-index: 12007; visibility: visible; left: 294px; top: 370px; width: 554px; height: 123px; font-size: 11px;">
<div id="ext-gen727" class="x-combo-list-inner" style="width: 554px; margin-bottom: 8px; height: 114px;">
<div class="x-combo-list-item"></div>
<div class="x-combo-list-item">12h Universe</div>
<div class="x-combo-list-item">1h Universe</div>
<div class="x-combo-list-item">24h Universe</div>
<div class="x-combo-list-item">2h Universe</div>
<div class="x-combo-list-item x-combo-selected">4h Universe</div>
Now i have problem selecting the value from the list as the div element of the list is not attached to the control.
Also please refer the screen shot, where i have multiple similar controls [Named "Add Security to Universe"]
In the screen shot you can see multiple drop downs [Add security to Universe] highlighted and all the drop downs have same value appearing in the list. so how can i identify these values from the drop down list.
I was wondering how ExtJS maintains mapping of the drop down div elements with the combo Box widget so that i could use the same logic for identifying the list. Can anyone tell me how can i go about doing this thing in selenium webdriver?
Did you notice that there will be only one visible x-combo-list on the page? (Let me know if you can open up two combo lists at the same time)
Therefore you only need to care about the visible one x-combo-list.
Css selector: .x-combo-list[style*='visibility: visible;'] .x-combo-list-item
Xpath: //*[contains(#class, 'x-combo-list') and contains(#style, 'visibility: visible;')]//*[contains(#class, 'x-combo-list-item')]
// untested java code, just for the logic
public void clickComboItem(WebElement input, String target) {
input.click(); // click input to pop up the combo list
List<WebElement> comboItems = driver.findElements(By.cssSelector(".x-combo-list[style*='visibility: visible;'] .x-combo-list-item"));
for (int i = 0; i <= comboItems.size(); i++) {
WebElement item = comboItems.get(i);
if (item.getText().eqauls(target)) {
item.click();
break;
}
}
}
// compilable C# version
public void ClickComboItem(IWebElement input, string target) {
input.Click();
IList<IWebElement> comboItems = driver.findElements(By.CssSelector(".x-combo-list[style*='visibility: visible;'] .x-combo-list-item"));
comboItems.First(item => item.Text.Trim() == target).Click();
}
What i can suggest is :
you catch all your inputs like :
List<WebElement> inputList = driver.findElements(By.cssSelector("input cssSelector")); // you must complete this cssSelector
WebElement input = inputList.get(0); // get the 1st input
input.click(); //click on the first input and the option list appears.
you catch all "options" like :
List<WebElement> optionList = driver.findElements(By.cssSelector(".x-combo-list-item")); // get all options
WebElement option = optionList.get(1);
option.click();
input.sendKeys(option.getText()); //getText() get the html inner value
This is just an example in Java and you can actually use a loop foreach if you want to automat this populate for all your inputs.
I use JavaScriptExecutor, my SelectRandomOption looks like this:
public void SelectRandomOption()
{
String randomOptionIndex = "Math.floor(Math.random()*Ext.getCmp('" + ExtJSIdOfComboBox + "').getStore().getCount()-1)";
String randomOptionValue = "Ext.getCmp('" + ExtJSIdOfComboBox + "').getStore().getAt(" + randomOptionIndex + ").getData()['model']";
String jsScript = "Ext.getCmp('" + ExtJSIdOfComboBox + "').setValue(" + randomOptionValue + ");";
js.ExecuteScript(jsScript);
}
I basically used the marked answer above however it needed a bit of adapting for Ext Js 4.1.
It's essentially the same approach but you need to look for a visible div marked with class "x-boundlist"
I used xpath and used queries that looked something like this:
.//div[#class[contains(.,'x-boundlist')]]
and then retrieve and click on an li matching your desired entry:
.//li[normalize-space(text())='combobox entry text']
I've put normalize-space in there as xpath seems to have real problems if you dont trim strings. That methods does a left + right trim and also removes duplicate spaces eg
' blah blah ' would change to 'blah blah'.

Resources