Optimisation and performance in Android

Preview:

Citation preview

Optimisation and Performance

Rakesh Kumar JhaM. Tech, MBA

Delivery Manager

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

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.

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.

What is Optimization

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

Optimization in Android

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

– Processor

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

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.

Dirty RAM

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

Dirty RAM

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

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.

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.’

Memory Optimization, Best Practices For Android

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

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.

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.

Memory Optimization, Best Practices For Android

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

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

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

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.

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>

Memory Optimization, Best Practices For Android

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

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.

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

Memory Optimization, Best Practices For Android

15. GZip your SVG files.

Makes them smaller and they parse quicker.

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.

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.

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>

Memory Optimization, Best Practices For Android

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

Targeting speed

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.

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.

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.

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

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

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.

Memory Optimization, Best Practices For Android

25. Use RelativeLayout whenever you can.

Memory Optimization, Best Practices For Android

26. Use external profilers as well as DDMS

Memory Optimization, Best Practices For Android

27. Use AsyncTasks

Targeting low file size

Memory Optimization, Best Practices For Android

28. Some Android devices have a 100mb limit

Memory Optimization, Best Practices For Android

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

Memory Optimization, Best Practices For Android

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

Targeting bugs

Memory Optimization, Best Practices For Android

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

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.

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

Networking

Background Data and Data Transfer

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

Checking Network Connection

Checking Network Connection

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

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.

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:

Checking Network Connection

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

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.

Checking Network Connection

NetworkInfo[] info = check.getAllNetworkInfo();

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(); }}

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

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.

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:

Performing Network Operations

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

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.

Performing Network Operations

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

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";}

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";}

PHP - MYSQL

• 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.

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";}?>

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";}?>

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";}?>

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);?>

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));

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()));

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();

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()));

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.

Type of web services

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.

Components of a Web Service

wsdl

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.

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.

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.

Type of web services

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

</definitions>

UDDI

• 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.

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.

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.

Binding

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

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

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.

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.

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.

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.

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.

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.

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.

How to create RESTFul webservice in Java?

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.

Jersey – RESTful Webservice

• use Jersey framework to design RESTful webservice.

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

Jersey – RESTful Webservice

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

Jersey – RESTful Webservice

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

Jersey – RESTful Webservice

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

Jersey – RESTful Webservice

• Enter project name as ‘useraccount’ and Click Finish

Jersey – RESTful Webservice

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

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>

Jersey – RESTful Webservice

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

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";}

Jersey – RESTful Webservice

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

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; } }

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; }

} 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; }

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; }

} 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; }}

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 */

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 */

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(); } }

Jersey – RESTful Webservice

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

Register.java

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

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; }

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; } }

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; } }

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

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; }

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; } }

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

• 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+

Recommended