2013年9月14日土曜日

Event prevent default is not working


If you are working on key action with jquery and having problems on event.preventDefault is not working. Let’s me explain something simple to you.

event.preventDefault

As given example on docs, it shows us how it works on click action. For instances, prevent default action of anchor request the given url when clicked, action of submit button clicked to submit the form.
So far so good.

bind.( “keydown” , function( event ){ return false; } );

preventDefault is good but when it comes to key action such as enter key on submit form and tab key on switching the focus of input element. It lose it effects. You will found out that enter key are still performing default action and others key as well.
So… what is the solution? Adding return false on handler. Snippets below shows an simple example on this solution.
$(document).bind('keydown', function(e){  
  
 return false; 
 
}); 

It’s works right!

What happens if you want only ‘enter’ key to be prevent default action. Here’s the solution.
$(document).bind('keydown', function(e){  
 var keyPressed = ('which' in e) ? e.which : e.keyCode;
  
 if( keyPressed == 13){         
  return false;
 }else{
  return true;
 }
 
}); 

Enter keycode is 13. Return true on event handler will allow the key to continue with default action and return false will stop event handler from continue to default action.



It’s still not working


There are a few quite common mistake make by people, especially for me. Either you too?


  • Errors inside the handler function

If there is errors (exp. syntax errors) occured inside the handler function, default action will be carry out even though there is return false in handler function. Don’t tried to ignore the errors that shows on your browser, it might be the core of your problems.


  • Mess up with JQuery instances and native Javascript instances

What does it means? Check it out with the differences at following codes.
$("ul").children("li")[0].html("");
$("ul").children("li")[0].innerHTML = "";

It is quite tricky problems, html() is jquery properties and innerHTML is javascript properties. But on this case, children(“li”) returns native javascript element array, so there is no method for html(“”) in returned element array. So, second code is the correct answer.

If you have do some checking by Object.keys( $(“ul”).children(“li”)[0] ); you will found out that the properties is different from jquery properties.

 


Conclusions


High level language doesn’t means you don’t have to understand the basic of it. Understanding basic sometimes will be the helper on solving problems.

Good luck

2013年9月6日金曜日

How to open select input method option menu programmatically on Android

Here's the snippets for Android to open the select input method option menu programmatically.

InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (mgr != null) {
    mgr.showInputMethodPicker();
}



2013年8月29日木曜日

Install ruby on rails for Aptana Studio 3 on Windows


I spent almost half of my day to install ruby on rails on my Windows PC. After a long fighting on installing, I found an EASY way for windows. Could be said as DAMN EASY.

What you need to do is download the latest version from Rails installer site and run it. Don’t need to download Ruby Installer, as it is included inside Rails installer. What you need to do is waiting until it’s done.

After installed, you can test it by open command prompt and go to whatever testing directory and type
rails new TestApps
cd TestApps
rails server

Then, open browser and go to http://localhost:3000 .If you are able to see the page. Congratulation, you are done with ruby on rails install.

Last things is to download Aptana Studio 3.

Caution here, make sure you install rails first instead of Aptana studio. Otherwise, you have to configure the path for rails on Aptana studio.

If you received error "Unable to find 'rdebug-ide' binary script. May need to install 'ruby-debug-ide' gem, or may need to add your gem executable directory to your PATH", when debug ruby in Aptana studio.



Install ruby-debug-ide by following command
gem install ruby-debug-ide

Then, restart your Aptana studio. You should be able to debug ruby file.

Okay! Hope you are already in coding. Thank you for reading.

2013年8月21日水曜日

Crop Images into pieces for java applet

By using CropImageFilter class, images can be cropped easily with few lines. According to Java docs, parameter of CropImageFilter constructor is
        CropImageFilter(int x, int y, int w, int h)

First, load the image from folder. Here's is the method I prepared.
    private Image loadImage(String img){
        return getImage(app.getDocumentBase(),"img/"+img);
    }

For eclipse IDE, I put my images file inside the src/img package.


After load the image, let's say "image_want_chop.png" is loaded and chop it with following code.
        Image originalImage = loadImage("image_want_chop.png");
        ImageFilter imageFilter = new CropImageFilter(x,y,width,height); 
        Image choppedImage = createImage(new FilteredImageSource(originalImage.getSource(),
                        imageFilter ));

Thank you for reading.

2013年8月20日火曜日

Split MySQL select data into multiple pages by using LIMIT


Our goal is to split the selected MySQL data into multiple pages and display current page and the data show on specify page.
mysql_page1


Introduce to LIMIT clause

Let’s say the limit of data on single page is 10 rows, and current page is page 2. It means I need to show the data begin from 20th to 30th. So what I need to do is to set the offset value and length of data selected.
    $offset = 0;
    $length_of_data = 10;
    $query = "SELECT * FROM mytable LIMIT {$offset} ,{$length_of_data}";

The parameter of LIMIT clause is LIMIT offset, length

Optimize the query


To prevent sql injection, we need to modify the code above into bottom.
    $length_of_data = 10;
    $query = "SELECT * FROM mytable LIMIT :offset ,{$length_of_data}";
    $page = intval(trim($_GET["page"]));
    $offset = $page * $length_of_data;
 
    try{               
        $stmt = $db->prepare($query);
        $stmt->bindParam(':offset',$offset,PDO::PARAM_INT);
        $stmt->execute();
    }catch(PDOException $ex){        
        die ($ex);
    }

Caution : According to stackoverflow, seem like there is a bug when using execute(array(“:offset”=>0)) or bindParam(“:offset”,trim($offset),PDO::PARAM_INT) without intval function. So it is better using what I given on above. I hope it works for your guys.

You can test it by add ?page=0 to your end of the url. It will show you the first 10 rows data without offset.

Display current page and all available pages


It is the last things we need to do. First get the total rows number from table. Then show the current page with special view and other pages with normal view.
 
    $query = "SELECT * FROM mytable";
    try{
        $stmt = $db->prepare($query);
        $stmt->execute();
    }catch(PDOException $ex){
        die ($ex); 
    }

    $rows = $stmt->fetchAll();
    $count = count($rows);
    for($num = 0;$num < $count / $limit_row;$num++){     
        if($page == $num){
            echo '<a href="forum_main.php?page'.$num.'"><span class="page_number current">'.   ($num+1).'</span></a>';
        }else{         
            echo '<a href="forum_main.php?page='.$num.'"><span class="page_number">'.($num+1).'</span></a>';
        }
    }

Here’s we done! Thank you for reading.

2013年7月6日土曜日

Simple Custom Dialog for Android

Android developers have provided us based on how to create a custom dialog by using alertdialog.builder method. If you are interesting with it, here’s the link. http://developer.android.com/guide/topics/ui/dialogs.html

I am going to shows another way instead of using alertdialog.builder. What is the benefit of this method is you can update the content of dialog view dynamically and directly.

If you are thinking changing the content of dialog when the button is pressed without closing dialog. You might give a try on this method.

First, create the layout for custom dialog

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/dialog_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is custom dialog"/>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/dialog_positive_button"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="positive"/>
<Button
android:id="@+id/dialog_negative_button"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="negative"/>

</LinearLayout>

</LinearLayout>

Then, create the custom dialog class

class SimpleCustomDialog extends AlertDialog{
 
 TextView text;
 
 SimpleCustomDialog(Context ctx){
  super(ctx);
  setTitle("Custom Dialog");
  
  LayoutInflater inflater = getLayoutInflater();
  View view = inflater.inflate(R.layout.alertdialog_layout, null);
  
  text = (TextView)view.findViewById(R.id.dialog_text);
  text.setText("this is custom dialog");
  
  Button positiveButton = (Button)view.findViewById(R.id.dialog_positive_button);
  Button negativeButton = (Button)view.findViewById(R.id.dialog_negative_button);
  
  positiveButton.setOnClickListener(new PositiveButtonListener());
  negativeButton.setOnClickListener(new NegativeButtonListener());
  setView(view);
 }
 
 class PositiveButtonListener implements View.OnClickListener{
  @Override
  public void onClick(View view) {
   text.setText("Button clicked");  
  }   
 }

 class NegativeButtonListener implements View.OnClickListener{
  @Override
  public void onClick(View view) {    
   // dialog wouldn't dismiss itself, you have to call dismiss method 
   //dismiss dialog
   SimpleCustomDialog.this.dismiss();  
  }   
 }
 
}

finally call show method to show dialog

SimpleCustomDialog mDialog = new SimpleCustomDialog(this);
mDialog.show();

If you want to dismiss the dialog, just call dismiss method.


Hope this article helps you. Thank your for reading.