Thursday, December 29, 2011

Creating and Running Android Emulator from Eclipse


Emulators are good to test our android project when there is no device available with us. Emulator will emulate the actual android operating system but with certain limitations. How do we create and run them?

Am gonna write in detail about creating and running emulator from eclipse. If you have already installed ADT plugin in eclipse (if not see my post http://coffeewithtechie.blogspot.com/2011/12/install-and-configure-android-in.html) you must see AVD Manager under Windows menu.

1.       Click on the AVD Manager to open Android Virtual Device (AVD) Manager Window.




2.       Click on New button. It opens AVD creator window similar to the image below.

3.       Type in the Name for your emulator.
4.       Select the Android version you are going to target for your emulator, when you click on target dropdown it gives you a list of available sdk’s from your system to select. Choose anyone and proceed to next field.     
                

5.       CPU/ABI option is disabled by default, but when you select target sdk, it gets filled with the cpu associated with that sdk, usually (ARM(armeabi)).

6.       Specify the size of your sd card to be created for your emulator. Value must be integer eg, 1024 and you can select any one of the units (KiB, MiB, GiB) from the dropdown next to it. Skip the file option.

7.       If you want to take snapshot from your emulator check snapshot enable option. Am gonna leave unchecked for this post.

8.       Size determines the size of your emulator to be created in pixels. Either you can choose from built in size options which corresponds to real device screen sizes, else if you want bigger or smaller than that, always feel free to choose Resolution option and enter your own width and height. Built in size options varies based on the target platform selected. See the table below for available built in options.



Note: creating emulators of big size can go out of your monitor’s range. Make sure that emulator fits your window screen.

9.       Hardware lets you modify default hardware properties of your emulator. When you choose target sdk it’ll be filled with the default values for that platform. New option at the corner lets you add some more properties based on your requirement and availability.



10.   Click on Create AVD to create emulator.

Eclipse takes some time to create emulator and when done, newly created emulator will be listed in AVD Manger. Select your emulator and click Start to run emulator. When clicked on start, launch options pop-up appears, you can configure your launch options using this pop-up, just ignore it and click on launch for now to run emulator.

Emulator booting


Emulator after booting - in portrait mode

To change emulator’s orientation,

a.       Turn on numlock.

b.      Press and hold numlock and press number 7 from num keys.


Emulator – landscape mode



Wednesday, December 28, 2011

Install and Configure Android in Eclipse


To all curious programmers and newbies, who wants to get their hands dirty in android platform must have these things mentioned below in your system.

a.     Android SDK.
b.     Eclipse - one of the recommended IDE for android development.
c.      JDK - to compile your android code (which will be in java).
d.     ADT plugin for eclipse.

So, how do we get these things into our system?? Ok, will explain step by step about installing and configuring android. First let me detail about downloading android sdk.

Downloading Android SDK

Android sdk requires windows xp and higher versions of xp. Once you are ready with this, you can go ahead and download android sdk from android developers site, here is the link to download http://developer.android.com/sdk/index.html

You can either download zip or .exe file, .exe file is recommended for windows users. Make sure to install it in right path, as we need this path to configure eclipse. Once you are done with downloading SDK move to next step downloading eclipse.

Downloading Eclipse for Android

Eclipse is an IDE used to develop android applications. It provides an easy to use interface and lots and lots of features which makes developer life easy. I am gonna write about using eclipse in another post, for now lets concentrate on downloading eclipse into our system. You can download eclipse from this link 
When you click on this link, you’ll be taken to eclipse website and a list of available eclipse will be displayed. Now here is the confusion. Which IDE to download? To solve the confusion here is the solution. Android recommends few packages,

1.     Eclipse IDE for Java Developers
2.     Eclipse Classic
3.     Eclipse IDE for Java EE Developers

Download any one of the above packages and install. We completed half of the task. Next is to install our favorite JDK.

Downloading JDK (Java Development Kit)

(Skip this step if you already have java in your system. To test, open command prompt and type java –version command. If you are able to see java, then java is already installed in your system and you can save some Bandwidth by skipping this step)
Most of them may be familiar with java, for those who are new to java can download jdk from Oracle site, http://www.oracle.com/technetwork/java/javase/downloads/index.html .

Download the latest available jdk and install in your system. Once done with installation, go to command prompt and type java –version command. If you are able to see java, then java is installed successfully in your system. If you see any error message, don’t panic, if you know that java is installed in your system the error message might simple indicate that path variable is not set for java. Set the path variable and you are done.

Finally we are at the final step of downloading things. Remember we have not yet configured android sdk in eclipse which you guys are waiting for. 

Downloading ADT (Android Development Tools) for Eclipse

ADT is a plugin for eclipse which is essential to use eclipse for android development. How do we download it into eclipse?? We already have eclipse in our system (if not, refer downloading eclipse section above). Open eclipse by clicking ecplise.exe icon from your eclipse installation path. For the first time, it asks for workspace with pre-populated path, if you are happy with that location click ok else change the path and click ok. Eclipse opens and a nice welcome page welcomes you. We are not concerned with this now. What we need is to install ADT plugin. It involves series of steps,

1.     In menu bar, click on help -> install new software.

2.     Install window opens, which looks like this                 

                                                                           

3.     Copy and paste this url, https://dl-ssl.google.com/android/eclipse/ in the text box before “Add” button and click on “Add”.            
        

4.     A pop-up opens and give a name to this url and click ok.                              
Note: If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).



5.         In the Available Software dialog, select the checkbox next to Developer Tools and click Next. If you expand developer tools, you can see what are the addins are being installed into eclipse.

6.       In the next window, you'll see a list of the tools to be downloaded. Click Next.

7.       Read and accept the license agreements, then click Finish.
Note: If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
    
    8. When the installation completes, restart Eclipse.

After restarting eclipse click on windows menu, you should see something similar to this.           
               

If you can see Android SDK Manager and AVD Manager options, then we are in the right path.
We are done with installing all the softwares and tools necessary for android development. Now lets configure eclipse to use android sdk.

Configuring Eclipse for Android

It involves modifying the ADT preference to point to the Android SDK Directory.
 1.     Select Window > Preferences... to open the Preferences panel.



 2.  Now you should see Android in your preferences. Eclipse sometime tries to point to android sdk path automatically, if it is not pointing to sdk location then add your sdk location.

 
 
3.     If everything goes right, you will see all the available versions of sdk listed.

4.     Click Apply and ok to save and close preferences.

We are done with installing and configuring android in eclipse. Let’s try and create one simple android application in next post.










Friday, December 17, 2010

Create your own auto-complete control using JavaScript and asp.net web-service

Adding auto-complete to a textbox makes user life easy. User doesn’t have to type complete word which he is willing to type. Also its an added advantage to user experience. User expects a website to be fast and more user friendly and of course auto-complete is an user friendly option. There are many auto complete controls available to download for ex, autocompleteextender control in ajax control toolkit.

The disadvantage of using already built, third party control is lack of flexibility. You cannot edit and modify the code written by someone else until it is open source and code is available to download.

So how about creating our own auto-complete control for websites? It is cool, isn’t it?  Lets go ahead and create our own. What we need to do is to write some html, javascript and asp.net webservice(in case of programmers not using .net you can use ajax calls to methods which supplies array of string values to control). I’ll be using .asmx files, as it is more familiar. Speaking about webservices in .net is beyond the scope of this topic.

Enough theory, let me start with some code which you are willing to see here it goes.,

public class DbingleController
    {
DbingleContextDataContext currentcontext;
public DbingleController()
        {
            currentcontext = new DbingleContextDataContext();
       
        }

public List<string> GetWords(string searchingword)
        {
var words = currentcontext.SearchWords.Where(w => w.Word.ToLower().StartsWith(searchingword.ToLower()));
            List<string> wordslist = new List<string>();
wordslist = words.OrderByDescending(c => c.Count).Select(w=>w.Word).Skip(0).Take(10).ToList();
            return wordslist;
        }
    }
[WebMethod]
        public string[] GetWordsList(string querystring)
        {
            if (!string.IsNullOrEmpty(querystring))
            {
                DbingleController controller = new DbingleController();
                return controller.GetWords(querystring).ToArray();
            }
            return new string[0];
          
        }

GetWordsList is a method in webservice which we’ll be calling from javascript. It returns array of words from database starting with query string passed as method parameter. DbingleController is a class which speaks with database.It’s a linq class. Webservice calls method in Dbinglecontroller class which gets data from database. You can have your own database queried to return array of strings. At the end only array of strings matters.
Now how to call this webservice? To call webservice include the code in master page.

<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true"  runat="server">
    <Services>
        <asp:ServiceReference Path="~/services/DbingleService.asmx" />
    Services>
    asp:ScriptManager>

Path is the path to your webservice.

In aspx page create a textbox and add an <ul> next to it, here is where you fill up array of strings to achieve auto complete.

                <asp:TextBox ID="QueryTextBox" AutoCompleteType="None" autocomplete="off" runat="server"
                    Width="429px" Height="25px" onkeyup="javascript:fillbox(event)">asp:TextBox>
<ul id="autocompleteextender" style="border: 1px solid; display: none; float: left;
                    list-style: none outside none; margin: 0 0 0 292px; padding: 0px; width: 431px; z-index: 1000;
                    background-color: White;text-align:left;">
                ul>

Finally, it’s time to write javascript and complete auto-complete.

<style type="text/css">
        .selecteditem
        {
            background-color: aliceblue;
            text-align:left;
        }
    style>
<script type="text/javascript">
          var textboxoriginalvalue;
          var arr = [];
          var downkeycount = -1;

          function fillbox(e) {

              var unicode = e.keyCode ? e.keyCode : e.charCode;
              if (unicode != 13) {

                  if (unicode != 40 && unicode != 38) {
                      var value = jQuery('#<%= QueryTextBox.ClientID %>').val();                     
                      textboxoriginalvalue = value;
                      getprediction();
                  }
                  if (unicode == 40)//down arrow
                  {
                      downkeycount += 1;
                      highlightword();
}
                  if (unicode == 38)//up arrow
                  {
                      if (downkeycount > -1) {
                          downkeycount += -1
                      }
                      if (downkeycount == -1) {
                          downkeycount = (arr.length - 1);
                         }
                      highlightword();                   

                  }
              }
          }

          function getprediction() {                            Dbingle.services.DbingleService.GetWordsList(textboxoriginalvalue, success, CallFailed);
          }
function success(res) {
              arr = res;
              fillwords();
          }
function CallFailed(res) {
              alert(res.get_message());
          }

          function fillwords() {
              var ulhtml = "";
              for (var i = 0; i < arr.length; i++) {
                  ulhtml += '
  • ' + arr[i] + '

  • ';
                  }
                  if (arr.length > 0) {
                      var ul = document.getElementById('autocompleteextender');
                      ul.style.display = 'block';
                  }
                  jQuery('#autocompleteextender').html(ulhtml);

              }
    function highlightword() {
                  $textboxitem = jQuery('#<%= QueryTextBox.ClientID %>');
                  jQuery('#autocompleteextender li').removeClass('selecteditem');
                  $listitem = jQuery('#autocompleteextender li:eq(' + downkeycount + ')');
                  $listitem.addClass('selecteditem');
                  if (downkeycount >= arr.length) {
                      $textboxitem.val(textboxoriginalvalue);
                      downkeycount = -1;
                  }
                  else {                 
                      $textboxitem.val(arr[downkeycount]);
                  }
              }
           script>

    On keyup event call fillbox(e) method of javascript, this method calls webservice to get array of strings starting with typed word and fills <ul>

    The line “Dbingle.services.DbingleService.GetPrediction(textboxoriginalvalue, success, CallFailed);” In getprediction() method calls the webservice [Dbingle.services] is a namespace [DbingleService] is a webserivce which you have added path reference in master page earlier. [GetWordsList] is method textboxoriginalvalue parameter passed to the method , the next two parameters are JavaScript methods which is called on success and failure of request respectively.
    A list objects are created with the array returned which are added to <u> and style property is changed.

    On press of up/down arrow key, fillbox(e) method is called which highlights and fills the value of text box with selected value. Once the end array is reached, the text box value is replaced with original user entered value.
    So now our autocomplete control is ready. Let’s see how it looks








    I created this control for my website www.dbingle.com

    Friday, February 5, 2010

    Generating Random Unique Alpha-Numeric Ids , Identifiers or Codes

    Here is the code to generate random unique alpha-numeric ids. The seed is must which is used to generate the unique Ids. Based on the requirement you can also include special characters (*,&,$..etc ) in the seed , which are helpful in generating random passwords.



    The generated code length can be increased by making the for loop to loop the specified no of times by assigning desired value to length variable.

    The Thread.sleep() method used in the function can be removed if the usage of code is in website. If you are using this code of standalone application then this method is must depending upon the processor speed. You can try commenting out this line of code to see what difference it makes when using in standalone application. It shows how the execution of method depends on the processor speed.