Saturday, August 25, 2012

Working Colors And Images In Android Application

-->

-->
For the Following Article, I will be using the simple Application developed here .
Basically as every one knows Colors and Images are used in Android Application to set background color / Image or Images can also be used to set an Image for 'ImageView' Element or Button with Image etc.
Following article will help you to define colors, images in your Android Application and use them.

First we will see how to add / define and work with Colors in your Android Application.

To use colors in your Android Application you need to define them in Resource file, To do the same, right click on the res (resources)>values folder, New > Android XML File

Following dialog will open, 


-->
Specify the name of the file as 'colors' say finish and in background, 'colors.xml' file will be created in your res>values folder.
In this file define colors names and color codes as follows:


 
-->
These color codes you can easily find by Googling over internet.

Once these colors are defined you can use them any where in your Android application.

For Example you want to set the background for a layout, In your xml activity file, as soon as you write the following line

android:background="@color/"

and press 'cntrl + space' you will see the list of your defined colors populates as shown in the following screen short. 
-->
Now suppose I have selected 'Pink' As the background color, then following is the output of the Application in the Emulator i.e. 'Pink' Color set as background color.



 
-->
Now we will move over on using Images In Android Application,

To use Images, you need to add Images in your 'res>drawable' folder, there will already 4 versions of drawable folder present in your 'res' folder namely,
drawable- hdpi
drawable-ldpi
drawable- mdpi
drawable-xhdpi

create an Additional 'drawable' folder in 'res' folder and then copy paste images in this (res>drawable) folder you want to use in your Application.

For my application here, I have created a 'drawable' folder and added three Images,
'help.png'
'htmlbackground.png'
and 'mug.png'

Directory structure will be as follows,

 
-->
Notice the highlited drawable folder with the images in the same.

Once these Images are defined you can start using the same in your application, For Example If you want to set the background of a layout as particular Image, then start typing following lines in your activity xml file,

android:background="@drawable/"

You will get the dropdown list of all the images added as follows,

 
-->
Now suppose I have selected 'htmlbackground.png' as background image of layout, then following will be the output in Emulator, i.e. Background of the layout as defined image.


 
-->
Similarly, For ImageView, While Creating an Image View in Android Application, In your activity xml file, Graphical layout, if you drag the 'Image View' control from the tool box to your screen, following dialog appears, where you can select the images that you have added in your 'drawable' folder.

-->
If I have selected 'help.png' for the Image view, then following will be the output in your Emulator,

 Similarly it works for Image on button as well.

I hope this article was useful to get working with Colors and Images in your Android Applications.

Thats all for now!

Happy Coding!

~Mayuri


Tuesday, August 21, 2012

Creating New Application in Android ICS..

-->

Creating a new Application in Android through Eclipse IDE is very Simple... Just some points to be remembered of are listed below.

For Development, I'm using following,
Eclipse Juno,
Android 4.0.3 (API Level 15)
Ubuntu OS

After all the configurations done to setup Android In your system, To Start Creating a New Application,

Start Eclipse, Select File > New > 'Android Application Project',

If In New Selection, If 'Android Application Project' do no appear then,

Select Other > Android > Android Application Project.

Now Following Dialog / Wizard opens to Create New Project,

-->
Fill in the Entries for Application Name, Project Name and Package Name.
Application Name will be shown in Playstore when you host your application, as well as in the Manage Applications Menu in Settings option in your Phone when application is Installed.

Project Name is used by Eclipse, it should be unique in the workspace meaning that no other application in the Eclipse workspace should have the same name.
Typically Application Name and Project Name will be the Same, Here I have kept as 'HelloApplication'

-->
Now comes the package name, i.e. Base package name in which the first class / Java File corresponding to Main Launcher Activity will be created. It should be a valid java package name.

Also check that 'Create custom Launcher Icon' option is by default checked, If this option is checked, in the next wizard it will ask for the custom, icon, text etc for Launching your Android Application, If you dont want a custom Icon and want to go with the default ones you can unckeck this option. I will keep this option as checked.

After above entries is filled in, Go for 'Next' Option, you will get the following wizard, To Customize your Launcher Icon,


 
-->
In the foreground Option, Select Image, Browse the Icon which you wish to keep it as launcher Icon for your application, I have selected the Image of Computer here, Also for the Shape option, select 'None'. ( by default, Shape selection will be circle which will have a white spaced circle around your Icon)

Select Next, and wizard will have two options to create Activity, as shown, 

 
-->
As you are creating first project select BlankActivity And Press Next,

Next, Wizard will as to fill in your first Launcher Activity Parameters as follows,

-->
Fill In the ActivityName, LayoutName and the Title t the Application,

ActivityName will be the name of the JavaFile/Class File for the Main Launcher Activity.

LayoutName will be the name of the Android XML layout file for the Main Launcher Activity where your UI elements will be defined.

Next is the Title of the Application which will be seen in Launcher as well as the Title of the Activity.

Fill in the Required values as press Finish which will create the default Hello World Application with your filled parameters values as follows,


 
-->
Now create a new Android Emulator to test this new Application created as follows,


 
-->
When you run the Application by right clicking on the Application name in Eclipse, Select Run As > Android Application, Emulator will be launched with your Application running as shown

-->
In the Above Image notice the Title 'Hello' and the Custom Icon i.e. The Computer Image we used as parameters in create new application wizard.

Also If you go in to browse the applications in your Emulator, In the Applications Listing you will see your Application with your custom Title and Custom Icon as follows


 
-->
Notice the Application Named 'Hello' with the computer Image in the Application list.

So here you are...!! Done with creating a fresh new Application in Android with your own Custom Icon and App Name.!!

I hope this article helped the beginers to create new Application.



Happy coding!

~Mayuri

Monday, January 9, 2012

Working with JSON & PhoneGap Application

I Love to use JSON objects especially when working with PhoneGap Applications. I find it very comforting while transferring data from client to server and vice versa.

I will explain through a simple example how I use JSON to ease the client-server data transmission.

Example will be, a client asking for the details of the Employee working in the Accounts department.

Basic Algo for the Example will be as follows,
  • Client will make an Ajax request, asking for the Details of Employees working in an Accounts Department.
  • On receiving the Request, Server will fetch all the details of the Employees working in Accounts form Database, convert these details to an Json Objects and send back to the Client.
  • Client on Receiving the Response from the server will parse the JSON objects and convert the data in local JS variables and render the data at client side, i.e. in a table grid etc. as per requirements. 
At the client Side, Include the following js files,
  • json2.js 
  • jsonStringify.js
At Server Side, Include the following jar
  • json.jar
Data transferred from client (Phonegap Application) to server (Any jsp/servlet server or web service etc.) will be in the form of an Ajax request, you can make use of any JS library like Jquery, prototype, zepto etc. to make the Ajax request from client, I prefer to use Jquery or Zepto and the syntax use in the following example will be compatible with both i.e. Jquery and Zepto.

Code for the Client side Making an Ajax Request will be as follows, 

function getEmpDetails() {
$.ajax({       
type : 'POST',  
url : <Server URL>,
data : {   
   'DepartmentType': 'Accounts'
},  
dataType:'json',
success : function(data) {       
        },
error : function(xhr, type) { 
}  
}); 
}

Explanation of the Above code, 

The function, getEmpDetails() will make an Ajax request, following are the parameters,
  • type - 'POST', here GET and POST are the two values, I prefer to make POST request.
  • url – this value indicates the server url,  Server could be the Java Servlet, jsp, Web Service etc. 
  • data – this value indicates the request parameters to be sent to the server, here in this example, the name of the department we are sending i.e. 'Accounts'.
  • datatype – this value indicates the data type of the data which will be returned form the server, here the value 'json' indicates that the data sent as the response from the server to client will be in the json format.
  • success – this function will be executed after successfully getting the response from the server, explained in detail in the later section of this example.
  • error – this function will be executed if there is some kind of error in getting the response from the server, this error type may include, some connection error to server, if the data is corrupted or not in the particular format as expected etc.
At the Server Side, 
On Receiving the Request, following snippet of the code shows the server side processing,  Here my Server is the simple Java Servlet, Dont forget to include the json.jar for the same.
I have included the comments in each and every line of the code as an explanation.

// Declare the Response Object type which will be json, as client expects response in json format.
JSONObject responseObj = new JSONObject();
        
//Declare a List of type JSONObject as our data will have multiple employee details working in the Accounts department,

List<JSONObject> employeeDetails = new LinkedList<JSONObject>();

//Reading the Request Parameters, 

String depeartmentType = request.getParameter(“DepartmentType”);

For getting the Employee details, server may need to query the Database, and populate the jsonobjects as follows,

try{

// Directly moving to executing a sample query not including the //connection statements here

ResultSet rs = statement.executeQuery(“select * from employee where department = '”+depeartmentType+”'”);

while (rs.next()){
// here is where the json object is populated as follows,
JSONObject empObj = new JSONObject();
empObj.put("empId", rs.getString(“ID”));      
empObj.put("empName", rs.getString(“NAME”));         
empObj.put("empDateOfJoining", rs.getString(“DOJ”));  
empObj.put("empSalary", rs.getString(“SALARY”));     
// this temp json object added to the employeeDetails List of type //JSONObject.
employeeDetails.add(empObj);


// finally add the populated linked list to the response object
responseObj.put("employeeDetails", employeeDetails);
            

// Get the print writer object and send the above response object //to the Client.
            PrintWriter writer = response.getWriter();
            writer.write(responseObj.toString());
            writer.flush();


}catch(Exception e){
e.printStackTrace();
}



Now On Receiving the Response from the Server, the above method of the Client Side will Change as follows,

function getEmpDetails() {
$.ajax({       
  type : 'POST',  
  url : <Server URL>,
  data : {   
'Department': 'Accounts'
       },  
  dataType:'json',   
          success : function(data) { 
          var empObject = eval('(' + JSON.stringify(data) + ')');            
          var empObjectLen = empObject.employeeDetails.length;
          
          for (var i=0; i<empObjectLen; i++) {     
       
// Get the data in local JS variables
       var empId = empObject.employeeDetails[i].empId;
       var empName = empObject.employeeDetails[i].empName;
       var empDateOfJoining = empObject.employeeDetails[i].empDateOfJoining ;
       var empSalary = empObject.employeeDetails[i].empSalary;
  }            
  },
     error : function(xhr, type) { 
alert('Internal Error Occoured!'); 
}  
}); 
}

Explanation, 
On successfully getting the response from the server,   Response type will be as follows,

{"employeeDetails":[{"empId":"001","empName":"Sam","empDateOfJoining":"2011-07-07","empSalary":"60000"},
{"empId":"002","empName":"Pam","empDateOfJoining":"2010-06-07","empSalary":"40000"},
{"empId":"003","empName":"Dolly","empDateOfJoining":"2010-07-09","empSalary":"80000"},
{"empId":"004","empName":"Dona","empDateOfJoining":"2010-07-07","empSalary":"40000"},
{"empId":"005","empName":"Sam S","empDateOfJoining":"2011-04-08","empSalary":"20000"},
{"empId":"006","empName":"Pam P","empDateOfJoining":"2010-09-07","empSalary":"40000"},
{"empId":"007","empName":"Polla","empDateOfJoining":"2012-01-01","empSalary":"70000"}]}


Appropriate parsing of this response is done in the 'success' function, where whole response is breaked up and finally made available in the local JS variables which can be used further to render the data at client side in the Grid, tables etc. as per user requirements.

I hope this article was useful to the readers.

That's all from My End for Now!

Happy Coding!! :-))

~Mayuri





Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here