optimisation and performance in android

127
Optimisation and Performance Rakesh Kumar Jha M. Tech, MBA Delivery Manager

Upload: rakesh-jha

Post on 30-Jun-2015

422 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Optimisation and performance in Android

Optimisation and Performance

Rakesh Kumar JhaM. Tech, MBA

Delivery Manager

Page 2: Optimisation and performance in Android

Optimisation and Performance What is Optimisation and Performance Memory Efficiently Networking Location Optimizing Graphics and UI

Optimizing Layouts Layout Tools

Benchmarking And Profiling Tracing Logging

Q & A

Page 3: Optimisation and performance in Android

What is Optimization

• Finding an alternative with the most cost effective or highest achievable performance under the given constraints, by maximizing desired factors and minimizing undesired ones.

Page 4: Optimisation and performance in Android

What is Optimization

• In comparison, maximization means trying to attain the highest or maximum result or outcome without regard to cost or expense.

• Practice of optimization is restricted by the lack of full information, and the lack of time to evaluate what information is available.

Page 5: Optimisation and performance in Android

What is Optimization

• In computer simulation (modeling) of business problems, optimization is achieved usually by using linear programming techniques of operations research.

Page 6: Optimisation and performance in Android

Optimization in Android

• Android devices having limited– Memory• Clean RAM and • Dirty RAM.

– Processor

Page 7: Optimisation and performance in Android

Clean RAM

• Unlike PCs, Android does not offer swap space for memory, however it does use paging and memory-mapping.

• Any files or resources which are present on the disk, such as code, are kept in mmap’ed pages.

• Android knows these pages can be recovered from the disk, so they can be paged out if the system needs memory somewhere else

Page 8: Optimisation and performance in Android

Dirty RAM

• Dirty RAM is the memory that cannot be paged out.

• It can be expensive, especially when running in a background process.

• Most of the memory in a running application is dirty memory and this is the one you should watch out for.

Page 9: Optimisation and performance in Android

Dirty RAM

• In order to optimize the memory usage, Android tries to share some framework resources or common classes in memory across processes.

Page 10: Optimisation and performance in Android

Dirty RAM

• whenever a device boots up, a process called zygote loads the common framework code.

Page 11: Optimisation and performance in Android

Dirty RAM

• Every new application process is then forked from the zygote process so it is able to access all the shared RAM pages loaded by it.

Page 12: Optimisation and performance in Android

Dirty RAM

• While investigating an application’s RAM usage, it is important to keep shared memory usage in mind since we should only be looking at the private dirty memory that is being used by our application.

• This is reflected by USS (unique set size) and PSS (proportional set size) in ‘meminfo.’

Page 13: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

• So what can you do to keep your system from running out of memory?

Page 14: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

• So what can you do to keep your system from running out of memory?

• I’ll discuss about 30 points, we have to keep in mind while developing mobile/handheld applications.

Page 15: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

1. ScrollViews and ListViews are an easy win.2. Use the folder structures3. 160dp = 1 inch. 320 dp = 2 inches. dp == dip4. Resource rules of thumb:5. you don’t have to tailor all your layout files,

you could instead tailor the dimens.xml files.6. Let whitespace scale more than graphics. Let

graphics scale more than buttons.

Page 16: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

7. Use the GraphicalLayout tool for fast previewsGraphicalLayout is the WYSIWG editor for XML files

Page 17: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

8. Don’t scale all your imagesThe conceptually simplest way of doing this is to produce a whole host of images and pop them into a matching plethora of drawable folders

Page 18: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

9. Avoid bitmaps (jpg, png).

Try to avoid .jpg or png images, this images are easy to implement, but you can save lot of space and achieve much sharper result by 9-patch image, even better to use xml

Page 19: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

10.Use XML Drawables.

Wherever you can use XML drawables instead of bitmaps. XML drawables won’t let you do everything, but improve your performance.

Page 20: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

11. Use XML Drawables.

Wherever you can use XML drawables instead of bitmaps. XML drawables won’t let you do everything, but improve your performance.

<shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle" ><cornersandroid:bottomRightRadius="14dp"android:bottomLeftRadius="14dp"android:topLeftRadius="14dp"android:topRightRadius="14dp"/><gradientandroid:startColor="@color/off_white"android:endColor="@color/pale_yellow"android:angle="270"android:type="linear"/><strokeandroid:width="4dp"android:color="@color/osm_darkerblue"/></shape>

Page 21: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

12. Why use 9-patch (when you can use XML drawables)

Page 22: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

13. Create custom views by overriding onDraw()

There are some things XML just isn’t so great at, we draw a lot of graphs in OpenSignal and WeatherSignal and there are libraries for this, but we coded our graphs custom.It’s kind of fun. You might never need to do it, but to make graphics that are highly dynamic and custom it is often the only way to go.

Page 23: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

14. Use SVG where you can’t use XML

Sometimes overriding onDraw() and painstakingly coding up all the lines and arcs you need to draw your custom view is overkill. After all, there is a language for vector graphics, it’s called … Scalable Vector Graphics

Page 24: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

15. GZip your SVG files.

Makes them smaller and they parse quicker.

Page 25: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

16. Customise your UI widgets.

To make sure your app looks the same on all devices, you’ll need to customise everything, it’s not as hard as you might think and in doing so you’ll get a lot more control over how your app looks.

Page 26: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

17. Selectors are super for building buttons.

what do you do to create a button that changes when clicked? Easy: define the background to be an XML file as below, which will receive the button state and serve up the appropriate drawable.

Page 27: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

17. Selectors are super for building buttons.

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true" android:drawable="@drawable/btn_bg_selected" /><item android:state_focused="true" android:drawable="@drawable/btn_bg" /><item android:drawable="@drawable/btn_bg" /> <!-- default -->

</selector>

Page 28: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

18. The ActionBar and many animation styles didn’t exist pre Honeycomb, use ActionBarSherlock and NineOldAndroids instead.

Page 29: Optimisation and performance in Android

Targeting speed

Page 30: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

19. Test on slow phones.

You’ll not only see any problems with slowness, but they’ll drive you nuts, no-one likes a slow app.

Page 31: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

20. Keep your XML layout hierarchy flat.

More layers means the system does a lot more work parsing your code and it can take views longer to deploy.

Page 32: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

21.Use Android Lint.

Right click on project folder in Eclipse>Android Tools>Run Lint. This can catch a host of things that can improve speed, or just make your code cleaner.

Page 33: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

22. Android Lint can get it wrong.

It can suggest things that will break your code in subtle ways, so do understand what it suggests before you make changes

Page 34: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

23. Using <merge> can help flatten your view hierarchy.

Simple way of getting rid of superfluous layers.

http://android-developers.blogspot.com.ar/2009/03/android-layout-tricks-3-optimize-by.html

Page 35: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

24. Use HierarchyViewer to see your layout hierarchy.

This is a brilliant tool which shows just how many layers of layouts you have and which of them are slowing things down.

Page 36: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

25. Use RelativeLayout whenever you can.

Page 37: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

26. Use external profilers as well as DDMS

Page 38: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

27. Use AsyncTasks

Page 39: Optimisation and performance in Android

Targeting low file size

Page 40: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

28. Some Android devices have a 100mb limit

Page 41: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

29. Use XML resources (last time I recommend this, I promise)

Page 42: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

30. When you must use PNGs always optimize (with PNGCrush or ImageOptim)

Page 43: Optimisation and performance in Android

Targeting bugs

Page 44: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

31. On the Android developer console check for any bugs that have been sent automatically.

Page 45: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

32. ProGuard is turned on by default now. Proguard is awesome (speeds up your app and reduces filesize) but it can make StackTraces very obscure.

Page 46: Optimisation and performance in Android

Memory Optimization, Best Practices For Android

33. Adjust ProGuard config to show line numbers in StackTraces. Make sure your proguard.cfg has a line:-keepattributes SourceFile,LineNumberTable

Page 47: Optimisation and performance in Android

Networking

Page 48: Optimisation and performance in Android

Background Data and Data Transfer

Page 50: Optimisation and performance in Android

ConnectivityManager

• The primary responsibilities of this class are to:• Monitor network connections (Wi-Fi, GPRS, UMTS,

etc.)• Send broadcast intents when network connectivity

changes• Attempt to "fail over" to another network when

connectivity to a network is lost• Provide an API that allows applications to query the

coarse-grained or fine-grained state of the available networks

Page 52: Optimisation and performance in Android

Checking Network Connection

Page 53: Optimisation and performance in Android

Checking Network Connection

• Android lets your application connect to the internet or any other local network and allows you to perform network operations.

Page 54: Optimisation and performance in Android

Checking Network Connection

• A device can have various types of network connections.

• We will focuses on using either a Wi-Fi or a mobile network connection.

Page 55: Optimisation and performance in Android

Checking Network Connection

• Before you perform any netowrk operations, you must first check that are you connected to that network or internet e.t.c.

• For this android provides ConnectivityManager class.

• You need to instantiate an object of this class by calling getSystemService() method. Its syntax is given below:

Page 56: Optimisation and performance in Android

Checking Network Connection

ConnectivityManager check = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);

Page 57: Optimisation and performance in Android

Checking Network Connection

Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the information of all the networks. This method returns an array of NetworkInfo. So you have to recieve it like this.

Page 58: Optimisation and performance in Android

Checking Network Connection

NetworkInfo[] info = check.getAllNetworkInfo();

Page 59: Optimisation and performance in Android

Checking Network Connection

The last thing you need to do is to check Connected State of the network. Its syntax is given below:

for (int i = 0; i<info.length; i++){ if (info[i].getState() == NetworkInfo.State.CONNECTED){ Toast.makeText(context, "Internet is connected Toast.LENGTH_SHORT).show(); }}

Page 60: Optimisation and performance in Android

Checking Network Connection

Apart from this connected states, there are other states a network can achieve. They are listed below:

Sr.No State1 Connecting2 Disconnected3 Disconnecting4 Suspended5 Unknown

Page 61: Optimisation and performance in Android

Performing Network Operations

After checking that you are connected to the internet, you can perform any network operation. Here we are fetching the html of a website from a url.

Page 62: Optimisation and performance in Android

Performing Network Operations

Android provides HttpURLConnection and URL class to handle these operations. You need to instantiate an object of URL class by providing the link of website. Its syntax is as follows:

Page 63: Optimisation and performance in Android

Performing Network Operations

String link = "http://www.google.com";URL url = new URL(link);

Page 64: Optimisation and performance in Android

Performing Network Operations

After that you need to call openConnection method of url class and recieve it in a HttpURLConnection object. After that you need to call the connect method of HttpURLConnection class.

Page 65: Optimisation and performance in Android

Performing Network Operations

HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.connect();

Page 66: Optimisation and performance in Android

Performing Network Operations

And the last thing you need to do is to fetch the HTML from the website. For this you will use InputStream and BufferedReader class. Its syntax is given below:

InputStream is = conn.getInputStream();BufferedReader reader =new BufferedReader(new InputStreamReader(is, "UTF-8"));String webPage = "",data="";while ((data = reader.readLine()) != null){ webPage += data + "\n";}

Page 67: Optimisation and performance in Android

Performing Network Operations

And the last thing you need to do is to fetch the HTML from the website. For this you will use InputStream and BufferedReader class. Its syntax is given below:

InputStream is = conn.getInputStream();BufferedReader reader =new BufferedReader(new InputStreamReader(is, "UTF-8"));String webPage = "",data="";while ((data = reader.readLine()) != null){ webPage += data + "\n";}

Page 68: Optimisation and performance in Android

PHP - MYSQL

Page 69: Optimisation and performance in Android

• we are going to explain, how you can integrate PHP and MYSQL with your android application.

• This is very useful in case you have a webserver, and you want to access its data on your android application.

Page 70: Optimisation and performance in Android

CREATING DATABASE

<?php$con=mysqli_connect("example.com","username","password");$sql="CREATE DATABASE my_db";if (mysqli_query($con,$sql)){ echo "Database my_db created successfully";}?>

Page 71: Optimisation and performance in Android

CREATING TABLES

<?php$con=mysqli_connect("example.com","username","password","my_db");$sql="CREATE TABLE table1(Username CHAR(30),Password CHAR(30),Role CHAR(30))";if (mysqli_query($con,$sql)){ echo "Table have been created successfully";}?>

Page 72: Optimisation and performance in Android

INSERTING VALUES IN TABLES

<?php$con=mysqli_connect("example.com","username","password","my_db");$sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES ('admin', 'admin','adminstrator')";if (mysqli_query($con,$sql)){ echo "Values have been inserted successfully";}?>

Page 73: Optimisation and performance in Android

PHP - GET AND POST METHODS<?php$con=mysqli_connect("example.com","username","password","database name");if (mysqli_connect_errno($con)){ echo "Failed to connect to MySQL: " . mysqli_connect_error();}$username = $_GET['username'];$password = $_GET['password'];$result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' and Password='$password'");$row = mysqli_fetch_array($result);$data = $row[0];if($data){echo $data;}mysqli_close($con);?>

Page 74: Optimisation and performance in Android

Android - Connecting MYSQL

• There are two ways to connect to MYSQL via PHP page.

• The first one is called Get method. We will useHttpGet and HttpClient class to connect. Their syntax is given below:

URL url = new URL(link);HttpClient client = new DefaultHttpClient();HttpGet request = new HttpGet();request.setURI(new URI(link));

Page 75: Optimisation and performance in Android

Android - Connecting MYSQL

• After that you need to call execute method of HttpClient class and recieve it in a HttpResponse object.

• After that you need to open streams to recieve the data.

HttpResponse response = client.execute(request);BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

Page 76: Optimisation and performance in Android

CONNECTING VIA POST METHOD

• In the Post method , the URLEncoder,URLConnection class will be used.

• The urlencoder will encode the information of the passing variables.

• It's syntax is given below:URL url = new URL(link); String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URLConnection conn = url.openConnection();

Page 77: Optimisation and performance in Android

CONNECTING VIA POST METHOD

• The last thing you need to do is to write this data to the link.

• After writing , you need to open stream to recieve the responded data.

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

Page 78: Optimisation and performance in Android

Type of web services

• Web service is a system that enables applications to communicate with an API.

• Web service helps to expose business logic through an API interface where different systems communicate over network.

Page 79: Optimisation and performance in Android

Type of web services

Page 80: Optimisation and performance in Android

Type of web services

• Application to application communication.• Interoperability between disparate systems.• Communication over network.• Exposed interface is platform independent and

internal implementation is abstracted.• Enables loosely coupled design.• Open protocol is used for establishing

communication.• Web services are self contained.

Page 81: Optimisation and performance in Android

Components of a Web Service

wsdl

Page 82: Optimisation and performance in Android

Type of web services

• Web Services Description Language (WSDL) is used to describe a web service in an XML file.

• It covers all the aspects of a web service like what is the message format, communication protocol, endpoint, security etc.

• This is a standard provided by W3C consortium and widely accepted for web services description.

Page 83: Optimisation and performance in Android

Type of web services

• A wsdl xml file for a web service is generally expected to be published publicly so that parties seeking to utilize its services can understand the nature of service and consume it accordingly.

Page 84: Optimisation and performance in Android

Type of web services

• Types is an important element in WSDL. It is used to describe the message attributes and respective types.

• XSD is the preferred format to describe the types.

• Type definition can be given in a separate XSD file and imported in WSDL.

Page 85: Optimisation and performance in Android

Type of web services

<definitions .... > <types> <xsd:schema .... />* </types>

</definitions>

Page 86: Optimisation and performance in Android

UDDI

Page 87: Optimisation and performance in Android

• Universal Description, Discovery and Integration (UDDI) is a directory service.

• Web services can register with a UDDI and make themselves available through it for discovery.

Page 88: Optimisation and performance in Android

Stub and Skeleton

• Stub and skeleton are counterparts in a web service setup. Skeleton belongs to service provider side and stub belongs to receiver side.

• At lower level stub and skeleton communicate with each other.

Page 89: Optimisation and performance in Android

Endpoint

• An endpoint is a particular network location with associated protocol which includes message format mapping using which we can access that instance of web service.

• This is described in WSDL file. Consider this as a handle using which we will access the web service.

Page 90: Optimisation and performance in Android

Binding

• Associating an interface with a protocol and message format is binding.

• It is used in endpoint definition. Binding is described in WSDL.

Page 91: Optimisation and performance in Android

Operation

• A single logical grouping of a meaningful action which comprises a request and response is an operation. Group of operations forms a web service.

Page 92: Optimisation and performance in Android

SOAP

• Simple Object Access Protocol is a XML based specification for web services message format and communication over network. That is it helps to describe the transport method and message format in a web service.

Page 93: Optimisation and performance in Android

Web Service Design

• As given in diagram a web service has logic and an interface.

• Logic is the actual service provided and interface is used to communicate with the web service. Interface definition is given in WSDL.

• There are two approaches in implementing a web service and they are bottom-up and top-down.

Page 94: Optimisation and performance in Android

Bottom Up Approach

• Bottom up approach is where we first define the logic of a web service and then using that we will build the interface.

• Service code is written first and then the WSDL is created using the service code.

• There are tools available to generate the wsdl file automatically based on it.

Page 95: Optimisation and performance in Android

Top Down Approach

• Top down is the reverse of bottom up approach.

• First the service definition is written up. WSDL is created first.

• The complete service definition, message format, transport protocol, security and everything is described in WSDL.

Page 96: Optimisation and performance in Android

REST web services

• Top down is the reverse of bottom up approach.

• First the service definition is written up. WSDL is created first.

• The complete service definition, message format, transport protocol, security and everything is described in WSDL.

Page 97: Optimisation and performance in Android

How to create RESTFul webservice in Java?

• RESTful webservice in Java and in the next post will be discussing how to consume RESTful webservice we are about to create in Android application.

Page 98: Optimisation and performance in Android

How to create RESTFul webservice in Java?

Page 99: Optimisation and performance in Android

How to create RESTFul webservice in Java?

• RESTful webservice in Java and in the next post will be discussing how to consume RESTful webservice we are about to create in Android application.

Page 100: Optimisation and performance in Android

Jersey – RESTful Webservice

• use Jersey framework to design RESTful webservice.

Reference: http://www.vogella.com/tutorials/REST/article.html#installation_jersey

Page 101: Optimisation and performance in Android

Jersey – RESTful Webservice

• Goto https://jersey.java.net/download.html and download Jersey 1.18 ZIP bundle as shown below:

Page 102: Optimisation and performance in Android

Jersey – RESTful Webservice

• Unzip the bundle, you can see list of Jars under lib folder as shown below:

Page 103: Optimisation and performance in Android

Jersey – RESTful Webservice

• Create Dynamic web project in Eclipse as shown below:Choose File>>New>>Dynamic Web Project

Page 104: Optimisation and performance in Android

Jersey – RESTful Webservice

• Enter project name as ‘useraccount’ and Click Finish

Page 105: Optimisation and performance in Android

Jersey – RESTful Webservice

• Add unzipped Jersey library JARs to WEB-INF/lib folder

Page 106: Optimisation and performance in Android

Jersey – RESTful Webservice• Register Jersey as Servlet dispatcher by adding below code into web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>useraccount</display-name> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.prgguru.jersey</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping></web-app>

Page 107: Optimisation and performance in Android

Jersey – RESTful Webservice

• Create a package called ‘com.prgguru.jersey’ under src folder

Page 108: Optimisation and performance in Android

Jersey – RESTful Webservice

• Create a class called ‘Constants.java’ under the package ‘com.example.jersey’ and add below code to it:

//Change these parameters according to your DBpublic class Constants { public static String dbClass = "com.mysql.jdbc.Driver"; private static String dbName= "users"; public static String dbUrl = "jdbc:mysql://localhost:3306/"+dbName; public static String dbUser = "root"; public static String dbPwd = "password";}

Page 109: Optimisation and performance in Android

Jersey – RESTful Webservice

• Create a class called ‘DBConnection.java’ under the package ‘com.prgguru.jersey’ and add below code to it:

Page 110: Optimisation and performance in Android

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement; public class DBConnection { /** * Method to create DB Connection * * @return * @throws Exception */ @SuppressWarnings("finally") public static Connection createConnection() throws Exception { Connection con = null; try { Class.forName(Constants.dbClass); con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); } catch (Exception e) { throw e; } finally { return con; } }

Page 111: Optimisation and performance in Android

public static boolean checkLogin(String uname, String pwd) throws Exception { boolean isUserAvailable = false; Connection dbConn = null; try { try { dbConn = DBConnection.createConnection(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Statement stmt = dbConn.createStatement(); String query = "SELECT * FROM user WHERE username = '" + uname + "' AND password=" + "'" + pwd + "'"; //System.out.println(query); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { //System.out.println(rs.getString(1) + rs.getString(2) + rs.getString(3)); isUserAvailable = true; }

Page 112: Optimisation and performance in Android

} catch (SQLException sqle) { throw sqle; } catch (Exception e) { // TODO Auto-generated catch block if (dbConn != null) { dbConn.close(); } throw e; } finally { if (dbConn != null) { dbConn.close(); } } return isUserAvailable; }

Page 113: Optimisation and performance in Android

public static boolean insertUser(String name, String uname, String pwd) throws SQLException, Exception { boolean insertStatus = false; Connection dbConn = null; try { try { dbConn = DBConnection.createConnection(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Statement stmt = dbConn.createStatement(); String query = "INSERT into user(name, username, password) values('"+name+ "',"+"'" + uname + "','" + pwd + "')"; //System.out.println(query); int records = stmt.executeUpdate(query); //System.out.println(records); //When record is successfully inserted if (records > 0) { insertStatus = true; }

Page 114: Optimisation and performance in Android

} catch (SQLException sqle) { //sqle.printStackTrace(); throw sqle; } catch (Exception e) { //e.printStackTrace(); // TODO Auto-generated catch block if (dbConn != null) { dbConn.close(); } throw e; } finally { if (dbConn != null) { dbConn.close(); } } return insertStatus; }}

Page 115: Optimisation and performance in Android

Create a class called ‘Utility.java’ under the package ‘com.prgguru.jersey’ and add below code to it:Utility.javaimport org.codehaus.jettison.json.JSONException;import org.codehaus.jettison.json.JSONObject; public class Utitlity { /** * Null check Method * * @param txt * @return */ public static boolean isNotNull(String txt) { // System.out.println("Inside isNotNull"); return txt != null && txt.trim().length() >= 0 ? true : false; } /** * Method to construct JSON * * @param tag * @param status * @return */

Page 116: Optimisation and performance in Android

public static String constructJSON(String tag, boolean status) { JSONObject obj = new JSONObject(); try { obj.put("tag", tag); obj.put("status", new Boolean(status)); } catch (JSONException e) { // TODO Auto-generated catch block } return obj.toString(); } /** * Method to construct JSON with Error Msg * * @param tag * @param status * @param err_msg * @return */

Page 117: Optimisation and performance in Android

public static String constructJSON(String tag, boolean status,String err_msg) { JSONObject obj = new JSONObject(); try { obj.put("tag", tag); obj.put("status", new Boolean(status)); obj.put("error_msg", err_msg); } catch (JSONException e) { // TODO Auto-generated catch block } return obj.toString(); } }

Page 118: Optimisation and performance in Android

Jersey – RESTful Webservice

• Create a class called Register.java under the package ‘com.example.jersey’ and add below code to it.

Register.java

Page 119: Optimisation and performance in Android

Register.javaimport java.sql.SQLException; import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;import javax.ws.rs.core.MediaType;//Path: http://localhost/<appln-folder-name>/register@Path("/register")public class Register { // HTTP Get Method @GET // Path: http://localhost/<appln-folder-name>/register/doregister @Path("/doregister") // Produces JSON as response @Produces(MediaType.APPLICATION_JSON) // Query parameters are parameters: http://localhost/<appln-folder-name>/register/doregister?name=pqrs&username=abc&password=xyz

Page 120: Optimisation and performance in Android

public String doLogin(@QueryParam("name") String name, @QueryParam("username") String uname, @QueryParam("password") String pwd){ String response = ""; //System.out.println("Inside doLogin "+uname+" "+pwd); int retCode = registerUser(name, uname, pwd); if(retCode == 0){ response = Utitlity.constructJSON("register",true); }else if(retCode == 1){ response = Utitlity.constructJSON("register",false, "You are already registered"); }else if(retCode == 2){ response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password"); }else if(retCode == 3){ response = Utitlity.constructJSON("register",false, "Error occured"); } return response; }

Page 121: Optimisation and performance in Android

private int registerUser(String name, String uname, String pwd){ System.out.println("Inside checkCredentials"); int result = 3; if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){ try { if(DBConnection.insertUser(name, uname, pwd)){ System.out.println("RegisterUSer if"); result = 0; } } catch(SQLException sqle){ System.out.println("RegisterUSer catch sqle"); //When Primary key violation occurs that means user is already registered if(sqle.getErrorCode() == 1062){ result = 1; } //When special characters are used in name,username or password else if(sqle.getErrorCode() == 1064){ System.out.println(sqle.getErrorCode()); result = 2; } }

Page 122: Optimisation and performance in Android

catch (Exception e) { // TODO Auto-generated catch block System.out.println("Inside checkCredentials catch e "); result = 3; } }else{ System.out.println("Inside checkCredentials else"); result = 3; } return result; } }

Page 123: Optimisation and performance in Android

Create a class called ‘Login.java’ under the package ‘com.example.jersey’ and add below code to it.

Login.javaimport javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;import javax.ws.rs.core.MediaType;//Path: http://localhost/<appln-folder-name>/login@Path("/login")public class Login { // HTTP Get Method @GET // Path: http://localhost/<appln-folder-name>/login/dologin @Path("/dologin") // Produces JSON as response @Produces(MediaType.APPLICATION_JSON) // Query parameters are parameters: http://localhost/<appln-folder-name>/login/dologin?username=abc&password=xyz

Page 124: Optimisation and performance in Android

public String doLogin(@QueryParam("username") String uname, @QueryParam("password") String pwd){ String response = ""; if(checkCredentials(uname, pwd)){ response = Utitlity.constructJSON("login",true); }else{ response = Utitlity.constructJSON("login", false, "Incorrect Email or Password"); } return response; }

Page 125: Optimisation and performance in Android

private boolean checkCredentials(String uname, String pwd){ System.out.println("Inside checkCredentials"); boolean result = false; if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){ try { result = DBConnection.checkLogin(uname, pwd); //System.out.println("Inside checkCredentials try "+result); } catch (Exception e) { // TODO Auto-generated catch block //System.out.println("Inside checkCredentials catch"); result = false; } }else{ //System.out.println("Inside checkCredentials else"); result = false; } return result; } }

Page 126: Optimisation and performance in Android

• Deploy the web application:Right click on the project ‘useraccount’ >> Run As >> Run on Server

Page 127: Optimisation and performance in Android

• http://opensignal.com/blog/2013/07/30/40-developer-tips-for-android-optimization/

• http://blog.hsc.com/android/technology-trends/android-memory-optimization/

• https://www.google.co.in/search?q=optimization+in+android&rlz=1C1CHMO_enIN570IN570&oq=optimization+in+android&aqs=chrome..69i57.8019j0j7&sourceid=chrome&es_sm=122&ie=UTF-8#q=what+is+optimization+