Android: Passing Objects between Activities

most of the times you would need to pass a POJO object through some activities to make sure you have everything related to a sample topic in one place as an OOP best practice. so to pass an object between some activities you need to do something like this …

inside the first activity you need to create your POJO and then add that to the nextScreen, then you need to make sure your POJO can be serialized, and then in nextScreen Activity read that POJO back and after unmarshaling back to the object shape read its content.
Step #1:

for example, I have a component that enables the app to start reading the QR code like this method.

public class Home extends AppCompatActivity implements View.OnClickListener {

private static MyObj obj1 = new MyObj();

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

}


public void onActivityResult(int requestCode, int resultCode, Intent intent) {

IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

if (scanningResult != null) {

String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();

Intent nextScreen = null;
if (isInFieldPath) {
nextScreen = new Intent(getApplicationContext(), FieldOptionMenu.class);

} else {
nextScreen = new Intent(getApplicationContext(), LabOptionMenu.class);
}

nextScreen.putExtra("format", scanFormat);
nextScreen.putExtra("content", scanContent);

polioData.setQrCodeContent(scanContent);
polioData.setQrCodeFormat(scanFormat);
nextScreen.putExtra("MySimpleObj",obj1);

startActivity(nextScreen);


} else {
Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}

}

Step #2:

you need to implement below items inside your POJO to make that serializable in android.


public class MyObject implements Parcelable {

private String something = "Navidamo Navidam";


public MyObject() {
super();
}

protected MyObject(Parcel in) {
something = in.readString();

}

public String getUsername() {
return something;
}

public void setUsername(String something) {
this.something = something;
}



// writing and serialization process

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(something);

}

//reading back to object from serilization process - unmarshaling data
public static final Creator<MyObject> CREATOR = new Creator<MyObject>() {
@Override
public MyObject createFromParcel(Parcel in) {
return new MyObject(in);
}

@Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};


}

Step #3:

and inside the destination activity simply use the below lines wherever you can get the intent.

MyObject obj = (MyObject) getIntent().getParcelableExtra("MySimpleObj");
Toast.makeText(getApplicationContext(),
obj.getSomething() + "wiht out bundle", Toast.LENGTH_LONG).show();

//            one way of getting data from Extra
//            Bundle bundle = getIntent().getExtras();
//            obj = (MyObject) bundle.getParcelable("MySimpleObj");
//            Toast.makeText(getApplicationContext(),
//                    obj.getSomething() + "with bundle", Toast.LENGTH_LONG).show();

 

Spring @Scope

in Spring frameworks, sometimes you need to take control of beans scope, in that case you can add AOP jar files which will come if you use BOM, and Context set of dependencies and then easily use the @Scope annotation on beans. Below is a set of bean scope available in Spring:

  • Singleton = only one object in entire Spring container
  • prototype = a new object per every time calling applicationContext.getBean(…)
  • web based bean scope:
    • request // a new object per request – a little bit longer than prototype since that was being called by getbean method every time.
    • session // an object per session and will be renewed whenever we hit the timeout for that session
    • globalsession // an object for entire application

example:


@service("myservice")

@scope("singleton") // this is the default bean scope
//or using this @Scope(ConfirgurableFactoryBean.SCOPE_SINGLETON)

public class MyServiceImple extends MyService{

//....

}

 

 

Optional DataType JDK 8

how do you normally do a NULL check inside the java application. if you’re using older jdk, just using the if to check whether the object is null or not, something like below …

 

if(myObject != null){
... // do something
}

by using new JDK 8, there is a wrapper class that could wrap object type and basically provides some features for developers and in simple words, do the heavy lifting internally, make the code compact and more readable.

 

please check below example.


Optional<MyDataType> returnedInstance = myObjInstance.getMeSomething();

 

Notes:
1. mechanism to check whether the return type contains the NULL pointer exception or not.
2.decrease the null pointer exception thrown by the application.
3. due to suggestion by openJDK mailing list — only use the Optional in return tye
3.a: still needed to check for input params for functions and methods inside the classes.
4. Checked exception can be used with Optional to handle and signal the entier application whenever the unexpected status would be met.
5. something like this …
Optional<TypeIAmExpecting> = getMySomething(String input);

ifPresent() — return true if value is not null and would be presented.
orElse(defultValue);
get(); — get the value
isPresent() — check in ifelse statement and ha get() or handle the no-exited stateus.

when to use: as return type

 

 

Testing in Java Part 1 – Basics

Different types of testing:

  1. System test / End to End test normally will be done via QA
  2. Aggregate Test / testing component to make sure the business functionalities with all the dependencies could be done as they supposed to. it took longer than unit test since it has a database to set up and tear down, or clean up some stuff, etc.
  3. Unit test / testing each individual functionality. no dependencies.

 

3 Stages every test case needs to have:

  1.  prepare the environment for testing (preparing any requirement before actually testing the behaviour – it might happen in every method.)
  2. the behaviour to test (the actual function you want to test – if that’s too big, you’re testing a lot of functionalities and if something happened you need a way to find that between that complex tests)
  3. checking the result (Assertions)

making testing in orders might make dependencies between unit tests which don’t have any meaning other than, Aggregate testing instead of testing every individual function.

NOTE: every test methods in your test class, should only test one behaviour, even if preparing and function parts of couple test methods will be similar but and the differences will be in assertion parts, then it might show that you are testing differents parts/ behaviours of the function.

NOTE: Make your test methods names, expressing the behaviour of testing, make sure they expose what you want to test.

NOTE: One test class for one Class object.

NOTE: testing the throwing of an exception in the case of a failure of the application?

<br data-mce-bogus="1">

<strong>@Test(Expected=MyTypeOfException.class)</strong>

&nbsp;

 

 

 

 

Data Structure – Merge Sort

under divide and conquer algorithms in sort category, we are reaching to Merge Sort, which basically

  1. Takes the input array and BREAK/DIVIDE it into half.
  2. call the same BREAK/DIVIDE function on the smaller halves , again – RECURSIVE function, with a base condition of array.size =1
  3. array.size() = 1 counted as SORTED. now rebuilding.
  4. in the time of rebuilding process for the smaller chunk of data, we are using previous smaller chunk in each step, meaning, smaller sorted data as a result of last previous recursive call.
  5. and then rebuild the array after sorting the smaller previous parts.

NOTE: in this sorting algorithm, we need a copy of the array, in a merging process and that’s the tricky part.

 big picture:

we have two main function in Merge Sort

  1. Partitioning(array, startIndex, endIndex) // breaking into pieces
  2. Merging(array, startIndex, midIndex, endIndex) // sorting and rebuilding

/**
* breaking the array into smaller pieces, RECURSIVE happened here.
*
* @param arrSRC
* @param startIndex
* @param endIndex
*/
public void partitioning(int[] arrSRC, int startIndex, int endIndex) {

System.out.println("Begin Dividing/Breaking by this array...");
showContent(arrSRC, startIndex, endIndex);

if (endIndex - 1 == startIndex) {
System.out.println("Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.");
return;
}

System.out.println("Dividing/Breaking - into smaller chunk - Finding Mid Index.");
int mid = (startIndex + endIndex) / 2;

System.out.printf("Dividing/Breaking - into smaller chunk -  startIndex: %d - endIndex: %d = midIndex:%d\n", startIndex, endIndex, mid);

partitioning(arrSRC, startIndex, mid);
partitioning(arrSRC, mid, endIndex);

doMerge(arrSRC, startIndex, mid, endIndex);

}

/**
* do the actual merge/build task.
*
* @param arrSrc
* @param startIndex
* @param mid
* @param endIndex
*/
private void doMerge(int[] arrSrc, int startIndex, int mid, int endIndex) {

//tricky partitioning in MERGE SORT since we need a semi-sorted array which was made in previous recursive function call.
System.out.println("Begin Conquering/ building array again...");

arrayCopy(arrSrc, tempArr, startIndex, endIndex);

int leftIndex = startIndex;
int rightIndex = mid;
int index = startIndex;

while (leftIndex < mid && rightIndex < endIndex) {
if (tempArr[leftIndex] <= tempArr[rightIndex]) {

arrSrc[index] = tempArr[leftIndex];
leftIndex++;

} else {
arrSrc[index] = tempArr[rightIndex];
rightIndex++;
}
index++;
}

while (leftIndex < mid) {
arrSrc[index] = tempArr[leftIndex];
leftIndex++;
index++;
}
while (rightIndex < endIndex) {
arrSrc[index] = tempArr[rightIndex];
rightIndex++;
index++;
}

System.out.print("Final Result ... \n\t ");
showContent(arrSrc, startIndex, endIndex);
System.out.println("");

}

Orders:

in the worst case scenario O(N x LogN), since it’s breaking the target into a smaller chunk. so it’s good for large unsorted data sets.

when to use?

when you want to do the sort in a multi-thread environment so every thread can do one part of sorting and then one manager thread can stick the parts together.

how to implement?


package com.navid.ds.practice.sorting.divideconqure;

/**
*
* @author Unknown_
*/
public class MergeSort {

public static int[] myArray = new int[]{10, 2, 5, 20, 90, 12, 31, 5};
private static int[] tempArr = null;

public MergeSort() {

tempArr = new int[myArray.length];

}

/**
* breaking the array into smaller pieces, RECURSIVE happened here.
*
* @param arrSRC
* @param startIndex
* @param endIndex
*/
public void partitioning(int[] arrSRC, int startIndex, int endIndex) {

System.out.println("Begin Dividing/Breaking by this array...");
showContent(arrSRC, startIndex, endIndex);

if (endIndex - 1 == startIndex) {
System.out.println("Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.");
return;
}

System.out.println("Dividing/Breaking - into smaller chunk - Finding Mid Index.");
int mid = (startIndex + endIndex) / 2;

System.out.printf("Dividing/Breaking - into smaller chunk -  startIndex: %d - endIndex: %d = midIndex:%d\n", startIndex, endIndex, mid);

partitioning(arrSRC, startIndex, mid);
partitioning(arrSRC, mid, endIndex);

doMerge(arrSRC, startIndex, mid, endIndex);

}

/**
* do the actual merge/build task.
*
* @param arrSrc
* @param startIndex
* @param mid
* @param endIndex
*/
private void doMerge(int[] arrSrc, int startIndex, int mid, int endIndex) {

//tricky partitioning in MERGE SORT since we need a semi-sorted array which was made in previous recursive function call.
System.out.println("Begin Conquering/ building array again...");

arrayCopy(arrSrc, tempArr, startIndex, endIndex);

int leftIndex = startIndex;
int rightIndex = mid;
int index = startIndex;

while (leftIndex < mid && rightIndex < endIndex) {
if (tempArr[leftIndex] <= tempArr[rightIndex]) {

arrSrc[index] = tempArr[leftIndex];
leftIndex++;

} else {
arrSrc[index] = tempArr[rightIndex];
rightIndex++;
}
index++;
}

while (leftIndex < mid) {
arrSrc[index] = tempArr[leftIndex];
leftIndex++;
index++;
}
while (rightIndex < endIndex) {
arrSrc[index] = tempArr[rightIndex];
rightIndex++;
index++;
}

System.out.print("Final Result ... \n\t ");
showContent(arrSrc, startIndex, endIndex);
System.out.println("");

}

/**
* This array Copy method is just an effort to expose the
*
* @param arrSrc
* @param arrDest
* @param lowerIndex
* @param higherIndex
*/
public void arrayCopy(int[] arrSrc, int[] arrDest, int lowerIndex, int higherIndex) {

for (int i = lowerIndex; i < higherIndex; i++) {
arrDest[i] = arrSrc[i];
}

}

public void showContent(int[] arr, int start, int end) {

System.out.print("[ ");
for (int i = start; i < end; i++) {
System.out.printf("%d, ", arr[i]);

}
System.out.println(" ]");
}

public static void main(String[] args) {

MergeSort ms = new MergeSort();

ms.partitioning(myArray, 0, myArray.length);

}

}

 

 

output

run:
Begin Dividing/Breaking by this array...
[ 10, 2, 5, 20, 90, 12, 31, 5,  ]
Dividing/Breaking - into smaller chunk - startIndex: 0 - endIndex: 8 = midIndex:4
Begin Dividing/Breaking by this array...
[ 10, 2, 5, 20,  ]
Dividing/Breaking - into smaller chunk - startIndex: 0 - endIndex: 4 = midIndex:2
Begin Dividing/Breaking by this array...
[ 10, 2,  ]
Dividing/Breaking - into smaller chunk - startIndex: 0 - endIndex: 2 = midIndex:1
Begin Dividing/Breaking by this array...
[ 10,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Dividing/Breaking by this array...
[ 2,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Conquering/ building array again...
Final Result ... 
     [ 2, 10,  ]

Begin Dividing/Breaking by this array...
[ 5, 20,  ]
Dividing/Breaking - into smaller chunk - startIndex: 2 - endIndex: 4 = midIndex:3
Begin Dividing/Breaking by this array...
[ 5,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Dividing/Breaking by this array...
[ 20,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Conquering/ building array again...
Final Result ... 
     [ 5, 20,  ]

Begin Conquering/ building array again...
Final Result ... 
     [ 2, 5, 10, 20,  ]

Begin Dividing/Breaking by this array...
[ 90, 12, 31, 5,  ]
Dividing/Breaking - into smaller chunk - startIndex: 4 - endIndex: 8 = midIndex:6
Begin Dividing/Breaking by this array...
[ 90, 12,  ]
Dividing/Breaking - into smaller chunk - startIndex: 4 - endIndex: 6 = midIndex:5
Begin Dividing/Breaking by this array...
[ 90,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Dividing/Breaking by this array...
[ 12,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Conquering/ building array again...
Final Result ... 
     [ 12, 90,  ]

Begin Dividing/Breaking by this array...
[ 31, 5,  ]
Dividing/Breaking - into smaller chunk - startIndex: 6 - endIndex: 8 = midIndex:7
Begin Dividing/Breaking by this array...
[ 31,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Dividing/Breaking by this array...
[ 5,  ]
Dividing/Breaking - into smaller chunk - found only one item in array, so it's counted as SORTED.
Begin Conquering/ building array again...
Final Result ... 
     [ 5, 31,  ]

Begin Conquering/ building array again...
Final Result ... 
     [ 5, 12, 31, 90,  ]

Begin Conquering/ building array again...
Final Result ... 
     [ 2, 5, 5, 10, 12, 20, 31, 90,  ]

BUILD SUCCESSFUL (total time: 0 seconds)

 

Data Structure – Selection Sort

in this sort, it’s very much like bubble sort since in bubble the largest element should be in the RIGHT side, in Selection sort we are looking for SMALLEST items and select that then find its proper location which will be the most LEFT side and REPLACE it with whatever in that location.

still, LEFT side is smallest and right side has the largest, but the number os swaps are decreased however to find the proper location we have to do a lot of comparisons.

Orders:

  • the worst case scenario O(N^2)
  • average case scenarios O(N^2) –> but in practice
  • Selection sort is better than Bubble sort,
  • Selection sort is worse than Insertion sort,
  •  best case scenario O(N^2) — since it has lots of comparisons.

where to use:

  • not good for large unsorted data sets, and in General.
  • since it has a few swaps N, it might be good in cases where the cost of Comparisons is cheaper than swaps.
  • from space and memory perspectives, since it’s working on the array, itself, it’s good.

how to code:

/**
*
* @author Navid_
*/
public class SelectionSort {

public static int[] myArray = new int[]{10, 2, 5, 20, 90, 12, 31, 5};

/**
* resetting array content to what it was.
*/
public static void resetData() {
myArray = new int[]{10, 2, 5, 20, 90, 12, 31, 5};
}

/**
* showing content of array
*
* @param arr
*/
public void showContent(int[] arr) {

System.out.print("[ ");
for (int i : arr) {
System.out.printf("%d, ", i);
}
System.out.println(" ]");
}

public static void main(String[] args) {
SelectionSort ss = new SelectionSort();

ss.showContent(SelectionSort.myArray);
ss.sort(SelectionSort.myArray);
ss.showContent(SelectionSort.myArray);

}

public void sort(int[] myArray) {

for (int i = 0; i < myArray.length; i++) {
//find smallest
int smallestIndex = searchToFindSmallest(myArray, i, myArray.length);

// now repalce the smallest with the next item in the unsorted array
swap(myArray, smallestIndex, i);

showContent(myArray);
}

}

/**
* smallest item index will be returned.
*
* @return
*/
public int searchToFindSmallest(int[] arr, int startSearch, int limitSearch) {

int smallest = startSearch;
boolean foundSthNew = false;
for (int index = startSearch; index < limitSearch; index++) {
if (arr[index] < arr[smallest]) {
// so we find something smaller
System.out.printf("Found a samllest item ... arr[%d]=%d\n",index,arr[index] );
smallest = index;
foundSthNew = true;
}
}

if (foundSthNew) {

return smallest;
} else {
return -1;
}
}

private void swap(int[] myArray, int smallestIndex, int i) {

int tmp = 0;
if (smallestIndex == -1) {
System.out.println("no swapping anymore.\n");
return;
}
tmp = myArray[i];
myArray[i] = myArray[smallestIndex];
myArray[smallestIndex] = tmp;
System.out.printf("Swapping arr[%d]=%d with arr[%d]=%d\n",i,myArray[i],smallestIndex,myArray[smallestIndex]);
}

}

and it’s output will be something like this …

run:
[ 10, 2, 5, 20, 90, 12, 31, 5,  ]
Found a samllest item ... arr[1]=2
Swapping arr[0]=2 with arr[1]=10
[ 2, 10, 5, 20, 90, 12, 31, 5,  ]
Found a samllest item ... arr[2]=5
Swapping arr[1]=5 with arr[2]=10
[ 2, 5, 10, 20, 90, 12, 31, 5,  ]
Found a samllest item ... arr[7]=5
Swapping arr[2]=5 with arr[7]=10
[ 2, 5, 5, 20, 90, 12, 31, 10,  ]
Found a samllest item ... arr[5]=12
Found a samllest item ... arr[7]=10
Swapping arr[3]=10 with arr[7]=20
[ 2, 5, 5, 10, 90, 12, 31, 20,  ]
Found a samllest item ... arr[5]=12
Swapping arr[4]=12 with arr[5]=90
[ 2, 5, 5, 10, 12, 90, 31, 20,  ]
Found a samllest item ... arr[6]=31
Found a samllest item ... arr[7]=20
Swapping arr[5]=20 with arr[7]=90
[ 2, 5, 5, 10, 12, 20, 31, 90,  ]
no swapping anymore.
[ 2, 5, 5, 10, 12, 20, 31, 90,  ]
no swapping anymore.
[ 2, 5, 5, 10, 12, 20, 31, 90,  ]
[ 2, 5, 5, 10, 12, 20, 31, 90,  ]
BUILD SUCCESSFUL (total time: 0 seconds)

Data Structure – Insertion Sort

it’s similar to bubbleSort, but it happened only in 1 PASS

by comparing every two items from left to right in array, pull one item from array then find its proper place and insert it there, then shift the rest of items – normally it would be SORTED items.

LEFT considered SORTED

items in RIGHT side considered UNSORTED.

when to use:

  • small datasets
  • nearly sorted large datasets
  • because the number of comparisons and swaps is relatively small.

orders:

  • very similar to  bubble sort
  • O(N^2) in worst case and average case
  • and for large semi-sorted data or small datasets we can say O(N)

space:

doesn’t need more data spaces so it can be done in the same place or in devices with minimum spaces.

how to implement:


/**
*
* @author Navid_
*/
public class InsertionSort {

public static int[] arr = new int[]{5, 10, 13, 90, 1};

public void sort(int[] array) {

int tmp = 0;
for (int i = 0; i + 1 < array.length; i++) { //loop through array if (array[i] >= array[i + 1]) {
// find the guy that needs to be inserted somewhere
System.out.printf("found an item to sort...array[%d] = %d\n", i + 1, array[i + 1]);
tmp = array[i + 1]; // save the unsorted guy
for (int k = i + 1; k >= 0; k--) {

//just handling when the first item is still larger than temp;
if (k == 0) {

System.out.printf("shifting to the RIGHT = %d and REPLACING the FIRST item in array with = %d, then BREAK.\n", array[k], tmp);
array[k] = tmp;
showContent(array);
break;
}

// trying to find the location and insert
if (array[k - 1] > tmp) {
System.out.printf("SHIFT to RIGHT= %d.\n", array[k - 1]);
array[k] = array[k - 1];
showContent(array);
} else {
System.out.printf("Found Place to INSERT so inserting ... array[%d] = %d.\n", k - 1, tmp);
array[k - 1] = tmp;
showContent(array);
break;
}

}

}

}

}

/**
* resetting array content to what it was.
*/
public static void resetData() {
//        myArray = new int[]{10, 2, 5, 20, 90, 12, 31, 5};
arr = new int[]{5, 10, 13, 90, 1};
}

/**
* showing content of array
*
* @param arr
*/
public void showContent(int[] arr) {

System.out.print("[ ");
for (int i : arr) {
System.out.printf("%d, ", i);
}
System.out.println(" ]");
}

public static void main(String[] args) {

InsertionSort is = new InsertionSort();

is.showContent(InsertionSort.arr);
is.sort(InsertionSort.arr);
is.showContent(InsertionSort.arr);

}

}

and its output will be something like this …

run:
[ 5, 10, 13, 90, 1,  ]
found an item to sort...array[4] = 1
SHIFT to RIGHT= 90.
[ 5, 10, 13, 90, 90,  ]
SHIFT to RIGHT= 13.
[ 5, 10, 13, 13, 90,  ]
SHIFT to RIGHT= 10.
[ 5, 10, 10, 13, 90,  ]
SHIFT to RIGHT= 5.
[ 5, 5, 10, 13, 90,  ]
shifting to the RIGHT = 5 and REPLACING the FIRST item in array with = 1, then BREAK.
[ 1, 5, 10, 13, 90,  ]
[ 1, 5, 10, 13, 90,  ]
BUILD SUCCESSFUL (total time: 0 seconds)

NOTE:

so for small amount of items you can still