Tuesday, October 18, 2011

Android development: ListView inside a PopupWindow

For some reason (you don't want to know believe me), I had to put a ListView in a PopupWindow. In more recent versions of Android (newer than Gingerbread) there is the convenient android.widget.ListPopupWindow class which does that job for you.
But for Gingerbread, you'll have to put the list in the PopupWindow. That's what I did, it showed up fine when I show the popup, I could scroll the ListView, but sadness, the OnItemClick of the OnItemClickListener would not get fired when pressing a item in the ListView.
After spending way to much time (getting the Android Java source code associated with the Android jar in Eclipse and stepping through the code in the debugger), I discovered that I had to set the PopupWindow to be focusable:
mPopupWindow.setFocusable(true);
And then voila, the OnItemClick gets called!
Hope it helps someone!

Wednesday, September 21, 2011

Monday, August 15, 2011

In JavaScript, curly brace placement matters: An example


If you’ve been working with JavaScript very long, you probably know that you should format curly braces in JavaScript code a certain way. In fact, if you’ve watched my TekPub series, Mastering jQuery, you’ve heard me stop James and remind him that at the beginning of nearly every episode.
However, you’re less likely to have seen a clear example of why this matters or why you should care. Even when you hear advice from a trusted source, it can be difficult to heed that advice if it seems like hearsay or convention for the sake of convention.
While I was working on my recent post about extracting data objects from HTML structures, it occurred to me that some of its example code presented a great learning opportunity regarding this topic. So, I want to take advantage of that opportunity to show you a concrete example of how placing your braces on the wrong line can break your JavaScript code.

Allman, K&R, and you

The specific part of the previous post that I want to talk about is this:
return {
  id: $item.data('id'),
  text: $item.text()
};
Notice how the opening brace in the object literal is on the same line as thereturn statement.
Placing opening braces on the same line as their corresponding control statements like that is called K&R style. Unlike most differences in coding style – most amounting to personal preference – using K&R style braces in JavaScript is important for an objective reason.
That reason is well-illustrated by looking at the alternative style in this case. That alternative, Allman style, is a style that’s more common in languages like C#. Allman style braces are placed alone, at the beginning of the line immediately aftera control statement.
Modifying the previous code to use Allman style braces would look like this:
return
{
  id: $item.data('id'),
  text: $item.text()
};
That code is now broken. Though you can usually get away with using Allman style braces in JavaScript, returning object literals is an example of when you cannot.

JavaScript semicolon insertion can ruin your day

The culprit here is JavaScript’s infamous semicolon insertion feature. A JavaScript interpreter will parse return\n as a complete statement, assume that you forgot a semicolon at the end, and then treat it as return;\n instead.
In other words, when you write this:
return
{
  id: $item.data('id'),
  text: $item.text()
};
It’s actually interpreted as if you had written this:
return; // Waiter, I didn't order this semicolon!
{
  id: $item.data('id'),
  text: $item.text()
};
The insidious result is that almost all browsers will allow the code to execute, but the prematurely terminated return statement will return undefined instead of the object you’d expect. No syntax error, no warning; just a chunk of “working” code that behaves inexplicably.

Conclusion

Since this problem manifests itself as an undefined return value, you can imagine how painful it can be to trace that back to an artifact of where the curly brace is located. Unless you’re already aware of the semicolon insertion trap, brace placement is usually the last thing that you’d suspect to be the culprit in these situations.
The problem would have been even worse in the larger example that this code excerpt was extracted from. The object literal’s location within the .map() call would have obfuscated the root issue even farther since “mapping” a series of undefined return values would simply result in an empty array.
Key takeaway? Always use K&R style braces in JavaScript, even if it’s not the style you prefer in other languages.
Allman braces bring zero objective value to the table. Using them out of personal preference isn’t worth the mental overhead of consistently remembering that they break when returning object literals, nor the debugging morass that will inevitably crop up when you aren’t paying close attention and muscle memory takes over.

Friday, July 29, 2011

JQuery sortable draggable bug.

JQuery sortable Update event calls twice when you bind it to class, not to id and when you drag item to other connectable block.
Jquery
$(".MyClass1, .MyClass2").sortable({
    connectWith: ".connectedSortable",
    update: function (event, ui) {
                alert("twice!");
            }})


Very simple solution is to change event "update" to "stop":

Jquery
$(".MyClass1, .MyClass2").sortable({
    connectWith: ".connectedSortable",
    stop: function (event, ui) {
                alert("once!");
            }})

Wednesday, July 27, 2011

Entity Framework. "New transaction is not allowed because there are other threads running in the session."

Task: Resolve error.
Solution: Use new context to update item in iteration.

Explanation:
This exception occurs in the following code:
C#
MyContext db=new MyContext();
var ListOfEntities=from p in db.Entity select p;
foreach(var item in ListOfEntities)
{
    item.Text="Changed!";
    db.SaveChanges();
}


In the following example it will be OK:


C#
MyContext db=new MyContext();
var ListOfEntities=from p in db.Entity select p;
foreach(var item in ListOfEntities)
{
    MyContext anotherDB =new MyContext();
    var MyItem=(from p in anotherDB where p.ID=item.ID select p).FirstOrDefault();
    MyItem.Text="Changed!";
    anotherDB.SaveChanges();
}


Wednesday, July 13, 2011

ASP.NET MVC 3 bug (Html helpers)

If your model has ID parameter then Html helper will replace it with ID from QueryString.
It will take from here ==> "/MyControler/someaction/ID"
not from here ==> "model=>model.ID"

Solution: Write your html inputs yourself if you have ID parameter in Model.

Thursday, April 21, 2011

JQuery clone elements

TASK:
Clone DOM elements.

SOLUTION:
Use .clone() and .appendTo().

EXPLANATION:

In the following example we copy DOM element ".from_to_copy" to ".where_to_copy" without typed data and without javascript's bindings.

JQuery
$(".from_to_copy").clone().appendTo(".where_to_copy");

In this example we copy DOM element with data typed and javascript's bindigs.
JQuery
$(".from_to_copy").clone(true).appendTo(".where_to_copy");

Just change default ".clone()" to ".clone(true)".

Monday, April 18, 2011

JQuery detection of browser

TASK: 
Fix something or do special instructions according to browser type.
SOLUTION: 
Use the flags of $.browser:

  • $.browser.webkit
  • $.browser.safari (deprecated) 
  • $.browser.opera
  • $.browser.msie
  • $.browser.mozilla


Also, we can detect version of browser using $.browser.version

Jquery.browser and $.browser are synonymous.

EXAMPLE: 

JQuery
if ($.browser.mozilla)
{
alert("The browser is mozilla");
}

JQuery
if ($.browser.msie)
{
alert("The browser is Internet Explorer, version:" + $.browser.version);
}

Wednesday, April 13, 2011

JQuery select element at index n

TASK:
Select the element at index n within the matched set.


SOLUTION:
$(".example:eq("+index+")").css("color", "red");

EXAMPLE:
Select element at index 1 and set css property "color" to "red":
JQuery
var index=1;
$(".example:eq("+index+")").css("color", "red");

HTML
<div class="example">div index 0</div>
<div class="example">div index 1</div>
<div class="example">div index 2</div>

JQuery index of element

TASK:
Recognize index of element in group on which we clicked.
SOLUTION: 
$("#parent child").index(this);
EXAMPLE:

JQuery
$(document).ready(function() {

    $("#example div").click(function() {
        var index = $("#example div").index(this);
        $("#example_index").html("Index " + index + " was clicked");
    });

});

HTML
<div id="example">
    <div>div index 0</div>
    <div>div index 1</div>
    <div>div index 2</div>
    <div>div index 3</div>
    <div>div index 4</div>
</div>
<div id="example_index">Click one of the above divs</div>

Monday, April 11, 2011

HTML IE conditional comments

TASK: 
Tell special instructions for IE.

SOLUTION: 

<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]-->

EXPLANATION: 

  1. Their basic structure is the same as an HTML comment (<!-- -->). Therefore all other browsers will see them as normal comments and will ignore them entirely.
  2. Explorer Windows, though, has been programmed to recognize the special <!--[if IE]> syntax, resolves the if and parses the content of the conditional comment as if it were normal page content.
  3. Since conditional comments use the HTML comment structure, they can only be included in HTML files, and not in CSS files. I'd have preferred to put the special styles in the CSS file, but that's impossible. You can also put an entire new <link> tag in the conditional comment referring to an extra style sheet.

The syntax I use is:

<!--[if IE]>
According to the conditional comment this is Internet Explorer<br />
<![endif]-->


<!--[if IE 6]>
According to the conditional comment this is Internet Explorer 6<br />
<![endif]-->


<!--[if IE 7]>
According to the conditional comment this is Internet Explorer 7<br />
<![endif]-->


<!--[if gte IE 6]>
According to the conditional comment this is Internet Explorer 6 and up<br />
<![endif]-->
<!--[if lt IE 6]>
According to the conditional comment this is Internet Explorer lower than 6<br />
<![endif]-->


<!--[if lte IE 6]>
According to the conditional comment this is Internet Explorer lower or equal to 6<br />
<![endif]-->


<!--[if gt IE 6]>
According to the conditional comment this is Internet Explorer greater than 6<br />
<![endif]-->

Note the special syntax:
  • gt: greater than
  • gte:greater than or equal to
  • lt:less than
  • lte: less than or equal to



Sunday, April 10, 2011

CSS underline


Task: 
Change space between word and bottom line in link element (<a></a>).

Solution: 
a {
padding-bottom: 10px; //space between word and line
color: #555;
text-decoration: none;
border-bottom: 1px solid #555;
}