You are on page 1of 126

https://www.youtube.com/watch?

v=dF0m_PG111g - very
good for round button cration in Android studio..

How exactly does the android:onClick XML attribute differ


from setOnClickListener?
No that is not possible via code. Android just implements the OnClickListener for you when you
define the android:onClick="someMethod" attribute.
Those two code snippets are totally the same but just implemented in two different ways.

Code Implementation
Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myFancyMethod(v);
}
});

// some more code

public void myFancyMethod(View v) {


// does something very interesting
}
Above is a code implementation of an OnClickListener. And now the XML implementation.
XML Implementation
<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myFancyMethod" />
<!-- even more layout elements -->
Now in the background Android does nothing else than the Java code calling your method on a
click event.

Note that with the XML above, Android will look for the onClick method myFancyMethod() only in
the current Activity. This is important to remember if you are using fragments, since even if you
add the XML above using a fragment, Android will not look for the onClick method in
the .java file of the fragment used to add the XML.
Another important thing I noticed. You mentioned you don't prefer anonymous methods. You
meant to say you don't like anonymous classes.

-------x-------------------x---------------x-------

1
how to read value from string.xml in android?
String mess = getResources().getString(R.string.mess_1);

‘’
Media Player Looping : Android
down vote accepted mMediaPlayer.setLooping(true);

http://labs.udacity.com/android-visualizer/ - good website for


showing layout xml to android view

Vibrate onclick
is there a way to get a button to vibrate but only when the if condition is verified?
Yes. It looks like you have 95% of the code there already. Where did you get stuck?

You already have a Vibrator Object and a conditional. All you need to do now is
call vibrate() like so:
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

if(l2 >= l1) {


insertactone.setBackgroundColor(Color.RED);
vibe.vibrate(100);
}
Don't forget that you need to request android.permission.VIBRATE in your manifest.

Try:

import android.os.Vibrator;
...
Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
Note:
Don't forget to include permission in AndroidManifest.xml file:

<uses-permission android:name="android.permission.VIBRATE"/>

How to provide shadow to Button

2
Use this approach to get your desired look.
button_selector.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item android:right="5dp" android:top="5dp">
<shape>
<corners android:radius="3dp" />
<solid android:color="#D6D6D6" />
</shape>
</item>
<item android:bottom="2dp" android:left="2dp">
<shape>
<gradient android:angle="270"
android:endColor="#E2E2E2" android:startColor="#BABABA" />
<stroke android:width="1dp" android:color="#BABABA" />
<corners android:radius="4dp" />
<padding android:bottom="10dp" android:left="10dp"
android:right="10dp" android:top="10dp" />
</shape>
</item>
</layer-list>
</item>

</selector>
And in your xml layout:
<Button
android:background="@drawable/button_selector"
...
..
/>

mipmap vs drawable folders [duplicate]


The mipmap folders are for placing your app/launcher icons (which are shown on the
homescreen) in only. Any other drawable assets you use should be placed in the relevant
drawable folders as before.

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because
they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger
than they were intended. Because of this, they use the next size up.

3
how to arrange xml code in android studio

1. Choose File > Settings > Code Style > XML > Set from > Predefined Style > Android.
2. Set File > Settings > Editor > Formatting > Show "Reformat Code" dialog.
3. Run formatting on a XML file ( CTRL+ALT+L by default)
4. You will see a popup window, set the Rearrange entries flag.

https://android-arsenal.com/tag/13 - good website for Android

????????????????????????????????????????????????????????????????????????????????

Push Notification using Google Firebase – Steps to create it.

Step1:

Goto

http://console.firebase.google.com
4
Step2:

In the above page click the CREATE NEW PROJECT

In the above screen give the Project Name and Country Region then press the Create Project

Then we get the following screen

5
In the above screen choose the ‘Add Firebase to your Android app’ button

It shows the following screen

In the above screen give the package name (ex. com.ramana.sriramanasramamlivevideo )

6
of your android program then press ‘ADD APP’, then it gives a Json file named
google-services.json. Put this file to your Android app Module root directory

7
In the above screen press the CONTINUE button.

After press the ‘CONTINUE’ button it gives the following screen. Based on the
screen. It gives some dependency values. Put these dependency values to your
android program’s gradle build file and sync. The gradle build file.

8
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'

Select the CLOUD MESSAGING in the above screen

9
This screen gives the server key, copy the server key and put the notification php file.

Server key
AIzaSyDYXDCCj5n7jQ558Lqu63qGWrKimhjtxzY

Sender ID
1062771646447

The above server key and Sender ID created from shonasaila@gmail.com account.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Server key
AIzaSyBz0hq5qRM1S73JOgBF6bs-aN_UhKEnxgk

Sender ID
271373187896

The above server key and Sender ID created from ashram@gururamana.org account.

10
For push notification in Sri Ramanasramam Live Video Android app

????????????????????????????????????????????????????????????????????????????????
I

To insert more than one record at once, we can do this, with each set of field values
separated by a comma:

INSERT INTO example


(example_id, name, value, other_value)
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');

You could also omit the fieldnames like this:

INSERT INTO example


VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');

????????????????????????????????????????????????????????????????????????????????

HashMap - getting First Key value


below are the values contain in the HashMap

statusName {Active=33, Renewals Completed=3, Application=15}


java code to getting the first Key (i.e Active)

Object myKey = statusName.keySet().toArray()[0];


how can we collect the first Key "Value" (i.e 33), i want to store the Both "Key" and "Value" in
separate variable

You can try in this way

11
Map<String,String> map=new HashMap<>();
Map.Entry<String,String> entry=map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
But you need to know HashMap not grantee the insertion order. You can use LinkedHashMap for
keep order.
Eg:

Map<String,String> map=new LinkedHashMap<>();


map.put("Active","33");
map.put("Renewals Completed","3");
map.put("Application","15");
Map.Entry<String,String> entry=map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
System.out.println(key);
System.out.println(value);
Out put:

Active
33

Converting 'ArrayList<String> to 'String[]' in Java


List<String> list = ..;
String[] array = list.toArray(new String[0]);
For example:

List<String> list = new ArrayList<String>();


//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
The toArray() method without passing any argument returns Object[]. So you have to pass an
array as an argument, which will be filled with the data from the list, and returned. You can pass
an empty array as well, but you can also pass an array with the desired size.
Important update: Originally the code above used new String[list.size()]. However, this
blogpost reveals that due to JVM optimizations, using new String[0] is better now.

????????????????????????????????????????????????????????????????????????????????

How to call another activity after certain time limit

12
You could use a Timer and add a TimerTask that is executed after a specific delay.
Here is a more or less completed example:

Timer timer = new Timer();


timer.schedule(new TimerTask() {

public void run() {

//here you can start your Activity B.

}, 10000);
The example above executes a new TimerTask in 10 seconds. Inside the TimerTask you can
override the run method. In the run method you can start your new activity. The run method is
executed after the delay. In this example it is 10'000 milliseconds.

Aligning Left/Center/Right LinearLayout - Android


You have to use a RelativeLayout.

Try something like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:id="@+id/previousButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="New Button" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:layout_alignParentBottom="true"
android:id="@+id/nextButton"
android:layout_toRightOf="@id/previousButton"
/>

</RelativeLayout>

13
????????????????????????????????????????????????????????????????????????????????

Android Studio rendering problems


Change your android version on your designer preview into your current version depend on your
Manifest. rendering problem caused your designer preview used higher API level than your
current android API level.

Adjust with your current API Level. If the API level isn't in the list, you'll need to install it via the
SDK Mangager.

14
????????????????????????????????????????????????????????????????????????????????

Configuration examples
To help you target some of your designs for different types of devices, here are some numbers for typical
screen widths:

 320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).

 480dp: a tweener tablet like the Streak (480x800 mdpi).

 600dp: a 7” tablet (600x1024 mdpi).

 720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

Using the size qualifiers from table 2, your application can switch between your different layout resources
for handsets and tablets using any number you want for width and/or height. For example, if 600dp is the
smallest available width supported by your tablet layout, you can provide these two sets of layouts:

res/layout/main_activity.xml # For handsets


res/layout-sw600dp/main_activity.xml # For tablets

In this case, the smallest width of the available screen space must be 600dp in order for the tablet layout
to be applied.

For other cases in which you want to further customize your UI to differentiate between sizes such as 7”
and 10” tablets, you can define additional smallest width layouts:

res/layout/main_activity.xml # For handsets (smaller than 600dp available


width)
res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger)

Notice that the previous two sets of example resources use the "smallest width" qualifier, sw<N>dp, which
specifies the smallest of the screen's two sides, regardless of the device's current orientation. Thus,
usingsw<N>dp is a simple way to specify the overall screen size available for your layout by ignoring the
screen's orientation.

However, in some cases, what might be important for your layout is exactly how much width or height
iscurrently available. For example, if you have a two-pane layout with two fragments side by side, you
might want to use it whenever the screen provides at least 600dp of width, whether the device is in
landscape or portrait orientation. In this case, your resources might look like this:

15
res/layout/main_activity.xml # For handsets (smaller than 600dp available width)
res/layout-w600dp/main_activity.xml # Multi-pane (any screen with 600dp available width
or more)

Notice that the second set is using the "available width" qualifier, w<N>dp. This way, one device may
actually use both layouts, depending on the orientation of the screen (if the available width is at least
600dp in one orientation and less than 600dp in the other orientation).

If the available height is a concern for you, then you can do the same using the h<N>dp qualifier. Or, even
combine the w<N>dp and h<N>dp qualifiers if you need to be really specific.

????????????????????????????????????????????????????????????????????????????????

Android Parsing – Retrieve From MySQL


Database
Creating PHP Script – Android JSON Parsing

 First we will create a php script that will fetch the data from the database.

1 <?php

2 define('HOST','mysql.hostinger.in');

3 define('USER','u813815354_user');

4 define('PASS','bhaq2010');

5 define('DB','u813815354_db');

7 $con = mysqli_connect(HOST,USER,PASS,DB);

9 $sql = "select * from Persons";

10

16
11 $res = mysqli_query($con,$sql);

 Now we will create an array.

1 $res = mysqli_query($con,$sql);

 Push the fetched data in the array as key=>value format (associative array).
 Key would be the column name.

1 while($row = mysqli_fetch_array($res)){

2 array_push($result,

3 array('id'=>$row[0],

4 'name'=>$row[1],

5 'address'=>$row[2]

6 ));

7}

 Print the array in JSON format with the function json_encode().


 Close the database.

1 echo json_encode(array("result"=>$result));

17
3 mysqli_close($con);

5 ?>

The final PHP Script

1 <?php

2 define('HOST','mysql.hostinger.in');

3 define('USER','u813815354_user');

4 define('PASS','bhaq2010');

5 define('DB','u813815354_db');

7 $con = mysqli_connect(HOST,USER,PASS,DB);

9 $sql = "select * from Persons";

10

11 $res = mysqli_query($con,$sql);

12

13 $result = array();

14

15 while($row = mysqli_fetch_array($res)){

16 array_push($result,

17 array('id'=>$row[0],

18 'name'=>$row[1],

19 'address'=>$row[2]

20 ));

21 }

22

23 echo json_encode(array("result"=>$result));

18
24

25 mysqli_close($con);

26

27 ?>

You can copy the above code. Save the code with some name (Extension must be .php). Upload the
file to your server and try executing it.

Our JSON is now ready at this URL => http://www.simplifiedcoding.16mb.com/get-data.php

The above link will give JSON String. Itt has an array of objects name result. In result we have
objects containing all the value. Each object has three values id, name and address.

Creating Android App for Parsing JSON

 Open Android Studion => Create a New Project


 I named my project as FetchJSON
 Go to your activity_main.xml
 Change the layout to LinearLayout and vertical orientation
 Create a ListView for displaying the details that will be fetched

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

2 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

3 android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

4 android:paddingRight="@dimen/activity_horizontal_margin"

5 android:paddingTop="@dimen/activity_vertical_margin"

6 android:orientation="vertical"

7 android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

19
10 <ListView

11 android:layout_width="match_parent"

12 android:layout_height="wrap_content"

13 android:id="@+id/listView" />

14 </LinearLayout>

 Create a new layout for our list items.


 Right click on Layout -> New -> Layout Resource File
 Name it list_item.xml
 Copy the following code and paste in the layout file list_item.xml

1 <?xml version="1.0" encoding="utf-8"?>

2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

3 android:layout_width="fill_parent"

4 android:layout_height="wrap_content"

5 android:orientation="vertical"

6 android:padding="10dp"

7 android:paddingLeft="10dp"

8 android:paddingRight="10dp" >

10

11 <TextView

12 android:id="@+id/id"

13 android:layout_width="fill_parent"

14 android:layout_height="wrap_content"

15 android:paddingBottom="2dip"

16 android:paddingTop="6dip"

17 android:textStyle="bold" />

20
18

19

20 <TextView

21 android:id="@+id/name"

22 android:layout_width="fill_parent"

23 android:layout_height="wrap_content"

24 android:paddingBottom="2dip"

25 android:textStyle="bold"/>

26

27

28 <TextView

29 android:id="@+id/address"

30 android:layout_width="wrap_content"

31 android:layout_height="wrap_content"

32 android:gravity="left"

33 android:textStyle="bold" />

34

35 </LinearLayout>

 Come to the MainActivity.java

1 public class MainActivity extends ActionBarActivity {

3 String myJSON;

5 private static final String TAG_RESULTS="result";

6 private static final String TAG_ID = "id";

7 private static final String TAG_NAME = "name";

21
8 private static final String TAG_ADD ="address";

10 JSONArray peoples = null;

11

12 ArrayList<HashMap<String, String>> personList;

13

14 ListView list;

 myJSON is the string where we will store the JSON string from server.
 We have declared some final String TAGS for getting the values from JSON String and
 A JSONArray peoples for storing the JSON Array and
 An array list for creating a list from JSON and
 A ListView for displaying the list in the Activity
 Come to onCreate method

1 @Override

2 protected void onCreate(Bundle savedInstanceState) {

3 super.onCreate(savedInstanceState);

4 setContentView(R.layout.activity_main);

5 list = (ListView) findViewById(R.id.listView);

6 personList = new ArrayList<HashMap<String,String>>();

7 getData();

8 }

 We have initialized our list object and personList.


 Finally we called the getData() method which will fetch the JSON string from the server.

22
1 public void getData(){

2 class GetDataJSON extends AsyncTask<String, Void, String>{

4 @Override

5 protected String doInBackground(String... params) {

6 DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

7 HttpPost httppost = new HttpPost("http://simplifiedcoding.16mb.com/get-data.php");

9 // Depends on your web service

10 httppost.setHeader("Content-type", "application/json");

11

12 InputStream inputStream = null;

13 String result = null;

14 try {

15 HttpResponse response = httpclient.execute(httppost);

16 HttpEntity entity = response.getEntity();

17

18 inputStream = entity.getContent();

19 // json is UTF-8 by default

20 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

21 StringBuilder sb = new StringBuilder();

22

23 String line = null;

24 while ((line = reader.readLine()) != null)

25 {

26 sb.append(line + "\n");

27 }

23
28 result = sb.toString();

29 } catch (Exception e) {

30 // Oops

31 }

32 finally {

33 try{if(inputStream != null)inputStream.close();}catch(Exception squish){}

34 }

35 return result;

36 }

37

38 @Override

39 protected void onPostExecute(String result){

40 myJSON=result;

41 showList();

42 }

43 }

44 GetDataJSON g = new GetDataJSON();

45 g.execute();

46 }

 getData is executing an AsyncTask. In the AyncTask class the doInBackgroundMethod will return the
JSON String.
 In onPostExecute method we will store that String to myJSON. Then we will call a new showList()
method to show the JSON string in the ListView after parsing.

1 protected void showList(){

2 try {

3 JSONObject jsonObj = new JSONObject(myJSON);

24
4 peoples = jsonObj.getJSONArray(TAG_RESULTS);

6 for(int i=0;i<peoples.length();i++){

7 JSONObject c = peoples.getJSONObject(i);

8 String id = c.getString(TAG_ID);

9 String name = c.getString(TAG_NAME);

10 String address = c.getString(TAG_ADD);

11

12 HashMap<String,String> persons = new HashMap<String,String>();

13

14 persons.put(TAG_ID,id);

15 persons.put(TAG_NAME,name);

16 persons.put(TAG_ADD,address);

17

18 personList.add(persons);

19 }

20

21 ListAdapter adapter = new SimpleAdapter(

22 MainActivity.this, personList, R.layout.list_item,

23 new String[]{TAG_ID,TAG_NAME,TAG_ADD},

24 new int[]{R.id.id, R.id.name, R.id.address}

25 );

26

27 list.setAdapter(adapter);

28

29 } catch (JSONException e) {

30 e.printStackTrace();

31 }

32

33 }

25
 Our final complete MainActivity.java is

1 package net.simplifiedcoding.fetchjson;

3 import android.os.AsyncTask;

4 import android.support.v7.app.ActionBarActivity;

5 import android.os.Bundle;

6 import android.view.Menu;

7 import android.view.MenuItem;

8 import android.widget.ListAdapter;

9 import android.widget.ListView;

10 import android.widget.SimpleAdapter;

11 import android.widget.TextView;

12

13 import org.apache.http.HttpEntity;

14 import org.apache.http.HttpResponse;

15 import org.apache.http.client.methods.HttpPost;

16 import org.apache.http.impl.client.DefaultHttpClient;

17 import org.apache.http.params.BasicHttpParams;

18 import org.json.JSONArray;

19 import org.json.JSONException;

20 import org.json.JSONObject;

21

22 import java.io.BufferedReader;

23 import java.io.InputStream;

24 import java.io.InputStreamReader;

25 import java.util.ArrayList;

26 import java.util.HashMap;

26
27

28

29 public class MainActivity extends ActionBarActivity {

30

31 String myJSON;

32

33 private static final String TAG_RESULTS="result";

34 private static final String TAG_ID = "id";

35 private static final String TAG_NAME = "name";

36 private static final String TAG_ADD ="address";

37

38 JSONArray peoples = null;

39

40 ArrayList<HashMap<String, String>> personList;

41

42 ListView list;

43

44 @Override

45 protected void onCreate(Bundle savedInstanceState) {

46 super.onCreate(savedInstanceState);

47 setContentView(R.layout.activity_main);

48 list = (ListView) findViewById(R.id.listView);

49 personList = new ArrayList<HashMap<String,String>>();

50 getData();

51 }

52

53

54 protected void showList(){

55 try {

56 JSONObject jsonObj = new JSONObject(myJSON);

57 peoples = jsonObj.getJSONArray(TAG_RESULTS);

27
58

59 for(int i=0;i<peoples.length();i++){

60 JSONObject c = peoples.getJSONObject(i);

61 String id = c.getString(TAG_ID);

62 String name = c.getString(TAG_NAME);

63 String address = c.getString(TAG_ADD);

64

65 HashMap<String,String> persons = new HashMap<String,String>();

66

67 persons.put(TAG_ID,id);

68 persons.put(TAG_NAME,name);

69 persons.put(TAG_ADD,address);

70

71 personList.add(persons);

72 }

73

74 ListAdapter adapter = new SimpleAdapter(

75 MainActivity.this, personList, R.layout.list_item,

76 new String[]{TAG_ID,TAG_NAME,TAG_ADD},

77 new int[]{R.id.id, R.id.name, R.id.address}

78 );

79

80 list.setAdapter(adapter);

81

82 } catch (JSONException e) {

83 e.printStackTrace();

84 }

85

86 }

87

88 public void getData(){

28
89 class GetDataJSON extends AsyncTask<String, Void, String>{

90

91 @Override

92 protected String doInBackground(String... params) {

93 DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());

94 HttpPost httppost = new HttpPost("http://simplifiedcoding.16mb.com/get-data.php");

95

96 // Depends on your web service

97 httppost.setHeader("Content-type", "application/json");

98

99 InputStream inputStream = null;

100 String result = null;

101 try {

102 HttpResponse response = httpclient.execute(httppost);

103 HttpEntity entity = response.getEntity();

104

105 inputStream = entity.getContent();

106 // json is UTF-8 by default

107 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);

108 StringBuilder sb = new StringBuilder();

109

110 String line = null;

111 while ((line = reader.readLine()) != null)

112 {

113 sb.append(line + "\n");

114 }

115 result = sb.toString();

116 } catch (Exception e) {

117 // Oops

118 }

119 finally {

29
120 try{if(inputStream != null)inputStream.close();}catch(Exception squish){}

121 }

122 return result;

123 }

124

125 @Override

126 protected void onPostExecute(String result){

127 myJSON=result;

128 showList();

129 }

130 }

131 GetDataJSON g = new GetDataJSON();

132 g.execute();

133 }

134

135 @Override

136 public boolean onCreateOptionsMenu(Menu menu) {

137 // Inflate the menu; this adds items to the action bar if it is present.

138 getMenuInflater().inflate(R.menu.menu_main, menu);

139 return true;

140 }

141

142 @Override

143 public boolean onOptionsItemSelected(MenuItem item) {

144 // Handle action bar item clicks here. The action bar will

145 // automatically handle clicks on the Home/Up button, so long

146 // as you specify a parent activity in AndroidManifest.xml.

147 int id = item.getItemId();

148

149 //noinspection SimplifiableIfStatement

150 if (id == R.id.action_settings) {

30
151 return true;

152 }

153

154 return super.onOptionsItemSelected(item);

155 }

156 }

 Finally just add the internet permission to your manifest.xml

1 <?xml version="1.0" encoding="utf-8"?>

2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"

3 package="net.simplifiedcoding.fetchjson" >

5 <!-- Internet Permission -->

6 <uses-permission android:name="android.permission.INTERNET" />

8 <application

9 android:allowBackup="true"

10 android:icon="@mipmap/ic_launcher"

11 android:label="@string/app_name"

12 android:theme="@style/AppTheme" >

13 <activity

14 android:name=".MainActivity"

15 android:label="@string/app_name" >

16 <intent-filter>

17 <action android:name="android.intent.action.MAIN" />

18

19 <category android:name="android.intent.category.LAUNCHER" />

31
20 </intent-filter>

21 </activity>

22 </application>

23

24 </manifest>

 Execute your application, you will see the following output.

In the Above Jason tutorial – Some classes are deprecated

Following code helpful to Jason parsing with Android studio


package com.ramana.tamilparamana;

32
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.support.v4.util.SimpleArrayMap;
import android.support.v4.util.ArrayMap;

public class JasonEvent extends AppCompatActivity {

String myJSON;
private static final String TAG_RESULTS = "res";
private static final String TAG_ID = "event";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> eventList;
TextView view, t1, t2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jason_event);
Typeface font1 = Typeface.createFromAsset(getAssets(), "TAU_CHON.TTF");
Typeface font = Typeface.createFromAsset(getAssets(), "FutuLt_0.ttf");

t1 = (TextView) findViewById(R.id.headertxt);
t1.setTypeface(font1);
view = (TextView) findViewById(R.id.jasonTxt);
t2 = (TextView) findViewById(R.id.txtV3);
view.setTypeface(font);

33
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
view.startAnimation(animation1);

//Animation animation2 = AnimationUtils.loadAnimation(getApplicationContext(),


R.anim.move);
//view.startAnimation(animation2);

t2.setTypeface(font);
eventList = new ArrayList<HashMap<String, String>>();
getData();
//view.setText(xx);

public void getData() {


class GetDataJSON extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {
//DefaultHttpClient httpclient = new DefaultHttpClient(new
BasicHttpParams());
//HttpPost httppost = new HttpPost("http://simplifiedcoding.16mb.com/get-
data.php");

HttpURLConnection connection = null;


String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://www.sriramana.org/tamilparayana/cell/get-
data.php");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.i("XXXXXXXXXX", line.toString());

}
result = buffer.toString();

} catch (MalformedURLException ee) {


ee.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

return result;
}

34
@Override
protected void onPostExecute(String result) {
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}

protected void showList(){


try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);

for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
//String name = c.getString(TAG_NAME);
//String address = c.getString(TAG_ADD);

HashMap<String,String> persons = new HashMap<String,String>();

persons.put(TAG_ID,id);
//persons.put(TAG_NAME,name);
//persons.put(TAG_ADD,address);
eventList.add(persons);
}

for (HashMap<String, String> map : eventList)


for (Map.Entry<String, String> entry : map.entrySet()) {
view.append(entry.getValue());
view.append("\n\n");
}

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

}
public void goBack(View view){
finish();

}
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

https://www.youtube.com/watch?v=Gyaay7OTy-w – very good tutorial for JASON parsing in Android Studio

Code name Version API level

35
Code name Version API level

Marshmallow 6.0 API level 23

Lollipop 5.1 API level 22

Lollipop 5.0 API level 21

KitKat 4.4 - 4.4.4 API level 19

Jelly Bean 4.3.x API level 18

Jelly Bean 4.2.x API level 17

Jelly Bean 4.1.x API level 16

Ice Cream Sandwich 4.0.3 - 4.0.4 API level 15, NDK 8

Ice Cream Sandwich 4.0.1 - 4.0.2 API level 14, NDK 7

Honeycomb 3.2.x API level 13

Honeycomb 3.1 API level 12, NDK 6

Honeycomb 3.0 API level 11

Gingerbread 2.3.3 - 2.3.7 API level 10

Gingerbread 2.3 - 2.3.2 API level 9, NDK 5

Froyo 2.2.x API level 8, NDK 4

36
Code name Version API level

Eclair 2.1 API level 7, NDK 3

Eclair 2.0.1 API level 6

Eclair 2.0 API level 5

Donut 1.6 API level 4, NDK 2

Cupcake 1.5 API level 3, NDK 1

(no code name) 1.1 API level 2

(no code name) 1.0 API level 1

Let's go in reverse order:

 Log.e: This is for when bad stuff happens. Use this tag in places like inside a catch
statment. You know that an error has occurred and therefore you're logging an error.
 Log.w: Use this when you suspect something shady is going on. You may not be
completely in full on error mode, but maybe you recovered from some unexpected behavior.
Basically, use this to log stuff you didn't expect to happen but isn't necessarily an error. Kind
of like a "hey, this happened, and it's weird, we should look into it."
 Log.i: Use this to post useful information to the log. For example: that you have
successfully connected to a server. Basically use it to report successes.
 Log.d: Use this for debugging purposes. If you want to print out a bunch of messages so
you can log the exact flow of your program, use this. If you want to keep a log of variable
values, use this.
 Log.v: Use this when you want to go absolutely nuts with your logging. If for some reason
you've decided to log every little thing in a particular part of your app, use the Log.v tag.
And as a bonus...

 Log.wtf: Use this when stuff goes absolutely, horribly, holy-crap wrong. You know those
catch blocks where you're catching errors that you never should get...yea, if you wanna log
them use Log.wtf

37
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android: Screen Densities, Sizes, Configurations, and Icon


Sizes
1. Definitions

 resolution = number of pixels available in the display, scale-independent pixel = sp


 density = how many pixels appear within a constant area of the display, dots per inch = dpi
 size = amount of physical space available for displaying an interface, screen's diagonal, inch
 density-independent pixel = virtual pixel that is independent of the screen density, dp

2. Density Classes
Class Name Density Factor Drawable Folder Comment

sp = 3/4 *
ldpi low density 120 dpi drawable-ldpi
dp

drawable-mdpi OR baseline size, example:


mdpi medium density 160 dpi sp = dp
drawable 320x480 (sp or dp)

sp = 1.5 x example: 480x800 sp =


hdpi high density 240 dpi drawable-hdpi
dp 320x533 dp

sp = 2 x
xhdpi extra high density 320 dpi drawable-xhdpi
dp

extra extra high sp = 3 x


xxhdpi 480 dpi drawable-xxhdpi
density dp

extra extra extra sp = 4 x


xxxhdpi 640 dpi drawable-xxxhdpi
high density dp

3. Icon Sizes (full / content)


Pop-up
Action Status Bar and Small and
Density Launcher Menu Tab Dialog and
Bar Notification Contextual
List View

36x36 / 24x24 / 24x24 /


ldpi 36x36 px 18x18 / 16x16 px 24x24 px 12x12 / 9x9 px
24x24 px 18x18 px 22x22 px

48x48 / 32x32 / 32x32 / 16x16 / 12x12


mdpi 48x48 px 24x24 / 22x22 px 32x32 px
32x32 px 24x24 px 28x28 px px

72x72 / 48x48 / 48x48 / 24x24 / 18x18


hdpi 72x72 px 36x36 / 33x33 px 48x48 px
48x48 px 36x36 px 42x42 px px

38
96x96 / 64x64 / 64x64 / 32x32 / 24x24
xhdpi 96x96 px 48x48 / 44x44 px 64x64 px
64x64 px 48x48 px 56x56 px px

144x144
xxhdpi (1) (1) (1) (1) (1) (1)
px

192x192
xxxhdpi (1) (1) (1) (1) (1) (1)
px

 (1) Google documentation says: "Applications should not generally worry about this density; relying
on XHIGH graphics being scaled up to it should be sufficient for almost all cases."
 Launcher icons for Android Market: 512x512 px.

4. Screen Size Classes


Class Size in dp Layout Folder Examples Comment

426x320 typical phone screen (240x320 ldpi, 320x480 mdpi,


small layout-small
dp etc.)

470x320 layout-normal OR baseline


normal typical phone screen (480x800 hdpi)
dp layout size

640x480 tweener tablet like the Streak (480x800 mdpi), 7"


large layout-large
dp tablet (600x1024 mdpi)

960x720
xlarge layout-xlarge 10" tablet (720x1280 mdpi, 800x1280 mdpi, etc.)
dp

 valid for Android 3.1 and older


 for Android 3.2 and newer see: Declaring Tablet Layouts for Android 3.2

5. Example Screen Configurations


Screen Low density Medium density High density Extra high density
Size (120), ldpi (160), mdpi (240), hdpi (320), xhdpi

small QVGA (240x320) 480x640

WVGA800
WQVGA400
(480x800)
(240x400)
normal HVGA (320x480) WVGA854 640x960
WQVGA432
(480x854)
(240x432)
600x1024

WVGA800 WVGA800 (480x800)(1)


large
(480x800)(2) WVGA854 (480x854)(1)

39
WVGA854 600x1024
(480x854)(2)

WXGA (1280x800)(3) 1536x1152 2048x1536


xlarge 1024x600 1024x768 1920x1152 2560x1536
1280x768 1920x1200 2560x1600

 (1) To emulate this configuration, specify a custom density of 160 when creating an Android Virtual
Device that uses a WVGA800 or WVGA854 skin.
 (2) To emulate this configuration, specify a custom density of 120 when creating an Android Virtual
Device that uses a WVGA800 or WVGA854 skin.
 (3) This skin is available with the Android 3.0 platform.

6. Screen Orientation
Orientation Name Layout Folder, Example

port portrait layout-port-large

land landscape layout-land-normal OR layout-land

7. Best Practices

1. Use wrap_content, match_parent, or dp units when specifying dimensions in an XML layout file.
o except for defining text sizes: sp (scaling depends on user setting)
o Note: fill_parent is deprecated since API level 8.
2. Do not use hard coded pixel values in your application code.
3. Do not use AbsoluteLayout.
o deprecated since Android 1.5
o alternative: RelativeLayout
4. Supply alternative bitmap drawables for different screen densities.
5. Provide a launcher icon for xxhdpi, but no other icons.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Icon Reference Chart ❯ Android


Be aware that the style changes occur fairly regularly with each major release, so it's always worth
checking current guidelines!
General Guidelines

Pixel Densities

Android icons require five separate sizes for different screen pixel densities. Icons for lower resolution are created
automatically from the baseline.

mdpi (Baseline): 160 dpi 1×

40
hdpi: 240 dpi 1.5×
xhdpi: 320 dpi 2×
xxhdpi: 490 dpi 3×
xxxhdpi: 640 dpi 4×

Sizes (px) Format and Notes


naming

Launcher icons

48 × 48 (mdpi) .png Three-dimensional, front view, with a slight perspective as if viewed


72 × 72 (hdpi) from above, so that users perceive some depth.
96 × 96 (xhdpi)
144 × 144 (xxhdpi)
192 × 192 (xxxhdpi)
512 × 512 (Google
Play store)

Action bar, Dialog & Tab icons

24 × 24 area in 32 × .png These icons are used in the action bar menu. The first number is the
32 (mdpi) size of the icon area, and the second is file size.
36 × 36 area in 48 ×
48 (hdpi)
48 × 48 area in 64 ×
64 (xhdpi)
72 × 72 area in 96 ×
96 (xxhdpi)
96 × 96 area in 128 ×
128 (xxxhdpi)

Small Contextual Icons

16 × 16 (mdpi) .png Small icons are used to surface actions and/or provide status for specific
24 × 24 (hdpi) items. For example, in the Gmail app, each message has a star icon that
32 × 32 (xhdpi) marks the message as important.
48 × 48 (xxhdpi)
64 × 64 (xxxhdpi)

Notification icons

22 × 22 area in 24 × .png These are used to represent application notifications in the status bar.
24 (mdpi) They should be flat (no gradients), white and face-on perspective
33 × 33 area in 36 ×
36 (hdpi)

41
44 × 44 area in 48 ×
48 (xhdpi)
66 × 66 area in 72 ×
72 (xxhdpi)
88 × 88 area in 96 ×
96 (xxxhdpi)

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

How do I disable orientation change on Android?


Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the
question and it really isn't a good idea now. See this answer by hackbod for reasons:
http://stackoverflow.com/a/5336057/84021

Add android:configChanges="keyboardHidden|orientation" to your AndroidManifest.xml.


This tells the system what configuration changes you are going to handle yourself - in this case by
doing nothing.

42
<activity android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">

See http://developer.android.com/reference/android/R.attr.html#configChanges for more details.

However, your application can be interrupted at any time, e.g. by a phone call, so you really should
add code to save the state of your application when it is paused.

Update: As of Android 3.2, you also need to add "screenSize":

<activity
android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Prevent WebView from displaying “web page not available”


I have an app that makes extensive use of a WebView. When the user of this app does not
have Internet connection, a page saying "web page not available" and various other text
appears. Is there a way to not show this generic text in my WebView? I would like to
provide my own error handling.

First create your own error page in HTML and put it in your assets folder, Let's call it
myerrorpage.html Then with onReceivedError:

mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String
failingUrl) {
mWebView.loadUrl("file:///android_asset/myerrorpage.html");

}
});

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

How To Load a PDF in an Android WebView

String myPdfUrl = "http://example.com/awesome.pdf";


String url = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;
Log.i(TAG, "Opening PDF: " + url);
43
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android Gradle magic


2014 has been a compelling year for Android. In June of this year, Google held the I/O 2014
conference showing Android L preview and its new platform to the living room and on your
wrist, promising a higher potential of Android platform with Material Design and a vast UI
improvement. To satisfy this potential, we need to talk aboutAndroid build toolkit: Gradle.

What is Gradle?
For those who can talk in computer languages, Gradle is an automation tool that Google
chose to use for building dependencies & compiling, running unit tests before deployment,
and deploying your application. For the ordinary folks, it's a magical program that computer
wizards at Google chose to help us building nice-and-tight Android apps. It supports beyond
Android as well: Java, Groovy (The language Gradle use), Scala, Assembly, C/C++,
Objective-C, and so on.

When Gradle was first released, I remember struggling to use it. Android Studio was still
unstable, and the build kept failing as my head kept banging against the wall. But when the
life gives you lemons, make lemonade. After learning more about Gradle, I'm here to give
you some Gradle usage and tips. SPOILER ALERT: This is going to be a long blog post.

What can it do?


Glad you asked. :D

1. Do you have open source/3rd party libraries or binary JAR files? Gradle can add and
import them!

44
2. You can create a list of tasks for Gradle to perform before building or compiling Android
app.

3. You can create multiple flavors of your app by overriding your project files and its
inheritance. (Pro/Free version is the easiest example.)

4. You can run unit tests before building so that your app unit features would be all tested
before compiling.

5. Many more!

It is very different perspective to look at what Gradle does comparing to what we develop
software by programming. It's about the building process until its successful deployment. It's
not about programming bugs or creating features.

When you create a new Android app project using Android Studio, a default Gradle task list
is also generated. It handles a lot of things for us such as compiling Java codes to its class
files, compiling your project libraries into JAR binary files, generating DEX byte codes, JAR
signing, Zip-aligning, and finally creating the APK executable binary file.

As you can see, Gradle can handle your project's library dependencies. You can create your
own build process if you want. You can accomplish the freemium model (A typical Android
app revenue model) or region-specific app variants. You can make sure that your app will
not crash when it's bulit because of the unit tests run by Gradle.

Enough Talking. Let's see in practice.


Top-level gradle files
When you create a new Android project with Gradle enabled, you would see two gradle files
at the project root directory: build.gradle and settings.gradle. These are top-level build
scripts. These files are useful if you want to add stuffs that should be global. For example, I
could add new gradle library repositories here so that all of my sub-level gradle scripts can
see them. I can specify Gradle version too. Here I'm adding maven central repository and
custom maven repository url.

45
// build.gradle file

// Top-level build file where you can add configuration options common to all sub-
projects/modules.

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.12.2'

// NOTE: Do not place your application dependencies here; they belong


// in the individual module build.gradle files
}
}

allprojects {
repositories {
jcenter()
mavenCentral()

maven {
url "SOME OTHER MAVEN REPOSITORY URLS"
}
}
}

What was that settings.gradle file? This is a file responsible for finding your sub projects and
linking them properly when building. In a new Android project, you'll see app folder which is
the actual Android project directory. However if you have Android Wear or TV project folders
additionally, settings.gradle file would be the one to include those folders so that Gradle can
know sub-project modules when building the app.

// settings.gradle

46
include ':app', ':wear',' ':tv'

Your project folder is structured by Gradle in a way that you can have multiple sub-project
modules as you witnessed above. This allows us to build your app by the platform: Mobile,
Smartwatch, and TV. That being said, each sub-project module has its own build.gradle only
for itself.

Sub-project gradle files


Because Gradle dictates your project structure, a typical sub-project structure looks like this:

Sub-project folder

- build

-- generated

-- intermediates

- libs

- src

-- androidTest

-- main

--- java

--- res

- build.gradle

The key points here are src folder and build.gradle file. Let's look at the build.gradle file for
this sub-project folder.

apply plugin: 'com.android.application'

android {
compileSdkVersion 20
buildToolsVersion "20.0.0"

47
defaultConfig {
applicationId "com.tivix.android.gradlePlayground"
minSdkVersion 16
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}

debug {

debuggable true
runProguard false
}

productFlavors {
demo {
applicationId "com.tivix.android.gradlePlayground.demo"
versionName "1.0-demo"
}
full {
applicationId "com.tivix.android.gradlePlayground.full"
versionName "1.0-full"
}
}

48
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:20.0.0'
compile 'com.google.android.gms:play-services:5.2.08'
compile 'com.google.maps.android:android-maps-utils:0.3'
}

This gradle file is specific for Android phone application. There are many information here
but many of them are straightforward such as compileSdkVersion, buildToolsVersion, and
defaultConfig.

If you look at dependencies portion, that's where you would add your project libraries
to import. Do you have raw Java JAR files? no problem. Put them in libs folder in this sub-
project folder. These days, many of Android/Java libraries are available in Maven repository.
It's essentially PyPi for Java. Gradle would visit the Maven repository, download the library,
and compile down to Gradle-friendly AAR format to import your libraries.

Notice buildTypes portion. This is where you can create a list of build configurations.I
have two build types: release and debug. Each build type has its own build settings to
target. Additionally, you can specify a different JAR signing key file per each build type here
using signingOptions.

Notice productFlavors portions. This is for app-variants. If you're coming from Django
world, Gradle product flavor works like Django's template inheritance. You can override the
project components by adding files in the product flavor. You can add exclusive contents for
the product flavor by adding new files.

All of the product flavors and build types extend src/main folder. Thus, you can assume
that Gradle has a default product called "main." In order to get this working, you need to
create actual folders in the filesystem to represent these, as that is the way Gradle finds the
product flavor in actual build process and can execute the build settings. That being said,
you can mix the product flavor and build type. Above build.gradle can generate below app-
variants:

demo-debug

49
demo-release

full-debug

full-release

debug

release

Now when you synchronize Gradle with your changed filesystem, Gradle actually create
additional tasks for these new variants. Boom. You can now build a specific variant with no
problem from now on. Moreover, each product flavor can now detect its unit test module by
creating the folder androidTest<FlavorName>. For main unit testing, androidTest folder
would run its Gradle task to run its unit tests. At the end, Gradle can actually store the test
result if you specify.

That's cool dude!


You have seen a glimpse of what Gradle can do for you. Think about many possibilities. You
can manage your project libraries, perform the integration test for your main AND all of your
product flavors, a different set of APK files generated by Gradle, and many more! For more
information, please check out Android Developer Website for the friendly tutorial
and Android Tool Project Site for the full-blown Gradle documentation specifically designed
for Android. Feel the magic of automation powered by Gradle. Your building process with
Gradle would increase the development cycle and quality of your Android app drastically.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

50
When creating icons, UI images, splash screen, and
other UI images for Android, the designer should
think about the screen size and DPI for quality
drawable resources.
I love the Android platform. The platform is very flexible from OS to app development
aspects, and many people love customizing their phone to show their personality. Because
Android is open-sourced, many phone manufacturers appeal their own form-factor and
customized OS theme. In order to accommodate this, Android has a concept of
Fragmentation to support multiple screen sizes & screen DPIs. However, this is somewhat
painful when it comes to design image resources. If the image has a wrong DPI, then the
image looks blurred, too pixelated, or small-scaled to the original screen. If the resolution is
wrong, the image may not look in fitted size on the screen. Literally, there is a ton of different
screen configurations for the contents to be displayed. Thankfully, Android has a set of
screen size & DPI categories.

There are about 6 different DPI (Density Pixel per


Inch) categories:
 Low - 120DPI

 Medium - 160DPI

 High - 240DPI

 Extra High - 320DPI (Like a retina display!)

 Extra Extra High - 480DPI

 Extra Extra Extra High - 640DPI (Available starting from Android 4.3 APIs. For 4K
resolution! Holy Moly!)

There are commonly two ways to target all screen


DPIs.
1. Easiest way - Make all images to Extra High or Extra Extra High DPI.

51
Android auto-scales the drawables if the device does not match the drawable DPI. If the
only drawables are created in high density, lower DPI screens will down-scale a resource to
fit in a layout. Con is that Android always goes to process the scaling every draw
time in UI thread.

2. Safe way - Make all images for every single DPI.


Android can pull appropriate drawables based on the device’s screen DPI. No scaling is
involved, therefore the images looks great in any device. However, the app file size gets
bigger if there are many drawable files to store. Longer time is needed for designers to
create these resources. (Width x Height x DPI settings)

What about the image resolutions? Do they also


differ by their DPI?
Image resolution and DPI are tightly coupled each other. There is a 3:4:6:8 scaling ratio in
drawable size by DPI.
LDPI - 0.75x
MDPI - Original size
HDPI - 1.5x
XHDPI - 2.0x
XXHDPI - 3x
XXXHDPI - 4.0x

For example if a 100x100 image is a baseline (MDPI),


LDPI - 75x75
HDPI - 150x150
XHDPI - 200x200
XXHDPI - 300x300
XXXHDPI - 400x400
and so on.

52
What if my drawable doesn’t need to be resized by
different screen factors?
Put your drawables in drawable or drawable-nodpi folder.
This folder would contain drawables available to all screen factors despite of DPIs such as
style XMLs, colors, and others.

So what is the best way?


If you're lazy enough to come up your own UI images, then try to create custom drawable
XMLs based on Android system resources if you can.

If your drawables are fews, try to target all DPIs and sizes.

If your drawables are a lot, try to use one high DPI and size setting for auto-scale.

If your target Android OS version is higher than Ice Cream Sandwich, chances are the
device can handle auto-scale pretty smoothly because of their general hardware specs.

These are some of my insights on drawable resources that the app comes with it to use for
itself. You don't need to worry about actual visual content necessarily. Android will have to
use ImageView or other appropriate layout element to placeholder that visual content with
defined density width & height. That will bring another topic which is mem/disk caching for
images. But as far as designing UI elements for Android, this is sufficient enough to start
off. Android is all about flexibility for developers. Go for one that you feel comfortable and
right about it!

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

why i cant remove title bar in android studio?


In the Style.xml window (App->src->main->res->values->styles.xml) make changes to
the <resources> to look like this:
53
<resources>

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">

</style>

</resources>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

If you want to show a button over a button in a same place in android use the FrameLayout

<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"
android:src="@drawable/play" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton2"
android:layout_alignTop="@+id/imageButton"
android:layout_toRightOf="@+id/imageButton"
android:layout_toEndOf="@+id/imageButton"
android:src="@drawable/pause" />
</FrameLayout>

In the above example play and pause buttons are showing in the same place

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

No Colors.xml file in Android project


right click on res->values folder and make a new file named colors.xml and define your color
as following in colors.xml:

<?xml version="1.0" encoding="utf-8"?>


<resources>
<color name="white">#FFFFFF</color>
<color name="yellow">#FFFF00</color>
</resources>

54
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

How to display Toast in Android?


In order to "display Toast" in your application, try this:

Toast.makeText(getActivity(), (String)data.result,
Toast.LENGTH_LONG).show();
Another example...

Toast.makeText(getActivity(), "this is my Toast message!!! =)",


Toast.LENGTH_LONG).show();
We can define two constants for duration:

int LENGTH_LONG Show the view or text notification for a long period of time.
int LENGTH_SHORT Show the view or text notification for a short period of time.
Read more about "Toasts"
Another option, customizing your toast:

LayoutInflater myInflater=LayoutInflater.from(this);
View view=myInflater.inflate(R.layout.your_custom_layout,null);
Toast mytoast=new Toast(this);
mytoast.setView(view);
mytoast.setDuration(Toast.LENGTH_LONG);
mytoast.show();

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

LISTVIEW

<ListView
android:layout_height="fill_parent"
android:id="@+id/listView2"
android:layout_width="match_parent"
android:background="@color/red_bg"
android:listSelector="@color/red_bg"
android:cacheColorHint="@color/red_bg"
android:choiceMode="singleChoice"
android:divider="@color/red_bg"
android:dividerHeight="3dip">
</ListView>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

55
how to programmatically hide a button in android sdk
playButton = (Button) findViewById(R.id.play);
playButton.setVisibility(1);
playButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//when play is clicked show stop button and hide play button
playButton.setVisibility(View.GONE);
stopButton.setVisibility(View.VISIBLE);

}
});

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Study - Google Cloud Messaging

Google Cloud Messaging (commonly


referred to as GCM) is a mobile service
developed by Google that enables
developers to send notification data or
information from developer-run servers to
applications that target the Google Android
Operating System, as well as applications
or extensions developed for
the Google Chrome
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

56
Screen Size

The actual physical size, measured as the scren’s diagonal

Screen density

The quantity of pixels within a physical area of the screen

Density-independent pixel

A virtual pixel unit that you should use when defining UI layout. Based on a 160 dpi screen.

Size
Small
Normal
Large
Xlarge

Density
Ldpi
Mdpi
Hdpi
Xhdpi
Nodpi

Orientation
Land
Port

Aspect ratio
Lang
Not long

res/layout/my_layout.xml
res/layout-small/my_layout.xml
res/layout-large/my_layout.xml
res/layout-xlarge/my_layout.xml
res/layout-xlarge-land/my_layout.xml

57
Use wrap_content, fill_parent or device independent pixel units when specifying dimensions in an
XML layout file.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Database Connection in Android


package com.comp1.android.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseConnectionAPI extends SQLiteOpenHelper{

//The Android's default system path of your application database.


private final static String DB_PATH = "/data/data/com.comp1.android.database/databases/";

private final static String DB_NAME = "fruitsmoothies.sqlite";

private final Context myContext;

private static SQLiteDatabase db;

/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and
resources.
* @param context
*/
public DatabaseConnectionAPI(Context context)
{

super(context, DB_NAME, null, 1);


this.myContext = context;
}

58
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException
{

boolean dbExist = checkDataBase();

if(dbExist)
{
//do nothing - database already exist
}
else
{

//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();

try
{
copyDataBase();
}
catch (IOException e)
{

throw new Error("Error copying database");


}
}
}

/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){

SQLiteDatabase checkDB = null;


try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}

59
return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{

//Open your local db as the input stream


InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db


String outFileName = DB_PATH + DB_NAME;

//Open the empty db as the output stream


OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile


byte[] buffer = new byte[2048];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}

//Close the streams


myOutput.flush();
myOutput.close();
myInput.close();

public void openDataBase() throws SQLException{


try
{
db.close();
}
catch(Exception e)
{
System.out.println("no database connected to close");
}
//Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

60
@Override
public synchronized void close() {
if(db != null)
db.close();
super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
/**
* Use this function to set the value of a particular column
*
* @param columnName The column name whose value is to be changed
* @param newColumnValue The value to be replaced in the column
* @param whereColumnName The column name to be compared with the where clause
* @param whereColumnValue The value to be compared in the where clause
*/
void onUpdateSet(String columnName, String newColumnValue, String[] whereColumnName, String[]
whereColumnValue){
String expanded_ColumnNames = new String(whereColumnName[0]);
String expanded_ColumnValues = new String(whereColumnValue[0]);
for(int i=1;i
{
expanded_ColumnNames = expanded_ColumnNames+","+whereColumnName[i];
expanded_ColumnValues = expanded_ColumnValues+","+whereColumnValue[i];
}
try
{
openDataBase();
db.execSQL("update recipe set \""+columnName+"\" = \""+newColumnValue+"\" where
\""+expanded_ColumnNames+"\" = \""+expanded_ColumnValues+"\"");
}
catch(Exception e)
{
System.out.println("Update couldnt complete "+e);
}

/**
* Query the given table, returning a Cursor over the result set.

61
*
* @param table The table name to compile the query against.
* @param columns A list of which columns to return. Passing null will return all columns,
* which is discouraged to prevent reading data from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted
* as an SQL WHERE clause (excluding the WHERE itself). Passing null
* will return all rows for the given table.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in order that they appear
* in the selection. The values will be bound as Strings.
* @param groupBy A filter declaring how to group rows, formatted as an
* SQL GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @param having A filter declare which row groups to include in the
* cursor, if row grouping is being used, formatted as an SQL HAVING
* clause (excluding the HAVING itself). Passing null will cause all
* row groups to be included, and is required when row grouping is
* not being used.
* @param orderBy How to order the rows, formatted as an SQL
* ORDER BY clause (excluding the ORDER BY itself). Passing
* null will use the default sort order, which may be unordered.
* @return A Cursor object, which is positioned before the first entry
*/
Cursor onQueryGetCursor(String table, String[] columns, String selection, String[] selectionArgs, String
groupBy, String having, String orderBy)
{
Cursor query = null;
try
{
openDataBase();
query = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
System.out.println("@@@@@ Query is :"+query);
}
catch(Exception e)
{
System.out.println("Query couldnt complete "+e);
}
return query;
}
/**
* Use this method to search a particular String in the provided field.
*
*
* @param columns The array of columns to be returned
* @param table The table name
* @param whereColumn The where clause specifying a particular columns
* @param keyword The keyword which is to be searched
*

62
* @return The cursor containing the result of the query
*/
Cursor onSearchGetCursor(String[] columns, String table, String[] whereColumn, String keyword)
{
String expColumns = new String(columns[0]);
Cursor rawquery=null;
for(int i=1;i
expColumns = expColumns+","+columns[i];
try
{
openDataBase();
rawquery = db.rawQuery("SELECT "+expColumns+" from "+table+" where "+whereColumn[0]+" like
\"%"+keyword+"%\" or "+whereColumn[1]+" like \"%"+keyword+"%\" or "+whereColumn[2]+" like
\"%"+keyword+"%\"", null);
}
catch(Exception e)
{
System.out.println("Raw Query couldnt complete "+e);
}
return rawquery;
}
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Calculate Distance between two location


(GeoPoint)
public double CalculationByDistance(Location Start, Location End)
{
double Radius = 6371;
double lat1 = Start.getLatitude();
double lat2 = End.getLatitude();
double lon1 = Start.getLongitude();
double lon2 = End.getLongitude();
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double km = Radius * c;
return km * 1000;
}

63
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android: Play Media File in the Assets Folder


ou can write an application using the code that plays a media file which is stored in your Assets folder.

Play a Media File in Assets Folder


Hide Copy Code
public void Play(String fileName)
{
AssetFileDescriptor descriptor = _context.getAssets().openFd(fileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
MediaPlayer mediaPlayer=new MediaPlayer();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), start, end);
mediaPlayer.prepare();
mediaPlayer.start();
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Image sizes

Flash Image for android

Mdpi - 320 X 480

Hdpi - 480 X 720

Xhdpi - 800 X 1200

Xxhdpi - 960 X 1440

640 X 1024

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Play audio file (.mp3) from asset folder in android.

import java.io.IOException;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

public class AudioPlayer {

64
String fileName;
Context contex;
MediaPlayer mp;

//Constructor
public AudioPlayer(String name, Context context) {
fileName = name;
contex = context;
playAudio();
}

//Play Audio
public void playAudio() {
mp = new MediaPlayer();
try {
AssetFileDescriptor descriptor = contex.getAssets()
.openFd(fileName);
mp.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.setLooping(true);
mp.start();
mp.setVolume(3, 3);

} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//Stop Audio
public void stop() {
mp.stop();
}
}

Call this class from any activity like as new AudioPlayer(file_name, mContext);

Code snippet to input file name in each coding.

String ringtoneFileName = "Ringtone1.mp3";

AudioPlayer audioPlayer = new AudioPlayer(ringtoneFileName,context);

65
audioPlayer.playAudio();

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

https://www.buzzingandroid.com/tools/android-layout-finder/ - very good

The Android Layout Finder helps you create the code that ties
your Android UI and Java code together.
http://www.technotalkative.com/android/ - good for android tutorial

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Note: This codes are not founded by me, i have just collected through search and
sorted it out.

1. *#*#4636#*#*

This code can be used to get some interesting information about your phone and
battery. It shows following 4 menus on screen:

 Phone information

 Battery information

 Battery history

 Usage statistics

2. *#*#7780#*#*
This code can be used for a factory data reset. It’ll remove following things:

 Google account settings stored in your phone

 System and application data and settings

 Downloaded applications

It’ll NOT remove:

66
 Current system software and bundled applications

 SD card files e.g. photos, music files, etc.

PS: Once you give this code, you get a prompt screen asking you to click on “Reset
phone” button. So you get a chance to cancel your operation.

3. *2767*3855#

Think before you give this code. This code is used for factory format. It’ll remove all
files and settings including the internal memory storage. It’ll also reinstall the phone
firmware.

PS: Once you give this code, there is no way to cancel the operation unless you
remove the battery from the phone. So think twice before giving this code.

4. *#*#34971539#*#*

This code is used to get information about phone camera. It shows following 4
menus:

 Update camera firmware in image (Don’t try this option)

 Update camera firmware in SD card

 Get camera firmware version

 Get firmware update count

WARNING: Never use the first option otherwise your phone camera will stop working
and you’ll need to take your phone to service center to reinstall camera firmware.
5. *#*#7594#*#*
This one is my favorite one. This code can be used to change the “End Call / Power”
button action in your phone. Be default, if you long press the button, it shows a
screen asking you to select any option from Silent mode, Airplane mode and Power
off.

67
You can change this action using this code. You can enable direct power off on this
button so you don’t need to waste your time in selecting the option.

6. *#*#197328640#*#*

This code can be used to enter into Service mode. You can run various tests and
change settings in the service mode

7. WLAN, GPS and Bluetooth Test Codes:

*#*#232339#*#* OR *#*#526#*#* OR *#*#528#*#* – WLAN test (Use “Menu” button


to start various tests)

*#*#232338#*#* – Shows WiFi MAC address

*#*#1472365#*#* – GPS test

*#*#1575#*#* – Another GPS test

*#*#232331#*#* – Bluetooth test

*#*#232337#*# – Shows Bluetooth device address

8. *#*#8255#*#* => This code can be used to launch GTalk Service Monitor.

9. Codes to get Firmware version information:

*#*#4986*2650468#*#* – PDA, Phone, H/W, RFCallDate

*#*#1234#*#* – PDA and Phone

*#*#1111#*#* – FTA SW Version

*#*#2222#*#* – FTA HW Version

*#*#44336#*#* – PDA, Phone, CSC, Build Time, Changelist number


68
10. Codes to launch various Factory Tests:

*#*#0283#*#* – Packet Loopback

*#*#0*#*#* – LCD test

*#*#0673#*#* OR *#*#0289#*#* – Melody test

*#*#0842#*#* – Device test (Vibration test and BackLight test)

*#*#2663#*#* – Touch screen version

*#*#2664#*#* – Touch screen test

*#*#0588#*#* – Proximity sensor test

*#*#3264#*#* – RAM version

11. To get to a File copy screen for backing up your images, videos, voice
memos, and other media files, type in *#*#273283*255*663282*#*#*

12. If you want to change default actions for the End Call and Power button, punch
in *#*#7594#*#* and change those settings.

13. Android also supports the Service Mode, invoked with


the *#*#197328640#*#*code, that lets you run tests related to the WiFi, Bluetooth,
and GPS circuitry. Other factory tests include LCD (*#*#0*#*#*), vibration and
backlight (*#*#0842#*#*), touchscreen (*#*#2664#*#*), RAM (*#*#3264#*#*),
proximity sensor (*#*#0588#*#*), and more.

14. Voice Dialer Logging Enabled => *#*#8351#*#*

15. PUK Unlock (from emergency dial screen)

69
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android – 0101 Attributes of ListView to keep in


mind
BY PARESH MAYANI - JUNE, 21ST 2011
If you are knowing and has already worked with Android ListView, then these are the
attributes you should know and use inside your android application to give a great
look & feel to ListView. FYI, i have noted down these attributes as mostly used, i
know there are some attributes also we can set while using ListView
like android:footerDividersEnabled and andorid:headerDividersEnabled. So these
below 6 are the attributes mostly used:
0000. android:background
It is used to set background resource to the ListView. Resources can either be color
or image.
0001. android:listSelector
It is used to set Selector to the ListView, it is generally Orange Color or Sky blue
color mostly. So you can also define your custom color/image as a list selector as per
your design.
0010. android:cacheColorHint
It indicates that this list will always be drawn on top of solid, single-color opaque
background. To disable the optimization, simply use the transparent color
#00000000. Here is a nice information given for ListView Backgrounds Optimization,
you should atleast go through once.
0011.android:choiceMode
It defines the choice mode means at a time how many items you can select at a time.
By default, ListView don’t have any choice made implemented. By setting the
choiceMode:
By setting the choiceMode To singleChoice, the list allows up to one item to be in a
chosen state.
By setting the choiceMode To multipleChoice, the list allows any number of items to
be chosen.
By setting the choiceMode to multipleChoiceModal the list allows any number of
items to be chosen in a special selection mode.
0100. android:divider
It defines the Divider to be displayed in between two ListView items.
0101. android:dividerHeight
It defines the Divider Height.
For example:
This is just a basic example to make you explain, you can take any color/image
resources:

70
<ListView
android:layout_height="fill_parent"
android:id="@+id/listView2"
android:layout_width="match_parent"
android:background="@color/red_bg"
android:listSelector="@color/red_bg"
android:cacheColorHint="@color/red_bg"
android:choiceMode="singleChoice"
android:divider="@color/red_bg"
android:dividerHeight="3dip">
</ListView>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android – GridView – 1001 attributes to keep in


mind
Same as my previous article on ListView attributes: Android – 0101 Attributes of
ListView to keep in mind, here i am going to share about the attributes of GridView
which we frequently use inside the application. Here are attributes:

Mostly Used:
0000 => android:numColumns=”auto_fit”
0001 => android:verticalSpacing=”5dp”
0010 => android:horizontalSpacing=”10dp”
0011 => android:stretchMode=”columnWidth”
0100 => android:columnWidth=”90dp”
0101 => android:smoothScrollbar=”true”

Rarely Used:
0110 => android:listSelector=”@color/red”
0111 => android:drawSelectorOnTop=”true”
1000 => android:scrollbarStyle=”insideOverlay”
1001 => android:scrollbars=”vertical”
0000. android:numColumns

71
Used to set number of columns we wants inside the GridView. we can also set
“auto_fit” value so that we developer need not to bother about number of columns.

0001. android:verticalSpacing
Used to set spacing between two gridview items vertically.

0010. android:horizontalSpacing
Used to set spacing between two gridview items horizontally.

0011. andorid:stretchMode
Used to control how items are stretched to fill their space.

0100. android:columnWidth
Used to set Width of the Column.
0101. android:smoothScrollbar=”true”
Used to control scrollbar effectively and When set to true, the list will use a more
refined calculation method based on the pixels height of the items visible on screen.

0110. android:listSelector=”@color/red”
Used to define the Selector image/color, selector image/color will be appeared
whenever we focus/pressed on the GridView item.

0111. android:drawSelectorOnTop=”true”
Used to control the selector image/color and When set to true, the selector will be
drawn over the selected item.

1000. android:scrollbarStyle=”insideOverlay”
Used to define the scroll bar position and its style.

1001. android:scrollbars=”vertical”
Used to define scrollbars such as Horizontal, vertical or both.
For example:

01 <GridView
02 android:id="@+id/gridViewImages"

72
03 android:layout_below="@+id/header"
04 android:layout_height="match_parent"
android:layout_width="fill_parent"
05 android:numColumns="auto_fit"
06 android:verticalSpacing="5dp"
07 adroid:horizontalSpacing="10dp"
08 android:smoothScrollbar="true">
09 </GridView>
10

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Keeping a Button under WebView in Android


Set android:layout_weight="1" on your WebView element and enclose it in a LinearLayout:
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<WebView android:id="@+id/webview1"
android:layout_above="@+id/btnOk"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<Button android:text="Ok"
android:id="@+id/btnOk"
android:layout_width="120px"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_centerHorizontal="true"/>
</LinearLayout>
shareimprove this answer

Only thing I changed in my above layout is adding layout-weight="1" and keeping everything else, but it works. Or
should I still change to LinearLayout? – Demonick Jun 13 '11 at 13:45

No. If it works as-is then feel free to stick with it. I'm please that it fixed things for you

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Adjusting size of custom dialog box in android


73
I'm not sure if this will work for your situation, but if you want to set it to full width or something
similar, you need to get the current Window for the activity and set it's layout params like so:

myDialog.show();
Window window = myDialog.getWindow();
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

its integer parameters of width and height. Simply use something like
window.setLayout(300,300);
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android Button Generators

http://angrytools.com/android/button/

http://hateum.github.io/AndroidDrawableGenerator/

Android Halo Colors

http://android-holo-colors.com/

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Intent i=new Intent(context,SendMessage.class);


i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);

First, get the intent which has started your activity using the getIntent() method:
Intent intent = getIntent();
If your extra data is represented as strings, then you can use intent.getStringExtra(String
name)method. In your case:
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

You need to pass some parameters into an activity while launching it.

Solution

A quick solution is to use Intent.putExtra() to push our data. And then use
getIntent().getExtras().getString() to retrieve it.

74
Discussion

Push Data
import android.content.Intent;

...

Intent intent =
new Intent(
this,
MyActivity.class );
intent.putExtra( "paramName", "paramValue" );
startActivity( intent );

The above code might be inside the main activity. "MyActivity.class" is the second Activity we want to
launch; it must be explicitly included in your AndroidManifest.xml file.

<activity android:name=".MyActivity" />

Pull Data
import android.os.Bundle;

...

Bundle extras = getIntent().getExtras();


if (extras != null)
{
String myParam = extras.getString("paramName");
}
else
{
//..oops!
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android TextView Align text to Right and Left


Here's another method:

<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background_common">
<TextView
android:text="Left Text"

75
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"/>
<TextView
android:text="Right Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"/>
</FrameLayout>

Layout_gravity tells the parent where to put the child. In a FrameLayout, children can go anywhere
and are unobstructed by other children. If there is overlap, the last child added is on top. Good luck!

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android - shadow on text?


You should be able to add the style, like this (taken from source code for Ringdroid):

<style name="AudioFileInfoOverlayText">
<item name="android:paddingLeft">4px</item>
<item name="android:paddingBottom">4px</item>
<item name="android:textColor">#ffffffff</item>
<item name="android:textSize">12sp</item>
<item name="android:shadowColor">#000000</item>
<item name="android:shadowDx">1</item>
<item name="android:shadowDy">1</item>
<item name="android:shadowRadius">1</item>
</style>
And in your layout, use the style like this:

<TextView android:id="@+id/info"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/AudioFileInfoOverlayText"
android:gravity="center" />
Edit: the source code can be viewed here: http://code.google.com/p/ringdroid/
Edit2: To set this style programmatically, you'd do something like this (modified from this
example to match ringdroid's resources from above)
TextView infoTextView = (TextView) findViewById(R.id.info);
infoTextView.setTextAppearance(getApplicationContext(),
R.style.AudioFileInfoOverlayText);
The signature for setTextAppearance is
public void setTextAppearance (Context context, int resid)

Since: API Level 1


Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance
resource.

76
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Set TextView text from html-formatted string


resource in XML
Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after
searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include
raw HTML in strings.xml, as long as you wrap it in

<![CDATA[ ...raw html... ]]>

Example:

<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>

Then, in your code:

TextView foo = (TextView)findViewById(R.id.foo);


foo.setText(Html.fromHtml(getString(R.string.nice_html)));

IMHO, this is several orders of magnitude nicer to work with :-)

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

How to display HTML in TextView?


You need to use Html.fromHtml() to use HTML in your XML Strings. Simply referencing a String
with HTML in your layout XML will not work.

For example:

myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

77
Android align textview to right
Actually our code is working but it will be clear if you give width less than parent, try this change

<TextView
android:id="@+id/textview_example"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center_vertical|right"
android:textColor="#474747"
android:text="ABAGSADGDBAJDHADNA"
android:textSize="14sp" />

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Aligning textviews on the left and right edges in


Android layout
Use a RelativeLayout with layout_alignParentLeft and layout_alignParentRight:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:id="@+id/mytextview1"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="@+id/mytextview2"/>

</RelativeLayout>

Also, you should probably be using dip (or dp) rather than sp in your layout. sp reflect text settings
as well as screen density so they're usually only for sizing text items.

78
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android layouts and automatic image resizing

I just encountered a situation very similar to the one you explained. I needed to have an
ImageView on top of the layout, which had to be stretched ONLY HORIZONTALLY and retain
its height when the phone gets into landscape orientation. I succeeded with just this:

<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/main_header"
android:scaleType="fitXY"
/>
and, of course, with activity's attribute:

<activity android:configChanges="keyboardHidden|orientation">
Hope this helps. Thank you.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Place 3 buttons in a LinearLayout to occupy equal amount of


space
Qustion:

i would like to have three buttons taking equal amount of available space horizontally in a row. I
used android:layout_gravity. What is the problem?
layout xml :

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1.0"
>

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Bg"
android:background="@drawable/button_red"
android:layout_weight=".2"
android:layout_gravity="left"

79
/>
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Bm"
android:background="@drawable/button_red"
android:layout_weight=".2"
android:textColor="#ffffff"
android:layout_gravity="center"
/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_red"
android:layout_weight=".2"
android:text="@string/Bf"
android:layout_gravity="right"
/>

</LinearLayout>
if someone see whats wrong, thanks.

The following layout should work. weights are for LinearLayouts..

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3"
>

<Button android:id="@+id/button1"
...
android:layout_weight="1"/>

<Button android:id="@+id/button2"
...
android:layout_weight="1"/>

<Button
android:id="@+id/button3"
...
android:layout_weight="1"/>

</LinearLayout>
shareedit

80
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Passing ArrayList through Intent


In your receiving intent you need to do:

Intent i = getIntent();
stock_list = i.getStringArrayListExtra("stock_list");
The way you have it you've just created a new empty intent without any extras.

If you only have a single extra you can condense this down to:

stock_list = getIntent().getStringArrayListExtra("stock_list");

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Passing string array between android activities


Bundle b=new Bundle();
b.putStringArray(key, new String[]{value1, value2});
Intent i=new Intent(context, Class);
i.putExtras(b);

Hope this will help you.

In order to read:

Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Which encoding should I use for my Android Studio project?


Since gradle and Android studio both use UTF-8, you should consider using that. It's a good
encoding too as it's based on unicode charset.

There has also been some talk on whether they should enforce UTF-8 or not in the future, so
you should start changing to UTF-8 asap :)

You can change your encoding as follows below.

Click File -> Settings (or click Ctrl + Alt + S) and find File Encodings in your Androd Studio.
See the image below as a reference.
Now you have three options

81
 change UTF-8 to match other encoding
 or change project encoding to match UTF-8 since both Gradle and Android Lint use this
(recommended)
 Ignore the warning

You can also see the current encoding of your file at the bottom right corner of Android studio.
You can also change it there. See the image below.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android layouts and automatic image resizing

82
I just encountered a situation very similar to the one you explained. I needed to have an
ImageView on top of the layout, which had to be stretched ONLY HORIZONTALLY and retain its
height when the phone gets into landscape orientation. I succeeded with just this:

<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/main_header"
android:scaleType="fitXY"
/>
and, of course, with activity's attribute:

<activity android:configChanges="keyboardHidden|orientation">
Hope this helps. Thank you.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Get Assets folder path and read txt file to string Android
example code
// Path for a WebView
String sAssets = "file:///android_asset/" + "index.htm";
WebView mWebView = (WebView)findViewById(R.id.webview1);
mWebView.loadUrl(sAssets);
// Path to Assets folder Context.getAssets
// getContext().getAssets()
// getAssets() - Return an AssetManager instance for your application's
package.

// File file = new File(getAssets()+"myFileName.txt"); // Error

// file to inputstream
InputStream input = getAssets().open("myData.txt");
// myData.txt can't be more than 2 gigs.
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();

// byte buffer into a string


String text = new String(buffer);

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Create a new activity using Android Studio


1. In Android Studio, in the java directory, select the package, com.mycompany.myfirstapp,
right-click, and select New > Activity > Blank Activity.
2. In the Choose options window, fill in the activity details: ...

83
3. Open the DisplayMessageActivity.java file.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

How can I change the image of an ImageView?


If you created imageview using xml file then follow the steps.

Solution 1:

Step 1: Create an XML file

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#cc8181"
>

<ImageView
android:id="@+id/image"
android:layout_width="50dip"
android:layout_height="fill_parent"
android:src="@drawable/icon"
android:layout_marginLeft="3dip"
android:scaleType="center"/>

</LinearLayout>
Step 2: create an Activity

ImageView img= (ImageView) findViewById(R.id.image);


img.setImageResource(R.drawable.my_image);

Solution 2:

If you created imageview from Java Class

ImageView img = new ImageView(this);


img.setImageResource(R.drawable.my_image);

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Failed to convert @drawable/ into a drawable

84
I have added an image to my Android project which I want to use in the UI. I have added the
file my-image.png to the drawable directory (to all 4 drawable directories created with the
project), and added the ImageView to the layout:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/textView"
android:layout_marginBottom="63dp"
android:src="@drawable/my-image" />
The problem is that I get the following error:

Rendering Problems

Failed to convert @drawable/my-image into a drawable


This is the capture:

Additionaly, if I try to compile the project, I get the following error:

Gradle: Execution failed for task ':MyProject:processDebugResources'.


Why do I get these errors and how can I solve it? Am I missing something? I've just started
Android development.

ANSWER:

Gradle: Execution failed for task ':MyProject:processDebugResources'.


because you have naming convention error in Resources

file name: must contain only [a-z0-9_.]


Rename file name to my_image

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android Layout Tutorial


An Android layout is a class that handles arranging the way its children appear on the screen. Anything that is
a View (or inherits from View) can be a child of a layout. All of the layouts inherit from ViewGroup (which

85
inherits from View) so you can nest layouts. You could also create your own custom layout by making a class
that inherits from ViewGroup.

The standard Layouts are:

AbsoluteLayout
FrameLayout
LinearLayout
RelativeLayout
TableLayout

FrameLayout
FrameLayout is designed to display a single item at a time. You can have multiple elements within a
FrameLayout but each element will be positioned based on the top left of the screen. Elements that overlap will
be displayed overlapping. I have created a simple XML layout using FrameLayout that shows how this works.

<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:src="@drawable/icon"
android:scaleType="fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
<TextView
android:text="Learn-Android.com"
android:textSize="24sp"
android:textColor="#000000"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>

Here is the result of this XML.

86
You can see I had both the ImageView and TextView fill the parent in both horizontal and vertical layout.
Gravity specifies where the text appears within its container, so I set that to center. If I had not set a gravity
then the text would have appeared at the top left of the screen.

FrameLayout can become more useful when elements are hidden and displayed programmatically. You can
use the attribute android:visibility in the XML to hide specific elements. You can call setVisibility from the code
to accomplish the same thing. The three available visibility values are visible, invisible (does not display, but
still takes up space in the layout), and gone (does not display, and does not take space in the layout).

So you could, for example, have a game in a FrameView where text displayed to the user is visible in the
middle of the screen at appropriate times (e.g. “Game Over”).

LinearLayout
LinearLayout organizes elements along a single line. You specify whether that line is verticle or horizontal
using android:orientation. Here is a sample Layout XML using LinearLayout.

87
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

Here is a screenshot of the result of the above XML.

Here is a screenshot of the same XML except that the android:orientation has been changed to horizontal.

88
You might note that the EditText field at the end of the line has had its width reduced in order to fit. Android will
try to make adjustments when necessary to fit items on screen. The last page of this tutorial will cover one
method to help deal with this.

I mentioned on the first page that Layouts can be nested. LinearLayout is frequently nested, with horizontal
and vertical layouts mixed. Here is an example of this.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="Last Name"

89
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>

As you can see we have a Vertical LinearLayout whose children are a button, and two horizontal
LinearLayouts. Each horizontal LinearLayout has two child controls. You should note that in the child
LinearLayout elements I used android:layout_height=”wrap_content” instead of fill_parent. If I had used
fill_parent the first name TextView and EditView would have taken all of the available space on the screen, and
the Last Name would not have been displayed. Here is what this XML does display.

Nested Layouts do not have to be of one type. I could, for example, have a LinearLayout as one of the children
in a FrameLayout.

RelativeLayout
RelativeLayout lays out elements based on their relationships with one another, and with the parent container.
This is arguably the most complicated layout, and we need several properties to actually get the layout we
want.

Relative To Container
These properties will layout elements relative to the parent container.

90
 android:layout_alignParentBottom – Places the bottom of the element on the bottom of the container
 android:layout_alignParentLeft – Places the left of the element on the left side of the container
 android:layout_alignParentRight – Places the right of the element on the right side of the container
 android:layout_alignParentTop – Places the element at the top of the container
 android:layout_centerHorizontal – Centers the element horizontally within its parent container
 android:layout_centerInParent – Centers the element both horizontally and vertically within its
container
 android:layout_centerVertical – Centers the element vertically within its parent container

Relative To Other Elements


These properties allow you to layout elements relative to other elements on screen. The value for each of
these elements is the id of the element you are using to layout the new element. Each element that is used in
this way must have an ID defined using android:id=”@+id/XXXXX” where XXXXX is replaced with the desired
id. You use “@id/XXXXX” to reference an element by its id. One thing to remember is that referencing an
element before it has been declared will produce an error.

 android:layout_above – Places the element above the specified element


 android:layout_below – Places the element below the specified element
 android:layout_toLeftOf – Places the element to the left of the specified element
 android:layout_toRightOf – Places the element to the right of the specified element

Alignment With Other Elements


These properties allow you to specify how elements are aligned in relation to other elements.

 android:layout_alignBaseline – Aligns baseline of the new element with the baseline of the specified
element
 android:layout_alignBottom – Aligns the bottom of new element in with the bottom of the specified
element
 android:layout_alignLeft – Aligns left edge of the new element with the left edge of the specified
element
 android:layout_alignRight – Aligns right edge of the new element with the right edge of the specified
element
 android:layout_alignTop – Places top of the new element in alignment with the top of the specified
element

Here is a sample XML Layout

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"

91
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/firstName"
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/backbutton" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/firstName"
android:layout_alignBaseline="@id/firstName" />
<TextView
android:id="@+id/lastName"
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/firstName" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/lastName"
android:layout_alignBaseline="@id/lastName" />
</RelativeLayout>

Here is the screen produced by that XML.

92
I wanted to show this to you because the first time I made a RelativeLayout I did exactly this and then looked
at the screen and said, “Hang on a minute, that’s not what I wanted!” The problem here is that when Android
draws the TextView lastName below the TextView firstName it only sets aside the space it needs for the
TextView. Android only reads the Layout XML one time so it doesn’t know that an EditView is the next item
and doesn’t plan for it. So when the EditView is drawn to the right of the TextView it only has the height of the
TextView to work with so it overlaps the EditView above it. Here is the Layout XML I wrote to create the form
the way it should look.

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/firstName"
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/backbutton" />
<EditText
android:id="@+id/editFirstName"
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/firstName"
android:layout_below="@id/backbutton"/>
<EditText
android:id="@+id/editLastName"
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editFirstName"
android:layout_alignLeft="@id/editFirstName"/>
<TextView
android:id="@+id/lastName"
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/editLastName"
android:layout_below="@id/editFirstName" />
</RelativeLayout>

You probably noticed that I had to rearrange the elements in the XML since, as I already mentioned, you
cannot reference an element that has not already been laid out. Here is what the updated RelativeLayout
produces.

93
TableLayout
TableLayout organizes content into rows and columns. The rows are defined in the layout XML, and the
columns are determined automatically by Android. This is done by creating at least one column for each
element. So, for example, if you had a row with two elements and a row with five elements then you would
have a layout with two rows and five columns.

You can specify that an element should occupy more than one column using android:layout_span. This can
increase the total column count as well, so if we have a row with two elements and each element has
android:layout_span=”3″ then you will have at least six columns in your table.

By default, Android places each element in the first unused column in the row. You can, however, specify the
column an element should occupy using android:layout_column.

Here is some sample XML using TableLayout.

<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow>
<Button
android:id="@+id/backbutton"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView

94
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>

This is the result of that XML.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Difference between px, dp, dip and sp on Android?


1. px
Pixels - corresponds to actual pixels on the screen.

95
2. in
Inches - based on the physical size of the screen.
1 Inch = 2.54 centimeters
3. mm
Millimeters - based on the physical size of the screen.
4. pt
Points - 1/72 of an inch based on the physical size of the screen.
5. dp or dip
Density-independent Pixels - an abstract unit that is based on the physical density of the
screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen.
The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct
proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent
with "sp".
6. sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size
preference. It is recommend you use this unit when specifying font sizes, so they will be
adjusted for both the screen density and user's preference.

+----------------+----------------+---------------+------------------------------
-+
| Density Bucket | Screen Density | Physical Size | Pixel Size
|
+----------------+----------------+---------------+------------------------------
-+
| ldpi | 120 dpi | 0.5 x 0.5 in | 0.5 in * 120 dpi = 60x60 px
|
+----------------+----------------+---------------+------------------------------
-+
| mdpi | 160 dpi | 0.5 x 0.5 in | 0.5 in * 160 dpi = 80x80 px
|
+----------------+----------------+---------------+------------------------------
-+
| hdpi | 240 dpi | 0.5 x 0.5 in | 0.5 in * 240 dpi = 120x120 px
|
+----------------+----------------+---------------+------------------------------
-+
| xhdpi | 320 dpi | 0.5 x 0.5 in | 0.5 in * 320 dpi = 160x160 px
|
+----------------+----------------+---------------+------------------------------
-+
| xxhdpi | 480 dpi | 0.5 x 0.5 in | 0.5 in * 480 dpi = 240x240 px
|
+----------------+----------------+---------------+------------------------------
-+
| xxxhdpi | 640 dpi | 0.5 x 0.5 in | 0.5 in * 640 dpi = 320x320 px
|
+----------------+----------------+---------------+------------------------------
-+

+---------+-------------+---------------+-------------+--------------------+
| Unit | Description | Units Per | Density | Same Physical Size |
| | | Physical Inch | Independent | On Every Screen |

96
+---------+-------------+---------------+-------------+--------------------+
| px | Pixels | Varies | No | No |
+---------+-------------+---------------+-------------+--------------------+
| in | Inches | 1 | Yes | Yes |
+---------+-------------+---------------+-------------+--------------------+
| mm | Millimeters | 25.4 | Yes | Yes |
+---------+-------------+---------------+-------------+--------------------+
| pt | Points | 72 | Yes | Yes |
+---------+-------------+---------------+-------------+--------------------+
| dp | Density | ~160 | Yes | No |
| | Independent | | | |
| | Pixels | | | |
+---------+-------------+---------------+-------------+--------------------+
| sp | Scale | ~160 | Yes | No |
| | Independent | | | |
| | Pixels | | | |
+---------+-------------+---------------+-------------+--------------------+

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android - Fragments
A Fragment is a piece of an activity which enable more modular activity design. It
will not be wrong if we say, a fragment is a kind ofsub-activity.

Following are important points about fragment −

 A fragment has its own layout and its own behaviour with its own life cycle callbacks.

 You can add or remove fragments in an activity while the activity is running.

 You can combine multiple fragments in a single activity to build a multi-plane UI.

 A fragment can be used in multiple activities.

 Fragment life cycle is closely related to the life cycle of its host activity which means
when the activity is paused, all the fragments available in the activity will also be
stopped.

 A fragment can implement a behaviour that has no user interface component.

 Fragments were added to the Android API in Honeycomb version of Android which
API version 11.

97
You create fragments by extending Fragment class and You can insert a
fragment into your activity layout by declaring the fragment in the
activity's layout file, as a <fragment> element.

Following is a typical example of how two UI modules defined by fragments can


be combined into one activity for a tablet design, but separated for a handset
design.

Fragment Life Cycle


Android fragments have their own life cycle very similar to an android activity.
This section briefs different stages of its life cycle.

98
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Unhide the Developer option in Android Phone

https://www.youtube.com/watch?v=Qb2olFyoMV4 - good
youtube for adding any physical device to android studio

Some Android mobile are hidden the developer options. I you want to
invoke the developer options. Go to settings in the phone and select
about phone. In the about phone there is a builder number. You juse
press 7 times on Build Number, now the developer option is unhided
from the Phone/

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

http://sampleprogramz.com/android/sqlitedb.php# - good website for android tutorial

http://programmerguru.com/android-tutorial/how-to-create-android-app-with-movable-to-sd-
card-feature/# - this also good website for android

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

99
Difference between ArrayAdapter and ListAdapter in
Android?
This is not related to Android. But a general Java question.

When you use ListAdapter as the type for your variable, you are really interested in the
interface. You may not be interested in calling some specific method
of ArrayAdapter<String> not available in ListAdapter. That is mainly because you will just assign
the adapter as the list adapter for the view.
You may use the precise type of ArrayAdapter<String> if you really need to call some specific
methods.
It all depends on your use case.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

ArrayList in java with example programs –


Collections Framework
Arraylist is a class which implements List interface. It is widely used because of the
functionality and flexibility it offers. Most of the developers choose Arraylist over
Array as it’s a very good alternative of traditional java arrays.
The issue with arrays is that they are of fixed length so if it is full we cannot add any
more elements to it, likewise if there are number of elements gets removed from it the
memory consumption would be the same as it doesn’t shrink. On the other ArrayList can
dynamically grow and shrink as per the need. Apart from these benefits ArrayList class
enables us to use predefined methods of it which makes our task easy. Let’s see the
ArrayList example first then we will discuss it’s methods and their usage.

ArrayList Example in Java

import java.util.*;

public class ArrayListExample {


public static void main(String args[]) {
/*Creation of ArrayList: I'm going to add String
*elements so I made it of string type */
ArrayList<String> obj = new ArrayList<String>();

100
/*This is how elements should be added to the array list*/
obj.add("Ajeet");
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");

/* Displaying array list elements */


System.out.println("Currently the array list has following elements:"+obj);

/*Add element at the given index*/


obj.add(0, "Rahul");
obj.add(1, "Justin");

/*Remove elements from array list like this*/


obj.remove("Chaitanya");
obj.remove("Harry");

System.out.println("Current array list is:"+obj);

/*Remove element from the given index*/


obj.remove(1);

System.out.println("Current array list is:"+obj);


}
}
Output:

Currently the array list has following elements:[Ajeet, Harry, Chaitanya, Steve, Anuj]
Current array list is:[Rahul, Justin, Ajeet, Steve, Anuj]
Current array list is:[Rahul, Ajeet, Steve, Anuj]

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Where to place Assets folder in Android Studio


Since Android Studio uses the new Gradle-based build system, you should
be putting assets/ inside of the source sets (e.g., src/main/assets/), if I understand
correctly.

Let Android Studio do it for you.


1. In Android Studio (1.0 & above), right-click on the folder and navigate to the Assets
Folder.

101
2. On the next screen just click Finish.

102
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Fragment
A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say,
a fragment is a kind of sub-activity.

Following are important points about fragment −

 A fragment has its own layout and its own behaviour with its own life cycle callbacks.
 You can add or remove fragments in an activity while the activity is running.
 You can combine multiple fragments in a single activity to build a multi-plane UI.
 A fragment can be used in multiple activities.
 Fragment life cycle is closely related to the life cycle of its host activity which means when
the activity is paused, all the fragments available in the activity will also be stopped.
 A fragment can implement a behaviour that has no user interface component.
 Fragments were added to the Android API in Honeycomb version of Android which API
version 11.

You create fragments by extending Fragment class and You can insert a fragment into your activity
layout by declaring the fragment in the activity's layout file, as a <fragment> element.

Prior to fragment introduction, we had a limitation because we can show only a single activity on the
screen at one given point in time. So we were not able to divide device screen and control different
parts separately. But with the introduction of fragment we got more flexibility and removed the
limitation of having a single activity on the screen at a time. Now we can have a single activity but
each activity can comprise of multiple fragments which will have their own layout, events and
complete life cycle.

Following is a typical example of how two UI modules defined by fragments can be combined into
one activity for a tablet design, but separated for a handset design.

103
The application can embed two fragments in Activity A, when running on a tablet-sized device.
However, on a handset-sized screen, there's not enough room for both fragments, so Activity A
includes only the fragment for the list of articles, and when the user selects an article, it starts Activity
B, which includes the second fragment to read the article.

Fragment Life Cycle

Android fragments have their own life cycle very similar to an android activity. This section briefs
different stages of its life cycle.

104
Fragment lifecycle

Here is the list of methods which you can to override in your fragment class −

 onAttach()The fragment instance is associated with an activity instance.The fragment and the
activity is not fully initialized. Typically you get in this method a reference to the activity
which uses the fragment for further initialization work.
 onCreate() The system calls this method when creating the fragment. You should initialize
essential components of the fragment that you want to retain when the fragment is paused or
stopped, then resumed.
 onCreateView() The system calls this callback when it's time for the fragment to draw its
user interface for the first time. To draw a UI for your fragment, you must return a View
component from this method that is the root of your fragment's layout. You can return null if
the fragment does not provide a UI.
 onActivityCreated()The onActivityCreated() is called after the onCreateView() method when
the host activity is created. Activity and fragment instance have been created as well as the
view hierarchy of the activity. At this point, view can be accessed with the findViewById()
method. example. In this method you can instantiate objects which require a Context object
 onStart()The onStart() method is called once the fragment gets visible.
 onResume()Fragment becomes active.
 onPause() The system calls this method as the first indication that the user is leaving the
fragment. This is usually where you should commit any changes that should be persisted
beyond the current user session.
 onStop()Fragment going to be stopped by calling onStop()
 onDestroyView()Fragment view will destroy after call this method
 onDestroy()onDestroy() called to do final clean up of the fragment's state but Not guaranteed
to be called by the Android platform.

How to use Fragments?

This involves number of simple steps to create Fragments.

 First of all decide how many fragments you want to use in an activity. For example let's we
want to use two fragments to handle landscape and portrait modes of the device.
 Next based on number of fragments, create classes which will extend the Fragment class. The
Fragment class has above mentioned callback functions. You can override any of the
functions based on your requirements.
 Corresponding to each fragment, you will need to create layout files in XML file. These files
will have layout for the defined fragments.
 Finally modify activity file to define the actual logic of replacing fragments based on your
requirement.

Types of Fragments

Basically fragments are divided as three stages as shown below.

105
 Single frame fragments − Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.
 List fragments − fragments having special list view is called as list fragment
 Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

TextWatcher
A Text Watcher is really helpful for scenarios like login/register screen validation. As an when user is
entering the data, you can keep an eye on user input and notify early instead of waiting till user press
submit button manually. Another great realtime example is Google search; it shows user the realtime
search suggestion while user entering data.

Implementing Text watcher is quite easy, you have to call addTextChangedListener() method and
pass the reference to TextWatcher instance. You can override the following TextWatcher
class method to take various actions, when the content of EditText changes.

Android TextWatcher Example


TextWatcher
Basically, a TextWatcher is used to keep watch on EditText while entering data into it. We can perform
operation and keep watch on which characters are being entered or how many characters are being entered
in the EditText.

For Ex. We can use TextWatcher to have checks on the password field that minimum number of characters
are entered or not, or We can check the password Strength depending on number of characters entered in
Password field .

TextWatcher class has 3 methods and we need override these methods to implement our own functionality.

1: public abstract void afterTextChanged (Editable s)


This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to
make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because
any changes you make will cause this method to be called again recursively. (You are not told where the
change took place because other afterTextChanged() methods may already have made other changes and
invalidated the offsets. But if you need to know here, you can use setSpan(Object, int, int, int) in
onTextChanged(CharSequence, int, int, int) to mark your place and then look up from here where the span
ended up.

106
2: public abstract void beforeTextChanged (CharSequence s, int start, int count, int after)
This method is called to notify you that, within s, the count characters beginning at start are about to be
replaced by new text with length after. It is an error to attempt to make changes to s from this callback.

3: public abstract void onTextChanged (CharSequence s, int start, int before, int count)
This method is called to notify you that, within s, the count characters beginning at start have just
replaced old text that had length before. It is an error to attempt to make changes to s from this callback.

TextWatcher Example
In this post I have given an Example in which we have a password field of type EditText , in which user
will enter his password and we will show strength of password according to the number of characters
entered by the user, we also show that maximum characters has been is entered when user enter 20
characters.

We have used following parameters to check Password Strength

Password Length Password Strengthness


1-5 Easy
6-9 Medium
10-14 Strong
15-20 Strongest

How to Attach TextWatcher to EditText

We create an Object of TextWatcher and override required methods

Declare the Objects

EditText editTextPassword;
TextView textViewPasswordStrengthIndiactor;

inside onCreate()

editTextPassword.addTextChangedListener(mTextEditorWatcher);

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

SQLite in Android How to update a specific row


First make a ContentValues object :

ContentValues cv = new ContentValues();

107
cv.put("Field1","Bob"); //These Fields should be your String values of actual column
names
cv.put("Field2","19");
cv.put("Field2","Male");
Then use the update method, it should work now:

myDB.update(TableName, cv, "_id="+id, null);

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Link should be open in same web view in Android


You need to add WebViewClient to your WebView in order to open it in the WebView.
Something like

myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android WebView click open within WebView not a default


browser
You have to set up a webViewClient for your webView.

Sample:

this.mWebView.setWebViewClient(new WebViewClient(){

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

public class Calendar extends Fragment {


String language;
View rootView;

108
WebView wv;

public Calendar() {
this.language = "";
}

public View onCreateView(LayoutInflater inflater, ViewGroup


container, Bundle savedInstanceState) {
this.rootView = inflater.inflate(C0155R.layout.calandar,
container, false);
this.wv = (WebView)
this.rootView.findViewById(C0155R.id.webView1);
this.wv.loadUrl("file:///android_asset/grivalamdate.html");
this.language = MainActivity.language;
if (this.language.equalsIgnoreCase("tamil"))
{
this.wv.loadUrl("file:///android_asset/grivalamdatetamil.html");
}
else
{
this.wv.loadUrl("file:///android_asset/grivalamdate.html");
}
return this.rootView;
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Fill fields in webview automatically


You don't need to use "java commands"... but instead JavaScript... for instance:

String username = "cristian";


webview.loadUrl("javascript:document.getElementById('username').value =
'"+username+"';");

So basically, what you have to do is a big string of JavaScript code that will get those fields and put
values on them; also, you can enable/disable the submit button from JavaScript.

Auto fill field in WebView using javascript fails


When you start to target API 19 and above, this is the behavior of WebView.loadUrl when it's passed
a javascript: URL that returns a value.

You should update your app so that when running on API 19 or above, it uses evaluateJavaScript, and
falls back to loadUrl when running on older devices. Something like:

109
if (android.os.Build.Version.SDK_INT >= 19) {
webview.evaluateJavaScript("...", null);
} else {
webview.loadUrl("javascript:...");
}

Auto fill in fields in WebView android


loadURL is asynchronous; in other words, calling loadUrl kicks off the HTTP request, but then
returns immediately, before the document is downloaded and rendered. The error you're seeing is
because you're trying to execute the javascript too early (before the document is downloaded, parsed,
and rendered).

You'll need to use a WebViewClient, and wait for the page to finish loading before you execute your
javascript. Try the onPageFinished callback, but be careful that you can sometimes get multiple
callbacks because of iFrames and the like.

fill form programmatically in Android


Webview - JavaScript
This is untested, but I see two things wrong here:

1. You should call setWebViewClient with your WebViewClient implementation before you
call loadUrl. However, loadUrl is asynchronous, so it probably would not make a
difference, but this is worth a try I think.
2. You are not calling super.onPageFinished(view, url); in onPageFinshed. You should
add this call.

EDIT 2:

I finally took a look at the actual page you are working with. The problem is that the page loads
content in a different frame, so you actually have to make the getElementsByName call on a different
document. The frame in which both of the inputs you want are located has the name mainFrame in
your page. So, you should write the javascript like this and load that into the WebView as you have
done above:

window.frames["mainFrame"].document.
getElementsByName('p_codigo_c')[0].value = "user";
window.frames["mainFrame"].document.
getElementsByName('p_clave_c')[0].value = "password";

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

110
Color

Color Colour Value Color Color Value


#223e49 #894211

#9c6b4d #cb4000

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

http://www.appiconsizes.com/

Generate all the iPhone, Android, IOS,


Facebook, web touch icons, Blackberry,
Windows Phone, Bada and WebOS app icons
and splash/default images at once. Select your
file below and press 'Go!'.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

https://www.fluidui.com/editor/live/ - it is good site for design your

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

1 Genymotion

Anyone who is familiar with the default Android Emulator will know that starting the emulator and
running an app can be an extremely slow and tedious process. Genymotion solves this problem by
providing a free (for personal uses) hardware accelerated Android emulator which is screaming fast.

111
Genymotion virtual devices support various Android API levels and work seamlessly with Android
Studio. Download it ASAP, it will save you a lot of time.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android Asset Studio


http://romannurik.github.io/AndroidAssetStudio/

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android Button Maker

Android Button Maker is online tool to generate buttons code for Android Apps. Android API
provide Drawable Resources where XML file defines geometric shape, including colors, border and
gradients.
These button is generating based on shape drawable XML code which load faster compare to normal
png buttons. You can customize button properties in setting panel and get source code.

http://angrytools.com/android/button/

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

http://www.technotalkative.com/lazy-android-part-7-useful-tools/ -

The above websites provide the Useful tools for Android


development
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

http://shreyasachar.com/AndroidAssetStudio/index.html - Android Asset Studio for


Material Design

<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

http://www.decompileandroid.com/ - good for android decompiler

http://www.javadecompilers.com/apk - very good android decompiler

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

112
Android Layout Finder | Buzzing Android
https://www.buzzingandroid.com/tools/android-layout-finder/ - this is a very good site
get the android code.
If you paste your layout xml file in the above site, if finds the controls and their
variables then generate the java code for initializing the controls .
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

If you want to develop multi screen app in android add the


following code in android manifest file.
<supports-screens android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"
android:anyDensity="true"
android:resizeable="true"/>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

<< <<<<<<<<<<<< <<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

113
How to Apply Shadow Effect on Android
TextView
This example explains how to apply Shadow Effect on Android TextView. You can apply Shadow
Effect on Android TextView in two ways. Either we do it pragmatically or we can change in the xml
layout.

Shadow Effect on Android TextView using XML Layout


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="20dp" >

<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:shadowColor="#000"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="50"
android:text="Text Shadow Example1"
android:textColor="#FBFBFB"
android:textSize="28dp"
android:textStyle="bold" />

<TextView
android:id="@+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Text Shadow Example2"
android:textColor="#FBFBFB"
android:textSize="28dp"
android:textStyle="bold" />

</LinearLayout>

In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the
configuration items are

 android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a
shadow on the left of text and +Dx on the right
 android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text
and +Dy specifies below the text.
 android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a
small value if shadow needs to be prominent.
 android:shadowColor – specifies the shadow color

114
Shadow Effect on Android TextView pragmatically

Use below code snippet to get the shadow effect on the second TextView pragmatically.

TextView textv = (TextView) findViewById(R.id.textview2);


textv.setShadowLayer(30, 0, 0, Color.RED);

Output

<<<<<< <<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

115
Android make activity as Fullscreen (Removing Title Bar or Action Bar)

If want to make an activity to fullscreen in some cases like playing video in fullscreen mode, playing
game etc., you can do that by following one of the methods.

Method 1

One way is using Theme.Holo.Light.NoActionBar.Fullscreen value in AndroidManifest.xml file.


(Use the appropriate theme name whichever you used in your application)

<activity android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
</activity>

Method 1

Another way is, do this through code in the activity. In your activity do the following before calling
setContentView() function

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.activity_main);

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

How to hide the title bar for an Activity in XML


with existing custom theme
I now did the following.

I declared a style inheriting everything from my general style and then disabling the titleBar.

<style name="generalnotitle" parent="general">


<item name="android:windowNoTitle">true</item>
</style>

Now I can set this style to every Activity in which I want to hide the title bar overwriting the a
pplication wide style and inheriting all the other style informations, therefor no duplication in the

116
style code.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

how to add background image to activity?


use the android:background attribute in your xml. Easiest way if you want to apply it to a whole
activity is to put it in the root of your layout. So if you have a RelativeLayout as the start of your xml,
put it in here:

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootRL"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
</RelativeLayout>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Android Studio drawable folders


Q: In Android Studio, I can't figure out where to put images to be used inside the app. The
drawable folder isn't broken down into drawable-hdpi, drawable-ldpi, etc. I saw another
question asking this and the answer was to switch to Project view instead of Android view but
drawable is only one folder there too. There is mipmap-hdpi, mipmap-ldpi, etc, but people are
saying that's only for app icons. I'm confused.

A: Ifnothing
you don't see a drawable folder for the DPI that you need, you can create it yourself. There's
magical about it; it's just a folder which needs to have the correct name.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

http://angrytools.com/ -
this is a good website for CSS gradian generator, Android b
utton maker CSS generator

117
mipmap vs drawable folders [duplicate]
The mipmap folders are for placing your app icons in only. Any other drawable assets you use should
be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they
are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

Set icon for android application


If you intend on your application being available on a large range of devices, you should
place your application icon into the different res/drawable... folders provided. In
each of these folders, you should include a 48dp sized icon:

 drawable-ldpi (120 dpi, Low density screen) - 36px x 36px


 drawable-mdpi (160 dpi, Medium density screen) - 48px x 48px
 drawable-hdpi (240 dpi, High density screen) - 72px x 72px
316 down  drawable-xhdpi (320 dpi, Extra-high density screen) - 96px x 96px
vote  drawable-xxhdpi (480 dpi, Extra-extra-high density screen) - 144px x 144px
accepted  drawable-xxxhdpi (640 dpi, Extra-extra-extra-high density screen) - 192px x
192px

You may then define the icon in your AndroidManifest.xml file as such:

<application android:icon="@drawable/icon_name"
android:label="@string/app_name" >
....
</application>

118
Sqlite database

The application databases are stored in the data/data/<name of your


package>/databases/ folder on your device. That’s the folder where we need
to copy our database.

Android Toast example


In Android, Toast is a notification message that pop up, display a certain amount of time, and
automtaically fades in and out, most people just use it for debugging purpose.

Code snippets to create a Toast message :

//display in short period of time


Toast.makeText(getApplicationContext(), "msg msg",Toast.LENGTH_SHORT).show();

//display in long period of time


Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();

119
How to display Toast in Android?

In order to "display Toast" in your application, try this:

Toast.makeText(getApplicationContext(), (String)data.result,
Toast.LENGTH_LONG).show();

other example...

Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",


Toast.LENGTH_LONG).show();

We can define two constats for duration:

int LENGTH_LONG Show the view or text notification for a long period of time.

int LENGTH_SHORT Show the view or text notification for a short period of time.

Read more about "Toasts"

other option, customizing your toast:

LayoutInflater myInflater=LayoutInflater.from(this);
View view=myInflater.inflate(R.layout.your_custom_layout,null);
Toast mytoast=new Toast(this);
mytoast.setView(view);
mytoast.setDuration(Toast.LENGTH_LONG);
mytoast.show();

sqlite browser: where is the db file?


All databases are saved in:

/data/data/the.app.package.name/databases/the_name_of_db

And no, you cannot access that file in a non-rooted phone. Fortunately the emulator is rooted.

Android Studio : unmappable character for


encoding UTF-8
30 down v I had the same problem because there was files with windows-1251 encoding and

120
ote ac cepted Cyrillic comments. In Android Studio which is based on IntelliJ IDEA you can solve it
in two ways:

a) convert file encoding to UTF-8 or

b) set the right file encoding in your build.gradle script:

android {
...
compileOptions.encoding = 'windows-1251' // write your encoding
here
...

To convert file encoding use the menu at the bottom right corner of IDE. Select right
file encoding first -> press Reload -> select UTF-8 -> press Convert.

Also read this Use the UTF-8, Luke! File Encodings in IntelliJ IDEA

How to view all items in arraylist java?


static String List<String> members = new ArrayList<String>();

would this add the string value to my arraylist and save it for later use?

Yes. Your code seems perfect to do it with no problems.

For example If I click three different buttons this will add three different className values to the
arraylist. Would this then store a string value that would hold three different string values for my
members arraylist?

If you tell to your button's onClickListener to add a string to the members ArrayList then it will be
done and no matter if you already had previously added that member to the ArrayList because array
lists don't care if there is duplicated data or not.

How would I check each item in my arraylist to see if the values are being added when a new activity
is started?

You have to iterate your array list with a for or a for-each cicle and then print that member name as a
log entry.

 For-each cicle
 F or (String member : members){
 Log.i("Member name: ", member);

121
}

 Simple For cicle


 int listSize = members.size();

 for (int i = 0; i<listSize; i++){
 Log.i("Member name: ", members.get(i));
}

If you try to print/ log a value which index is out of range, i.e., i < 0 || i >= listSize then a
IndexOutOfBoundsException will be thrown and crash your app.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

http://blog.softeq.com/2012/12/using-pre-populated-
sqlite-database-in.html - good tutorial for SQLite datab ase
handling
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Populating a ListView using ArrayList?


You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection)
to your items in your layout (ListView, Spinner etc.).

This is what the Android developer guide says:

A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class
expects that the provided resource id references a single TextView. If you want to use a more
complex layout, use the constructors that also takes a field id. That field id should reference a
TextView in the larger layout resource. However the TextView is referenced, it will be filled with the
toString() of each object in the array. You can add lists or arrays of custom objects. Override the
toString() method of your objects to determine what text will be displayed for the item in the list. To
use something other than TextViews for the array display, for instance, ImageViews, or to have some
of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the
type of view you want.

So your code should look like:

public class YourActivity extends Activity {

private ListView lv;

public void onCreate(Bundle saveInstanceState) {


setContentView(R.layout.your_layout);

122
lv = (ListView) findViewById(R.id.your_list_view_id);

// Instanciating an array list (you don't need to do this,


// you already have yours).
List<String> your_array_list = new ArrayList<String>();
your_array_list.add("foo");
your_array_list.add("bar");

// This is the array adapter, it takes the context of the activity as a


// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
your_array_list );

lv.setAdapter(arrayAdapter);
}
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Insert and Retrieve Values from a List (ArrayList)

This Java program does the followings

1. Inserts values into an ArrayList

2. Retrieve the values of ArrayList using Iterator

3. Retrieve the values of ArrayList using get method

4. Retrieve the values of ArrayList using Enumeration

Java Program
1 import java.util.ArrayList;
import java.util.Collections;
2 import java.util.Enumeration;
3 import java.util.Iterator;
4 import java.util.List;
5
6 public class ArrayListDemo
7 {
8
public static void main(String args[])
9 {
10 List list = new ArrayList();

123
11
12 //Adding values to the ArrayList
13 list.add("test1");
list.add("test2");
14 list.add("test3");
15
16 System.out.println("Retrieving values from ArrayList using Iterator");
17 retrieveValuesFromListMethod1(list);
18 System.out.println("**********************\n\n");
19
20 System.out.println("Retrieving values from ArrayList using get
method");
21
retrieveValuesFromListMethod2(list);
22 System.out.println("**********************\n\n");
23
24 System.out.println("Retrieving values from ArrayList using
25Enumeration");
26 retrieveValuesFromListMethod3(list);
27 System.out.println("**********************\n\n");
}
28
29
30 /*This method retrieves values from ArrayList using Iterator
31 */
32 public static void retrieveValuesFromListMethod1(List list)
33 {
34 Iterator itr = list.iterator();
while(itr.hasNext())
35
{
36 System.out.println(itr.next());
37 }
38 }
39
40 /*This method retrieves values from ArrayList using get method
41 */
public static void retrieveValuesFromListMethod2(List list)
42 {
43 //Retrieving values from list
44 int size = list.size();
45 for(int i=0;i<size;i++)
46 {
System.out.println(list.get(i));
47 }
48 }
49
50
51 /*This method retrieves values from ArrayList using Enumeration
52 */
53 public static void retrieveValuesFromListMethod3(List list)
{
54
Enumeration e = Collections.enumeration(list);
55 while(e.hasMoreElements())
56 {
57 System.out.println(e.nextElement());
58 }

124
59
60 }
61
62}
63
64
65
66
67
68
69

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Setting background colour of Android layout


element
You can use simple color resources, specified usually inside res/values/colors.xml.
<color name="red">#ffff0000</color>
and use this via android:background="@color/red" . This color can be used anywhere else too,
e.g. as a text color. Reference it in XML the same way, or get it in code
via getResources().getColor(R.color.red).
You can also use any drawable resource as a background,
use android:background="@drawable/mydrawable" for this (that means 9patch drawables, normal
bitmaps, shape drawables, ..).

125
Center a button in a Linear layout
If you want to center an item in the middle of the screen don't use a LinearLayout as these are
meant for displaying a number of items in a row.
Use a RelativeLayout instead.
So replace:

android:layout_gravity="center_vertical|center_horizontal"
for the relevant RelativeLayout option:
android:layout_centerInParent="true"
So your layout file will look like this:

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<ImageButton android:id="@+id/btnFindMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/findme"></ImageButton>

</RelativeLayout>

????????????????????????????????????????????????????????????????????
Set button's parent linear layout gravity to center

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/white"
android:orientation="horizontal"
android:gravity="center">

<Button
android:id="@+id/okbutton"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:text="SET"
android:gravity="center"
android:textSize="50sp" />

</LinearLayout>

126

You might also like