Friday, December 17, 2010

Android android:layout_toRightOf, android:layout_alignParentRight="true" simple

Android iin View г байршуулж байгаа жишээ

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/shape">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_name"
            android:text="Name"></TextView>
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Description"
            android:id="@+id/tv_description"
            android:layout_toRightOf="@+id/tv_name"
            android:layout_marginLeft="10px"
            />
    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/iv_forward"
            android:background="@drawable/forward_arrow"
            android:layout_alignParentRight="true"
            />
</RelativeLayout>





goob simple layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/news_new_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingTop="2px"
        android:paddingBottom="6px"
        android:background="@drawable/item_back_lightgrey_red_inner"
        >
    <ImageView
            android:id="@+id/news_new_image"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_marginTop="4px"
            android:layout_marginLeft="2px"
            android:layout_marginRight="4px"
            android:layout_marginBottom="2px"
            />
    <TextView
            android:id="@+id/news_new_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="@style/StyleTextBold14"
            android:textColor="@drawable/color_black_white"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/news_new_image"
            android:duplicateParentState="true"
            />
    <TextView
            android:id="@+id/news_new_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10px"
            android:textColor="@drawable/color_black_white"
            android:layout_toRightOf="@+id/news_new_image"
            android:layout_below="@+id/news_new_name"
            android:duplicateParentState="true"
            />
    <TextView
            android:id="@+id/news_new_site"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10px"
            android:textColor="@drawable/color_black_white"
            android:layout_below="@+id/news_new_name"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10px"
            android:duplicateParentState="true"
            />
</RelativeLayout>

Thursday, December 16, 2010

JQuery slideUp down Nav Menu simple

<html>
<head>
    <title>Toggle</title>
    <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
    <style>
        .right-menu {float:left; width:230px; padding:15px 0 0 0;}
        .right-basicmenu{float:left; width:230px; padding-top:5px;}
        .right-basicmenu a, .right-basicmenu a:visited {width:220px; display:block; padding:10px 0 10px 10px;  color:#fff; font-size:138.5%;  background-color:#016ea7; font-family:"Myriad Pro";}
        .right-basicmenu a.rsel, .right-basicmenu a.rsel:visited {font-size:138.5%; font-weight:bold; color:#fff; background-color:#016ea7; font-family:"Myriad Pro";}
             ul.style {list-style:none; padding:0; margin:0;}
             ul.style li{list-style:none;}
            .right-submenu {float:left; width:200px; padding-left:30px; margin-top:5px; background-color:#eef9ff;}
            .right-submenu li a, .right-submenu li a:visited {width:200px; padding:6px 0; color:#000; font-size:108%; font-family:"Myriad Pro"; background:none;}
            .right-submenu a.submenusel, .right-submenu a.submenusel:visited {color:#0c499c; font-size:108%; font-family:"Myriad Pro"}
    </style>
</head>
<body>
    <div class="right-menu" id="right-menu">
        <div class="right-basicmenu">
            <a href="javascript:void(0);">Adventure Tours</a>
            <div class="right-submenu">
                <ul class="style">
                    <li><a href="javascript:void(0)">*Fishing</a></li>
                    <li><a href="javascript:void(0)" class="submenusel">*Mountaineerig</a></li>
                    <li><a href="javascript:void(0)">*Walking</a></li>
                    <li><a href="javascript:void(0)">*Horse riding</a></li>
                    <li><a href="javascript:void(0)">*Camel riding</a></li>
                    <li><a href="javascript:void(0)">*Biking</a></li>
                    <li><a href="javascript:void(0)">*Film making</a></li>
                    <li><a href="javascript:void(0)">*Jeep sarari</a></li>
                </ul>
            </div>
        </div>

        <div class="right-basicmenu">
            <a href="javascript:void(0);">Culture Tours</a>
            <div class="right-submenu">
                <ul class="style">
                    <li><a href="javascript:void(0)">*Fishing</a></li>
                    <li><a href="javascript:void(0)">*Mountaineerig</a></li>
                </ul>
            </div>
        </div>
    </div>
   
    <script type="text/javascript">
        function clickon(){   
            var $p = $(this).parent();
            var iam = false;
            $('#right-menu .right-basicmenu').filter(function(){
                return $(this).data("clicked");
            }).each(function () {   
                if ($(this).data("clicked")) {
                    $(this).data("clicked",false);
                    $($(this).children().get(1)).slideUp("slow");
                    iam = $(this).data("index")==$p.data("index");
                }
            });
            if (!iam) {
                $p.data("clicked",!$p.data("clicked"));
                if($p.data("clicked"))
                    $(this).next().slideDown("slow");
                else
                    $(this).next().slideUp("slow");
            }
        }       
        $('#right-menu .right-basicmenu').each(function(i){
            $(this).data("clicked",false);
            $(this).data("index",i);
            var $a = $($(this).children().get(0));           
            $a.click(clickon);
            $a.next().slideUp("fast");
        });           
    </script>
</body>
</html>

Html css png image fix on IE

Хэрэв Internet Explore 6 дээр png зураг алдаатай харагдаад байвал доорхи кодыг бичээд үзээрэй


iepngfix.js


// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support
// (c) 2008-2009 Angus Turnbull http://www.twinhelix.com

// This is licensed under the GNU LGPL, version 2.1 or later.
// For details, see: http://creativecommons.org/licenses/LGPL/2.1/

var IEPNGFix = window.IEPNGFix || {};

IEPNGFix.tileBG = function(elm, pngSrc, ready) {
    // Params: A reference to a DOM element, the PNG src file pathname, and a
    // hidden "ready-to-run" passed when called back after image preloading.

    var data = this.data[elm.uniqueID],
        elmW = Math.max(elm.clientWidth, elm.scrollWidth),
        elmH = Math.max(elm.clientHeight, elm.scrollHeight),
        bgX = elm.currentStyle.backgroundPositionX,
        bgY = elm.currentStyle.backgroundPositionY,
        bgR = elm.currentStyle.backgroundRepeat;

    // Cache of DIVs created per element, and image preloader/data.
    if (!data.tiles) {
        data.tiles = {
            elm: elm,
            src: '',
            cache: [],
            img: new Image(),
            old: {}
        };
    }
    var tiles = data.tiles,
        pngW = tiles.img.width,
        pngH = tiles.img.height;

    if (pngSrc) {
        if (!ready && pngSrc != tiles.src) {
            // New image? Preload it with a callback to detect dimensions.
            tiles.img.onload = function() {
                this.onload = null;
                IEPNGFix.tileBG(elm, pngSrc, 1);
            };
            return tiles.img.src = pngSrc;
        }
    } else {
        // No image?
        if (tiles.src) ready = 1;
        pngW = pngH = 0;
    }
    tiles.src = pngSrc;

    if (!ready && elmW == tiles.old.w && elmH == tiles.old.h &&
        bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) {
        return;
    }

    // Convert English and percentage positions to pixels.
    var pos = {
            top: '0%',
            left: '0%',
            center: '50%',
            bottom: '100%',
            right: '100%'
        },
        x,
        y,
        pc;
    x = pos[bgX] || bgX;
    y = pos[bgY] || bgY;
    if (pc = x.match(/(\d+)%/)) {
        x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100));
    }
    if (pc = y.match(/(\d+)%/)) {
        y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100));
    }
    x = parseInt(x);
    y = parseInt(y);

    // Handle backgroundRepeat.
    var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR],
        repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR];
    if (repeatX) {
        x %= pngW;
        if (x > 0) x -= pngW;
    }
    if (repeatY) {
        y %= pngH;
        if (y > 0) y -= pngH;
    }

    // Go!
    this.hook.enabled = 0;
    if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) {
        elm.style.position = 'relative';
    }
    var count = 0,
        xPos,
        maxX = repeatX ? elmW : x + 0.1,
        yPos,
        maxY = repeatY ? elmH : y + 0.1,
        d,
        s,
        isNew;
    if (pngW && pngH) {
        for (xPos = x; xPos < maxX; xPos += pngW) {
            for (yPos = y; yPos < maxY; yPos += pngH) {
                isNew = 0;
                if (!tiles.cache[count]) {
                    tiles.cache[count] = document.createElement('div');
                    isNew = 1;
                }
                var clipR = Math.max(0, xPos + pngW > elmW ? elmW - xPos : pngW),
                    clipB = Math.max(0, yPos + pngH > elmH ? elmH - yPos : pngH);
                d = tiles.cache[count];
                s = d.style;
                s.behavior = 'none';
                s.left = (xPos - parseInt(elm.currentStyle.paddingLeft)) + 'px';
                s.top = yPos + 'px';
                s.width = clipR + 'px';
                s.height = clipB + 'px';
                s.clip = 'rect(' +
                    (yPos < 0 ? 0 - yPos : 0) + 'px,' +
                    clipR + 'px,' +
                    clipB + 'px,' +
                    (xPos < 0 ? 0 - xPos : 0) + 'px)';
                s.display = 'block';
                if (isNew) {
                    s.position = 'absolute';
                    s.zIndex = -999;
                    if (elm.firstChild) {
                        elm.insertBefore(d, elm.firstChild);
                    } else {
                        elm.appendChild(d);
                    }
                }
                this.fix(d, pngSrc, 0);
                count++;
            }
        }
    }
    while (count < tiles.cache.length) {
        this.fix(tiles.cache[count], '', 0);
        tiles.cache[count++].style.display = 'none';
    }

    this.hook.enabled = 1;

    // Cache so updates are infrequent.
    tiles.old = {
        w: elmW,
        h: elmH,
        x: bgX,
        y: bgY,
        r: bgR
    };
};


IEPNGFix.update = function() {
    // Update all PNG backgrounds.
    for (var i in IEPNGFix.data) {
        var t = IEPNGFix.data[i].tiles;
        if (t && t.elm && t.src) {
            IEPNGFix.tileBG(t.elm, t.src);
        }
    }
};
IEPNGFix.update.timer = 0;

if (window.attachEvent && !window.opera) {
    window.attachEvent('onresize', function() {
        clearTimeout(IEPNGFix.update.timer);
        IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
    });
}






iepngfix.htc



<public:component>
<script type="text/javascript">

// IE5.5+ PNG Alpha Fix v2.0 Alpha
// (c) 2004-2009 Angus Turnbull http://www.twinhelix.com

// This is licensed under the GNU LGPL, version 2.1 or later.
// For details, see: http://creativecommons.org/licenses/LGPL/2.1/

var IEPNGFix = window.IEPNGFix || {};
IEPNGFix.data = IEPNGFix.data || {};


// CONFIG: blankImg is the path to blank.gif, *relative to the HTML document*.
// Try either:
// * An absolute path like:  '/images/blank.gif'
// * A path relative to this HTC file like:  thisFolder + 'blank.gif'
var thisFolder = document.URL.replace(/(\\|\/)[^\\\/]*$/, '/');
IEPNGFix.blankImg = thisFolder + 'blank.gif';


IEPNGFix.fix = function(elm, src, t) {
    // Applies an image 'src' to an element 'elm' using the DirectX filter.
    // If 'src' is null, filter is disabled.
    // Disables the 'hook' to prevent infinite recursion on setting BG/src.
    // 't' = type, where background tile = 0, background = 1, IMG SRC = 2.

    var h = this.hook.enabled;
    this.hook.enabled = 0;

    var f = 'DXImageTransform.Microsoft.AlphaImageLoader';
        src = (src || '').replace(/\(/g, '%28').replace(/\)/g, '%29');

    if (
        src && !(/IMG|INPUT/.test(elm.nodeName) && (t != 2)) &&
        elm.currentStyle.width == 'auto' && elm.currentStyle.height == 'auto'
    ) {
        if (elm.offsetWidth) {
            elm.style.width = elm.offsetWidth + 'px';
        }
        if (elm.clientHeight) {
            elm.style.height = elm.clientHeight + 'px';
        }
        if (elm.currentStyle.display == 'inline') {
            elm.style.display = 'inline-block';
        }
    }

    if (t == 1) {
        elm.style.backgroundImage = 'url("' + this.blankImg + '")';
    }
    if (t == 2) {
        elm.src = this.blankImg;
    }

    if (elm.filters[f]) {
        elm.filters[f].enabled = src ? true : false;
        if (src) {
            elm.filters[f].src = src;
        }
    } else if (src) {
        elm.style.filter = 'progid:' + f + '(src="' + src +
            '",sizingMethod="' + (t == 2 ? 'scale' : 'crop') + '")';
    }

    this.hook.enabled = h;
};


IEPNGFix.process = function(elm, init) {
    // Checks the onpropertychange event (on first 'init' run, a fake event)
    // and calls the filter-applying-functions.

    if (
        !/MSIE (5\.5|6)/.test(navigator.userAgent) ||
        typeof elm.filters == 'unknown'
    ) {
        return;
    }
    if (!this.data[elm.uniqueID]) {
        this.data[elm.uniqueID] = {
            className: ''
        };
    }
    var data = this.data[elm.uniqueID],
        evt = init ? { propertyName: 'src,backgroundImage' } : event,
        isSrc = /src/.test(evt.propertyName),
        isBg = /backgroundImage/.test(evt.propertyName),
        isPos = /width|height|background(Pos|Rep)/.test(evt.propertyName),
        isClass = !init && ((elm.className != data.className) &&
            (elm.className || data.className));
    if (!(isSrc || isBg || isPos || isClass)) {
        return;
    }
    data.className = elm.className;
    var blank = this.blankImg.match(/([^\/]+)$/)[1],
        eS = elm.style,
        eCS = elm.currentStyle;

    // Required for Whatever:hover - erase set BG if className changes.
    if (
        isClass && (eS.backgroundImage.indexOf('url(') == -1 ||
        eS.backgroundImage.indexOf(blank) > -1)
    ) {
        return setTimeout(function() {
            eS.backgroundImage = '';
        }, 0);
    }

    // Foregrounds.
    if (isSrc && elm.src && { IMG: 1, INPUT: 1 }[elm.nodeName]) {
        if ((/\.png/i).test(elm.src)) {
            if (!elm.oSrc) {
                // MM rollover compat
                elm.oSrc = elm.src;
            }
            this.fix(elm, elm.src, 2);
        } else if (elm.src.indexOf(blank) == -1) {
            this.fix(elm, '');
        }
    }

    // Backgrounds.
    var bgSrc = eCS.backgroundImage || eS.backgroundImage;
    if ((bgSrc + elm.src).indexOf(blank) == -1) {
        var bgPNG = bgSrc.match(/url[("']+(.*\.png[^\)"']*)[\)"']/i);
        if (bgPNG) {
            if (this.tileBG && !{ IMG: 1, INPUT: 1 }[elm.nodeName]) {
                this.tileBG(elm, bgPNG[1]);
                this.fix(elm, '', 1);
            } else {
                if (data.tiles && data.tiles.src) {
                    this.tileBG(elm, '');
                }
                this.fix(elm, bgPNG[1], 1);
                this.childFix(elm);
            }
        } else {
            if (data.tiles && data.tiles.src) {
                this.tileBG(elm, '');
            }
            this.fix(elm, '');
        }
    } else if ((isPos || isClass) && data.tiles && data.tiles.src) {
        this.tileBG(elm, data.tiles.src);
    }

    if (init) {
        this.hook.enabled = 1;
        elm.attachEvent('onpropertychange', this.hook);
    }
};


IEPNGFix.childFix = function(elm) {
    // "hasLayout" fix for unclickable children inside PNG backgrounds.
    var tags = [
            'a',
            'input',
            'select',
            'textarea',
            'button',
            'iframe',
            'object'
        ],
        t = tags.length,
        tFix = [];
    while (t--) {
        var pFix = elm.all.tags(tags[t]),
            e = pFix.length;
        while (e--) {
            tFix.push(pFix[e]);
        }
    }
    t = tFix.length;
    if (t && (/relative|absolute/i).test(elm.currentStyle.position)) {
        alert('IEPNGFix: Unclickable children of element:' +
            '\n\n<' + elm.nodeName + (elm.id && ' id=' + elm.id) + '>');
    }
    while (t--) {
        if (!(/relative|absolute/i).test(tFix[t].currentStyle.position)) {
            tFix[t].style.position = 'relative';
        }
    }
};


IEPNGFix.hook = function() {
    if (IEPNGFix.hook.enabled) {
        IEPNGFix.process(element, 0);
    }
};


IEPNGFix.process(element, 1);

</script>
</public:component>


png image









simple.html


<html>
<head>
<script type="text/javascript" src="iepngfix.js"></script>
<style type="text/css">
img, div, input { behavior: url("iepngfix.htc") }
</style>
</head>
<body>
<div style="background:url('bg.png') no-repeat;height:200px;width:200px;text-align:center;">
<a style="display:block;padding-top:100px;" href="http://www.google.com/">click</a>
</div>
</body>
</html>



maybe usage on server

in .htaccess file

AddType text/x-component .htc

Wednesday, December 15, 2010

Html style nowrap overflow hidden simple

<html>
<body>

<table>
<tr>
<td style="width:100px;overflow:hidden;"><div style="width:50px;white-space:nowrap;">sain u. boroo yu baina daa and mine.</div></td>
</tr>
</table>

</body>
</html>

Tuesday, December 14, 2010

Javascript event, with html beginner simple

Event:

function targetElem(e) {
 var targ;
 if (!e) var e = window.event;
 if (e.target) targ = e.target;
 else if (e.srcElement) targ = e.srcElement;
 if (targ.nodeType == 3) // defeat Safari bug
  targ = targ.parentNode;
}


function keyEvent(e) {
 var code;
 if (!e) var e = window.event;
 if (e.keyCode) code = e.keyCode;
 else if (e.which) code = e.which;
 var character = String.fromCharCode(code);
 alert('Character was ' + character);
}



function rightButtonClick(e) {
 var rightclick;
 if (!e) var e = window.event;
 if (e.which) rightclick = (e.which == 3);
 else if (e.button) rightclick = (e.button == 2);
 alert('Rightclick: ' + rightclick); // true or false
}

function coordinates(e) {
 var posx = 0;
 var posy = 0;
 if (!e) var e = window.event;
 if (e.pageX || e.pageY)  {
  posx = e.pageX;
  posy = e.pageY;
 }
 else if (e.clientX || e.clientY)  {
  posx = e.clientX + document.body.scrollLeft
   + document.documentElement.scrollLeft;
  posy = e.clientY + document.body.scrollTop
   + document.documentElement.scrollTop;
 }
 // posx and posy contain the mouse position relative to the document
 // Do something with this information
}

Jishee:

<html>
<body>

<div id="simple"><img src="1"><img src="2"></div>
<script>
var div = document.getElementById('simple');
var imgs = div.getElementsByTagName('img');
if (imgs.length > 0) {
    alert(imgs[0].src);
}
</script>

<div id="message"></div>
<div onMouseOver="over(this);" onMouseOut="out(this);" style="height:20px;background:yellow">mouse over here</div>
<script>
over=function(obj){
document.getElementById('message').innerHTML="--over";
}
out=function(obj){
document.getElementById('message').innerHTML="--out";
}

//var t = document.getElementsByTagName('table')[0];
//var tr = t.getElementsByTagName('tr');
//for(var i = 0; i < tr[0].childNodes.length; i++){
//    alert(tr[0].childNodes[i].innerHTML);
//}
</script>

</body>
</html>

Monday, December 13, 2010

About DOCTYPE html PUBLIC

Доорхи таг нь HTML -ийн стандартыг тодорхойлдог бөгөөд XHTML 1.0 Transitional , HTML 4.01 Transitional гэх мэт толгой текст байдгийг ажигласан байх.
Энэ тагийг тависнаар IE дээр Select болон зарим тагийн Padding болон бусад стилийг солиход илүү хялбар зөв болно.

Жишээ дээр хэрэгжүүлж үр дүнг нь ажиглаад үзээрэй

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">






<html>
<style>
select { padding:10px; }
</style>
<body>
<select>
<option >sdafasdfasdfasd</option>
</select>
</body>
</html>

Sunday, December 12, 2010

JSP Page ( JSTL using ) - > Generate Javascript ( Expression Language using ) with same system tag script

Энэ жишээ нь JSP бичих үед тулгардаг ( тодотговол өгөгдлийн санд ' болон " тэмдэгтүүд бүртгэгдсэний дараа javascript object болгоход мөн click=" event доторхи үйлдэл дээр дээрх тэмдэгтээс болж алдаа заадаг " )  асуудлыг шийднэ.

using 1

<c:if test="${programehasblock_programehasblocks.totalNumberOfElements > 0}">
    <script type="text/javascript">
        $(function() {
        <c:forEach items="${programehasblock_programehasblocks.thisPageElements}" var="row" varStatus="status">
            _initItem(${row.id}, eval('('
                    + "{ id: ${row.id},"
                    + "name:'<gtx:replace strValue="${row.name}" oldStr="\"" newStr="\\\&quot;"/>',"
                    + "time:\"<fmt:formatDate value="${row.starttime}" pattern="yyyy.MM.dd HH:mm:ss"/>\",description:'${row.descr}' }"
                    + ')'));
        </c:forEach>
        });
    </script>
</c:if>

using 2

<c:choose>                                                                        <c:when test="${!empty row.anyid}">
                                                                            <a href="javascript:void(0);"
                                                                               onclick='_addItem(${row.id},"<gtx:replace strValue="${row.name}" oldStr="\"" newStr="\\\&quot;"/>",${row.age},${row.anyid});'>нэмэх</a>
                                                                        </c:when>
                                                                        <c:otherwise>
                                                                            <a href="javascript:void(0);"
                                                                               onclick='_addItem(${row.id},"<gtx:replace strValue="${row.name}" oldStr="\"" newStr="\\\&quot;"/>",${row.age},0);'>нэмэх</a>
                                                                        </c:otherwise>                                                                    </c:choose>




<script>_addItem(obj){alert(obj.name);};</script> гэх мэт үйлдлийг өөрсдөө бичнэ.
<gtx:replace нь текст сольдог tag ( Expression Language ) юм.

Friday, December 10, 2010

Android file read write simple

public class ReadNWriteFile extends Activity {

 final String TEST_STRING = new String("Hello Android");
 final String FILE_NAME = "SAMPLEFILE.txt";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  TextView tv = new TextView(this);
  fileCreate();
  tv.setText(readFile());
  setContentView(tv);
 }

 private void fileCreate() {
  try {
   OutputStream os = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
   OutputStreamWriter osw = new OutputStreamWriter(os);
   osw.write(TEST_STRING);
   osw.close();
  } catch (Exception e) {
   Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
  }
 }

 private String readFile() {
  try {
   FileInputStream fin = openFileInput(FILE_NAME);
   InputStreamReader isReader = new InputStreamReader(fin);
   char[] buffer = new char[TEST_STRING.length()];
   // Fill the buffer with data from file
   isReader.read(buffer);
   return new String(buffer);
  } catch (Exception e) {
   Log.i("ReadNWrite, readFile()", "Exception e = " + e);
   return null;
  }
 }
}
 
 
 your serializable data save or load on file 
 
/**
     * internal data storage
     */
    public static void saveCache(String filename, Serializable settings, Activity act)
            throws IOException {

        FileOutputStream fos = act.openFileOutput(filename, Context.MODE_PRIVATE);

        OutputStream buffer = new BufferedOutputStream(fos);
        ObjectOutput output = new ObjectOutputStream(buffer);
        try {
            output.writeObject(settings);
        } finally {
            output.close();
        }
    }

    /**
     * internal data storage
     */
    public static Serializable openCache(String filename, Activity act)
            throws IOException {

        FileInputStream fis = act.openFileInput(filename);

        InputStream buffer = new BufferedInputStream(fis);
        ObjectInput input = new ObjectInputStream(buffer);
        try {
            return (Serializable) input.readObject();
        } catch (Exception ex) {
            throw new IOException(ex.getMessage());
        } finally {
            input.close();
        }
    } 

Android GET, POST and Multipart POST and downloader simple

HttpGet simple

try {
        HttpClient client = new DefaultHttpClient(); 
        String getURL = "http://www.google.com";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get); 
        HttpEntity resEntityGet = responseGet.getEntity(); 
        if (resEntityGet != null) { 
                    //do something with the response
                    Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
                }
} catch (Exception e) {
    e.printStackTrace();
}

HttpPost simple


try {
        HttpClient client = new DefaultHttpClient(); 
        String postURL = "http://somepostaddress.com";
        HttpPost post = new HttpPost(postURL);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user", "kris"));
            params.add(new BasicNameValuePair("pass", "xyz"));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
            HttpResponse responsePOST = client.execute(post); 
            HttpEntity resEntity = responsePOST.getEntity(); 
            if (resEntity != null) {   
                Log.i("RESPONSE",EntityUtils.toString(resEntity));
            }
    } catch (Exception e) {
        e.printStackTrace();
    }

MultipartEntity

File file = new File("path/to/your/file.txt");
try {
         HttpClient client = new DefaultHttpClient(); 
         String postURL = "http://someposturl.com";
         HttpPost post = new HttpPost(postURL);
     FileBody bin = new FileBody(file);
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
     reqEntity.addPart("myFile", bin);
     post.setEntity(reqEntity); 
     HttpResponse response = client.execute(post); 
     HttpEntity resEntity = response.getEntity(); 
     if (resEntity != null) {   
               Log.i("RESPONSE",EntityUtils.toString(resEntity));
         }
} catch (Exception e) {
    e.printStackTrace();
}





Image or Text downloader good and full simple



import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: boroo
 * Date: Dec 9, 2010
 * Time: 6:01:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class WebUtils {

    public WebUtils() {
    }

    private InputStream OpenHttpConnection(String urlString)
            throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        }
        catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    public String DownloadText(String URL) {
        int BUFFER_SIZE = 2000;
        InputStream in = null;

        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            e1.printStackTrace();
            return "";
        }

        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        StringBuilder str = new StringBuilder();
        char[] inputBuffer = new char[BUFFER_SIZE];

        try {
            while ((charRead = isr.read(inputBuffer)) > 0) {
                //---convert the chars to a String---
                String readString =
                        String.copyValueOf(inputBuffer, 0, charRead);
                str.append(readString);
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return str.toString();
    }

    public Document DownloadXML(String URL) {
        try {
            InputStream in = OpenHttpConnection(URL);
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db;

            try {
                db = dbf.newDocumentBuilder();
                doc = db.parse(in);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
            return doc;
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        }
    }

    public Bitmap DownloadImage(String URL) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }


    ///////////////////////// static methods ////////////////////

    public static final String buildUri(String uri, Map<String, String> map)
            throws IllegalArgumentException {
        StringBuilder sb = new StringBuilder();
        sb.append(uri);
        int i = 0;

        if (map != null && !map.isEmpty()) {

            for (String key : map.keySet()) {
                if (i == 0) {
                    sb.append("?");
                } else {
                    sb.append("&");
                }

                sb.append(key);
                sb.append("=");
                sb.append(map.get(key));

                i++;
            }
        }
        return sb.toString();
    }
}

Android resource array and usage simple

resource using simple


import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import com.sodonsolution.android.utils.ResourceUtils;

/**
 * Created by IntelliJ IDEA.
 * User: boroo
 * Date: Dec 23, 2010
 * Time: 10:29:42 AM
 * To change this template use File | Settings | File Templates.
 */
public class ResourceManager {
    protected String[] Errors;

    public Resources getRes() {
        return res;
    }

    public void setRes(Resources res) {
        this.res = res;
        if(res != null) {
            Errors = getStringArray("news_errors");
        }
    }

    private Resources res;

    public ResourceManager() {
    }

    public String getError(int index) {
        if (Errors.length <= index) {
            return "Error is not found!";
        } else {
            return Errors[index];
        }
    }

    public String getString(String resName) {
        int i = res.getIdentifier(resName, "string", StaticConfigs.DEFAULT_RESOURCE_PACKAGE);
        return res.getString(i);
    }

    public String[] getStringArray(String resName) {
        int i = res.getIdentifier(resName, "array", StaticConfigs.DEFAULT_RESOURCE_PACKAGE);
        return res.getStringArray(i);
    }

    public Drawable getDrawable(int i) {
        return res.getDrawable(i);
    }

    public Drawable getDrawable(String resName) {
        return res.getDrawable(res.getIdentifier(
                resName,
                "drawable",
                StaticConfigs.DEFAULT_RESOURCE_PACKAGE
        ));
    }
}

Friday, December 3, 2010

Spring framework usage for JSP

Тусгай тэмдэгтийн тайлбар: <any> нь any бол заавал бичигдэх ёстой зүйлийг заана.

  1. WebLayoutController

public class <Name>Controller extends WebLayoutController {
/**
*for <td>${<contextname>_}</td>
*/
private static final String DEFAULT_CONTENT_OBJECT_PREFIX = "<contextname>_";
/**
*List list = manager.list(id, site);
*request.setAttribute(prefix+“list”, list);
*/
private <Name>Manager manager;
/**
*for <td>${<prefix>list}</td>
*/
private String prefix = DEFAULT_CONTENT_OBJECT_PREFIX;

@Override
protected ModelAndView handleSiteRequest(HttpServletRequest request
, HttpServletResponse httpServletResponse
, ModelAndView modelAndView
, PageInfo pageInfo, WebSite webSite) throws Exception {

Object clientId = request.getSession()
.getAttribute(webSite.getConfiguration(Config.SESSION_CLIENT_ID));
String clientStatus = request.getParameter(“firstname”);

if (clientId == null || !clientStatus.equals(“in”)) {
//response any jump url
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
  response.setHeader("Pragma","no-cache"); //HTTP 1.0
  response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
response.sendRedirect(request.getContextPath()
+ "/<key of Controller>(home.shtml .etc)");
return null;
} else {
//response any content page with layout page
modelAndView.addObject(CONTENT_JSP_KEY, <contentPageName> + ".jsp");
}
return modelAndView;
}



  1. AbstractController

public class ClientXdataController extends AbstractController {
/**
*for <td>${<contextname>_}</td>
*/
private static final String DEFAULT_CONTENT_OBJECT_PREFIX = "<contextname>_";
/**
*List list = manager.list(id, site);
*request.setAttribute(prefix+”list”, list);
*/
private <Name>Manager manager;
/**
*for <td>${<prefix>list}</td>
*/
private String prefix = DEFAULT_CONTENT_OBJECT_PREFIX;

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request
, HttpServletResponse response) throws Exception {

WebSite webSite = WebUtil.getSiteFromRequest(httpServletRequest);
Object client = request.getSession()
.getAttribute(webSite.getConfiguration(Config.SESSION_CLIENT_ID));

if (client == null && “”.equals(client)) {
//response any content page
ModelAndView next = new ModelAndView(
webSite.getName()+"/"+webSite.getTemplate()
+"/<title of Controller>(home .etc)");
return next;
} else {
//response any text
response.getWriter().println("OK");
return null;
}
}
}

Sequence:

request url - > Servlet ( load spring framework ) - > call controller ( return modelAndView ) - > print jsp ( with data );

Thursday, December 2, 2010

Android phone app listview with ( icon, title, description ) simple

Бүрэн гүйцэт ажиллана

download or save into res/drawable/icon.png,  res/drawable/menu.png

res/drawable/gradient_background_grey.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#424242"
        android:endColor="#222222"
        android:angle="0"
     />
    <corners android:radius="0dp" />
</shape>


res/layout/listview.xml

<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_height="wrap_content"
              android:layout_width="fill_parent">
    <TableRow
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
        <ImageView
                android:id="@+id/ImageView01"
                android:src="@drawable/menu"
                android:layout_height="fill_parent"
                android:layout_width="wrap_content"></ImageView>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      android:orientation="vertical"
                      android:layout_height="fill_parent"
                      android:layout_width="fill_parent">
            <TextView
                    android:id="@+id/TextView01"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#FFFF00"></TextView>
            <TextView
                    android:id="@+id/TextView02"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:textColor="#0099CC"></TextView>
        </LinearLayout>
    </TableRow>
</TableLayout>


res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <TextView
            android:id="@+id/TextView01"
            android:layout_height="wrap_content"
            android:background="@drawable/gradient_background_grey"
            android:text="List of Country &amp; their denotation"
            android:textStyle="normal|bold"
            android:gravity="center_vertical|left"
            android:layout_width="fill_parent"></TextView>
    <ListView
            android:id="@+id/ListView01"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:duplicateParentState="false">
    </ListView>
</LinearLayout>


src/package/MainActivity.java

import android.app.Activity;
import android.os.Bundle;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

    private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public EfficientAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
        }

        public int getCount() {
            return country.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listview, null);
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.TextView01);
                holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(curr[position]);
            holder.text2.setText(country[position]);

            return convertView;
        }

        static class ViewHolder {
            TextView text;
            TextView text2;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView l1 = (ListView) findViewById(R.id.ListView01);
        l1.setAdapter(new EfficientAdapter(this));
    }

    private static final String[] country = { "Iceland", "India", "Indonesia",
"Iran", "Iraq", "Ireland", "Israel", "Italy", "Laos", "Latvia",
"Lebanon", "Lesotho ", "Liberia", "Libya", "Lithuania",
"Luxembourg", "Iceland", "India", "Indonesia",
"Iran", "Iraq", "Ireland", "Israel", "Italy", "Laos", "Latvia",
"Lebanon", "Lesotho ", "Liberia", "Libya", "Lithuania",
"Luxembourg"};
    private static final String[] curr = { "ISK", "INR", "IDR", "IRR", "IQD",
"EUR", "ILS", "EUR", "LAK", "LVL", "LBP", "LSL ", "LRD", "LYD",
"LTL ", "EUR", "ISK", "INR", "IDR", "IRR", "IQD",
"EUR", "ILS", "EUR", "LAK", "LVL", "LBP", "LSL ", "LRD", "LYD",
"LTL ", "EUR"};

}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example">
    <application android:icon="@drawable/icon" android:label="Simple Android Project">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Android context menu simple

ContextMenu харахдаа анх холбож өгсөн компонент дээрээ удаан дараад авахад гарч ирнэ

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example">
    <application android:icon="@drawable/icon" android:label="Simple Android Project">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <TextView
            android:id="@+id/text"
            android:textColor="?android:textColorPrimary"
            android:text="hello"
            android:background="@android:drawable/title_bar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    <Button
            android:id="@+id/button"
            android:text="call contextmenu"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"           
            />
</LinearLayout>


res/layout/contextmenu.xml not use.


MainActivity.java

package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn = (Button) findViewById(R.id.button);
        registerForContextMenu(btn);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Context Menu");
        menu.add(0, v.getId(), 0, "Action 1");
        menu.add(0, v.getId(), 0, "Action 2");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if(item.getTitle()=="Action 1"){function1(item.getItemId());}
        else if(item.getTitle()=="Action 2"){function2(item.getItemId());}
        else {return false;}
        return true;
    }

    public void function1(int id){
        Toast.makeText(this, "function 1 called", Toast.LENGTH_SHORT).show();
    }
    public void function2(int id){
        Toast.makeText(this, "function 2 called", Toast.LENGTH_SHORT).show();
    }
}

Android options menu simple



AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example">
    <application android:icon="@drawable/icon" android:label="Simple Android Project">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <TextView
            android:id="@+id/text"
            android:textColor="?android:textColorPrimary"
            android:text="hello"
            android:background="@android:drawable/title_bar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    <Button
            android:id="@+id/button"
            android:text="call contextmenu"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"           
            />
</LinearLayout>

res/layout/options.xml


<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/icon"
        android:icon="@drawable/icon" />
    <item android:id="@+id/text"
        android:title="Text" />
    <item android:id="@+id/icontext"
        android:title="Icon and text"
        android:icon="@drawable/menu" />
</menu>

MainActivity.java

package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * Displays a word and its definition.
 */
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.icon:     Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
                                break;
            case R.id.text:     Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
                                break;
            case R.id.icontext: Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
                                break;
        }
        return true;
    }
}