logo

Java for Android - Documentation and Code Snippets

All you need to create Android app in Java.

Java Syntax

Primitive Data Types:

  • byte
  • short
  • int
  • long
  • float
  • double
  • char
  • boolean

Java Operators:

  • Arithmetic: + , - , * , ? , %
  • Assignment: = , -= , += , *= , /= , %= , &= , ^= , |= , <<= , >>= , >>>=
  • Bitwise: ^ , & , |
  • Logical: && , ||
  • Relational: < , > , <= , >= , == , !=
  • Shift: << , >> , >>>
  • Ternary: ?:
  • Unary: ++x , --x , x++ , x-- , +x , -x , ! , ~

Java Code Snippets

Class Implementation

public class MyClass {

 public String mString;
 private int mInt;
 // More member variables

 // Constructor for Class
 public MyClass() {
 mString = “Foo”;
mInt = 10;
 }
 // More methods...
}
                

Methods

public int doIt() {
 return 0;
}
public int doIt(int a) {
 return a;
}
public int doIt(int a, int b) {
 return a+b;
}
                

Creating/Using an Instance

SomeObject a = new SomeObject();
a.getMemberVariable();
a.doIt();
a.doIt(1);
a.doIt(2,3);
Declaring Variables
double doubleVar = 1.0
doubleVar = 2.0
int intVar = 1;
String stringVar = “Hey”;
Boolean truth = true;
                

Variable Types

int 1, ,2, 500, 10000
floatdouble 1.5, 3.14, 578.234
boolean true, false
string "Abanoub", "John", "Samy"
ClassName Activity, TextView, .. etc

Control Flow

Boolean condition = true;
if (condition) {
} else {
}
int val = 5;
switch (val) {
 case 1:
 break;
 case 2:
 break;
 default:
 break;
}
for (int i = 0; i < 5; i++) {
}
                

String Quick Example

String personOne = "Ray";
String personTwo = "Brian";
String combinedString = personOne + ": Hello, " + personTwo + "!";
String tipString = "2499.00";
Int tipInt = Integer.parseInt(tipString);
double tipDouble = Double.parseDouble(tipString);
                

Array Quick Examples

String personOne = "Ray";
String personTwo = "Brian";
String [] array = {personOne, personTwo};
for(String person : array) {
 Log.d("person:", person);
}
String ray = array[0];
                

Dictionary Quick Examples

HashMap<String, String> map = new
HashMap<>();
map.put(“personOne”,”Ray”);
// updates old value if already exists
map.put(“personOne”,”Brian”);
map.put(“personTwo”,”Darryl”);
// remove value for key
map.remove(“personOne”);
// iterate through map
for(Map.Entry<String, String>
personEntry : map.entrySet()) {
Log.d(personEntry.getKey(),
personEntry.getValue());
}
                

Java Code Snippets/Code Samples for Android

How to get file from assets in Java on Android

//the function to get the file as a string
public String loadData(String inFile) {
 String tContents = "";
 try {
    InputStream stream = getAssets().open(inFile);
    int size = stream.available();
    byte[] buffer = new byte[size];
    stream.read(buffer);
    stream.close();
    tContents = new String(buffer);
 } catch (IOException e) {
    // Handle exceptions here
 }
 return tContents;
}
//calling the function
getFileFromAssets("test.html");
//or (any file)
getFileFromAssets("test.txt");
                

How to copy text to clipboard on Android in Java

//initialize the button & editText in OnCreate()
Button copyBtn = findViewById(R.id.copyBtn);
EditText toCopy = findViewById(R.id.etCopy);

//when you click the copy-button this methon/function is fired
copyBtn.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
     //the copy2clipboard function called with the text of the editText
     copy2Clipboard(toCopy.getText().toString());
  }
});
//the function to copy any text passed in
void copy2Clipboard(CharSequence text){
  ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
  ClipData clip = ClipData.newPlainText("copy text", text);
  if (clipboard != null){
     clipboard.setPrimaryClip(clip);
  }
  Toast.makeText(this," text copied", Toast.LENGTH_LONG).show();
}
                

Get the first n characters of a string

//s -> the string
//n -> the n of characters
//upToNCharacters -> the final string
String upToNCharacters = s.substring(0, Math.min(s.length(), n));
                

How to save file on Android in Java

//add those permissions to manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

//call the function
saveFile(getApplicationContext(), "filename", "the content of the file itself");

//you can use "this" instead of "getApplicationContext()"
saveFile(this, "anotherFileName", "content of the file 2");

//saveFile function
public void saveFile(Context mcoContext,String sFileName, String sBody){

 File file = new File(mcoContext.getFilesDir(),"CVApp");

 if(!file.exists()){
    file.mkdir();
 }

 try{
    File gpxfile = new File(file, sFileName);
    FileWriter writer = new FileWriter(gpxfile);
    writer.append(sBody);
    writer.flush();
    writer.close();
 }catch (Exception e){
    e.printStackTrace();
 }
}
                

How to implement merge sort algorithm in Java

package Sorts;

import static Sorts.SortUtils.print;

class MergeSort implements SortAlgorithm {

    @Override
    @SuppressWarnings("unchecked")
    public <T extends Comparable<T>> T[] sort(T[] unsorted) {
        T[] tmp = (T[]) new Comparable[unsorted.length];
        doSort(unsorted, tmp, 0, unsorted.length - 1);
        return unsorted;
    }

    private  static <T extends Comparable<T>> void doSort(T[] arr, T[] temp, int left, int right) {
        if (left < right) {
            int mid = left + (right - left) / 2;
            doSort(arr, temp, left, mid);
            doSort(arr,  temp,mid + 1, right);
            merge(arr, temp, left, mid, right);
        }
   }

    private static <T extends Comparable<T>> void merge(T[] arr, T[] temp, int left, int mid, int right) {
        System.arraycopy(arr, left, temp, left, right - left + 1);


        int i= left;
        int j = mid + 1;
        int k = left;

        while (i <= mid && j <= right) {
            if (temp[i].compareTo(temp[j]) <= 0) {
                arr[k++] = temp[i++];
            }
            else {
                arr[k++] = temp[j++];
            }
        }

        while (i <= mid) {
            arr[k++] = temp[i++];
        }

	while (j <= right) {
	    arr[k++] = temp[j++];
	}
    }

    // Driver program
    public static void main(String[] args) {

        // Integer Input
        Integer[] arr = {10, 9, 8, 4, 5, 6, 13, 55, 72, 86, 100, 123, 7, 3, 2, 1};
        MergeSort mergeSort = new MergeSort();
        mergeSort.sort(arr);

        // Output => 1	   4  	 6	9	12	23	54	78	231
        print(arr);

        // String Inpu
        // String[] stringArray = {"c", "a", "e", "b","d"};
        // mergeSort.sort(stringArray);
        // Output => a	b	c	d	e
        // print(stringArray);
    }
}
                

Finally

This documentation and code snippets will be updated monthly.