Shortcuts (Most Useful)

Quick Keys (Essential!)

Alt+Enter - Quick import
Tab - Auto Finish

Search Keys

Shift+Shift — Search Every Where
Ctrl+F — Find Text with in a Single File
Ctrl+Shift+F - Find Text in All Files
Ctrl+R — Replace Selected Text in a Single File
Ctrl+Shift+R — Replace Selected Text in all Files (Be Careful while Using This)
Ctrl+Shift+A — Search for IDE Commands

Ctrl+N — Navigate to Class
Ctrl+Shift+N — Navigate to a File
Ctrl+B — Jump to Declareations
Alt+ ↑ — Jump to Previous Method
Alt+↓ — Jump to Next Method
Ctrl+G — Jump to Line
Ctrl+E — Recent Files
Ctrl+Shift+Back Space — Jump to Last Edited Location
Ctrl+B — Find Declarations
Ctrl+Left Mouse(or)Ctrl+Alt+F7— Show Usage
Alt + F7 / Ctrl + F7 — Find usages /Find usages in file
Ctrl+Shift+B — Find Implementations
F3 — Find Next
Shift+F3 — Find Previous

Selection Keys

Ctrl + W — Extend selection (selects a word->line->method->Class )
Ctrl +Shift+ W — Decrease Selection
Alt + J — Select next occurrence
Ctrl + Alt + Shift + J — Select all occurrences
Alt + Shift + J — Unselect occurrence
Ctrl+Shift+V — Paste from recent buffers (from a History of Copied Contents)

Editing Keys

Ctrl+F6 -Refractor Code
Ctrl+D — Duplicate a Line/Selected part
Ctrl+Y — Delete a Line/Selected part
Ctrl+Q — Quick Documentation
Ctrl + Space — Code completion
Ctrl+Shift+Space — Smart code completion (by expected type removes unrelated suggestions)
Alt+Insert — Generate Code
Ctrl+J — Insert Live template
Ctrl + O — Override methods
Ctrl + I — Implement methods
Ctrl + Alt + T — Surround with…
Ctrl + / — Comment / uncomment with line comment
Ctrl + Shift + / — Comment / uncomment with block comment
Ctrl+Alt+L — Reformat code

Run

Ctrl + F9 — Compile and Run Make project
Ctrl + Shift + F9 — Compile selected file, package or module
Shift + F10 — Run
Shift + F9 — Debug
Ctrl + Shift + F10 — Run context configuration from editor

Debugging

F8 / F7 — Step over / into
Shift + F7 / Shift + F8 — Smart step into/Step out
Alt + F9 — Run to cursor
Alt + F8 — Evaluate expression
F9 — Resume program
Ctrl + F8 — Toggle break point
Ctrl + Shift + F8 — View breakpoints

https://developer.android.com/reference/android/util/Log.html

Common Different Types of Logs

  • Log.e - Error log shows issues that have caused errors
  • Log.w - Warning (possible issues) that are not yet errors
  • Log.i - Info log messages for regular usage
  • Log.d - Debug log messages that are useful during development only
  • Log.v - Verbose (all) log messages (the default)

Connect Android device to Android Studio

Tutorial Here

TLDR:

What you need:

  • Android Studio
  • USB cable
  • Android device

Steps:

  1. Enable USB debugging of your Phone
  2. Run your app on Android Studio

Quick way to implement buttons

More Info

In your xml file:

1
2
3
4
5
6
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btn"
android:onClick="onClickBtn" />

In your class of the java file:

1
2
3
4
5
public void onClickBtn(View v) //The function name can be changed
{
Toast.makeText(this, "Clicked on Button", Toast.LENGTH_LONG).show(); //Dummy code
//Code Here
}

Read Write Data Example

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.example.max.iopractice;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
private TextView mesg;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mesg = findViewById(R.id.mesg);
}

public void write1(View view){
String data = "Hello,World\n";
try{
FileOutputStream fos = openFileOutput("MyData.txt",MODE_PRIVATE);
fos.write(data.getBytes());
fos.flush();
fos.close();
}catch (java.io.IOException e){
e.printStackTrace();
}
}

public void write2(View view){
String data = "Hello,World\n";
try{
FileOutputStream fos = openFileOutput("MyData.txt",MODE_APPEND);
fos.write(data.getBytes());
fos.flush();
fos.close();
}catch (java.io.IOException e){
e.printStackTrace();
}
}

public void read(View view){
try{
FileInputStream fis = openFileInput("MyData.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine())!= null){
builder.append(line + "\n");
}
mesg.setText(builder);
}catch (java.io.IOException e){
e.printStackTrace();
}
}
}

GPS Map Example

AndroidManifest.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.max.lab10">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key"/>

<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

MapsActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package com.example.max.lab10;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

/*
DISTANCE DID NOT WORK AS EXPECTED.
*/

private GoogleMap mMap;

// =========== Step 1: Add markers, latlng, and button objects below ================

Marker markerParis, markerLondon, markerNewYork, homeMarker;
LatLng HongKong, Paris, London, NewYork;
Button btnParis, btnLondon , btnNewYork;


// =========== Step 1: Add markers, latlng, and button objects above ================



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

// Setting cities' coordinates
initializingCity();

btnParis = (Button) findViewById(R.id.Paris);
btnLondon = (Button) findViewById(R.id.LN);
btnNewYork = (Button) findViewById(R.id.NY);

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

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

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


// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

//=====Step 2: Map Setup Code Below =============================
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);

mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
@Override
public boolean onMyLocationButtonClick() {
homeMarker = mMap.addMarker(new MarkerOptions().position(HongKong).title("Hong Kong").snippet("Population: 8.0M"));

//shift my camera animation
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(HongKong,10));
return false;
}
});

mMap.addMarker(new MarkerOptions().position(HongKong).title("Hong Kong"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(HongKong));


//======Step 2: Map Setup Code Above=============================
}

// Step 3: Initialize city coordinates
private void initializingCity(){
HongKong = new LatLng(22.2783,114.1747);
Paris = new LatLng(48.8567, 2.3508);
London = new LatLng(51.518815, -0.1275);
NewYork = new LatLng(40.713723, -74.012640);


}

//Step 4: Code for user's button click response

private void goLondon() {
// Code for actions when btnLondon is clicked
mMap.clear();
double distance = computeDistance(London);
String distMsg = "Distance from HK: " + distance + "Km";

markerLondon = mMap.addMarker(new MarkerOptions().position(London).title("London").snippet("Population: 8.308M"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(London,10));
Toast.makeText(getApplicationContext(),distMsg,Toast.LENGTH_LONG).show();

}

private void goNewYork() {
// Code for actions when btnNewYork is clicked
mMap.clear();
double distance = computeDistance(NewYork);
String distMsg = "Distance from HK: " + distance + "Km";

markerNewYork = mMap.addMarker(new MarkerOptions().position(NewYork).title("NewYork").snippet("Population: 19M"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(NewYork,10));
Toast.makeText(getApplicationContext(),distMsg,Toast.LENGTH_LONG).show();

}



private void goParis() {
// Code for actions when btnParis is clicked
mMap.clear();
double distance = computeDistance(Paris);
String distMsg = "Distance from HK: " + distance + "Km";

markerParis = mMap.addMarker(new MarkerOptions().position(Paris).title("Paris").snippet("Population: 2.2M"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(Paris,10));
Toast.makeText(getApplicationContext(),distMsg,Toast.LENGTH_LONG).show();

}

// Step 5: Compute the actual spherical distance between 2 cities on earth
private double computeDistance(LatLng dest) {
int R = 6731; // earth radius in km
double dLat = Math.toRadians(HongKong.latitude-dest.latitude);
double dLng = Math.toRadians(HongKong.longitude-dest.longitude);
double lat1 = Math.toRadians(dest.latitude);
double lat2 = Math.toRadians(HongKong.longitude);

double a = Math.pow((dLat/2),2) + Math.pow(Math.sin(dLng/2),2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return (int)Math.round(R * c);

}

}

TextToSpeech Example

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package com.example.max.texttospeech;

import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.Locale;


public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{


Button btnTalk;
TextToSpeech tts;
EditText talkText;
Spinner languageChoice;
float pitch = -0.7f;
float rate = 1f;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnTalk = findViewById(R.id.btnTalk);
talkText = findViewById(R.id.talkText);
languageChoice = findViewById(R.id.languageChoice);

addListenerOnSpinner();
addListenerOnBtnTalk();
}

private void addListenerOnBtnTalk() {
btnTalk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

String content = talkText.getText().toString();
speechOut(content);

}
});

}

private void addListenerOnSpinner() { //Static Spinner
languageChoice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(adapterView.getContext(),"Selected Language:"
+ adapterView.getItemAtPosition(i).toString(),Toast.LENGTH_SHORT).show();

String Text = adapterView.getSelectedItem().toString();
if(Text.equals("English")) {
int result = tts.setLanguage(Locale.UK);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
Log.e("TTS","Initialization Failed");
}
}
else if(Text.equals("Cantonese")) {
int result = tts.setLanguage(new Locale("yue", "HK"));
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
Log.e("TTS","Initialization Failed");
}
}
else if(Text.equals("Chinese")) {
int result = tts.setLanguage(Locale.TRADITIONAL_CHINESE);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
Log.e("TTS","Initialization Failed");
}
}
else if(Text.equals("Japanese")) {
int result = tts.setLanguage(Locale.JAPANESE);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
Log.e("TTS","Initialization Failed");
}
}
else if(Text.equals("German")) {
int result = tts.setLanguage(Locale.GERMAN);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
Log.e("TTS","Initialization Failed");
}
}
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});

}


@Override
public void onInit(int i) {
if(i == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.UK);
tts.setPitch(pitch);
tts.setSpeechRate(rate);

if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
Log.e("TTS","Initialization Failed");
}

}
}

@Override
protected void onStart() {
super.onStart();
tts = new TextToSpeech(this,this);
}

@Override
protected void onStop() {
super.onStop();
tts.shutdown();
}

private void speechOut(String msg){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
tts.speak(msg,TextToSpeech.QUEUE_FLUSH,null,null);
else
tts.speak(msg,TextToSpeech.QUEUE_FLUSH,null);
}
}

TCP Example

Really simple TCP client
Sending TCP data from Android (as client) - no data being sent?