Saturday, November 21, 2020

Java basics - part 1

This is the very beginning of a JAVA programming series, which covers basics, important points regarding sequence, selection, iteration, std in, std out, and lot more.

This post contains some important thins regarding Java language, and most of them are coming as learning outcomes from "Hackerrank" Java problem solving.

Std Input

import scanner class

import java.util.Scanner;
 
Then use like below 

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
String s = scan.nextLine();
 
do{
String st1=scan.nextLine();

System.out.println(count + " " + st1);
count += 1;
}while(
scan.hasNext());

while(
scan.hasNext()){
// String st1=scan.nextLine();
st1 =
scan.nextLine();
System.out.println(count + " " + st1);
count += 1;
 
scan.close();
 

Std Output

Use standard output to send to terminal
 
System.out.println("String val: " + stringVariable );
System.out.println("Double val: " + Double.toString(doubleVariable) );
System.out.println("Integer val: " + Integer.toString(integerValue) );
 
 

If - else if - else, Switch, shorthand if  

// if - else if - else
if(intVar > 100){
    System.out.println(">100");
}
else if(intVar >= 80){
    System.out.println(">=80");
}
else{
    System.out.println("<80");
}
 
// shorthand
resultVar = (intVar > 100) ? ">100" : ( (intVar >= 80) ? ">=80" : "<80" );
System.out.println(resultVar);
 
// switch - case
switch(someInteger){
    case 1:
        System.out.println("equals 1");
        break;
    case 2:
        System.out.println("equals 2");
        break;
    case 5:
        System.out.println("equals 5");
        break;
    default:
        System.out.println("default value");
}
 

formatting output with printf

// 15 chars left is a string, right aligning integer with 3 digits
System.out.printf("%-15s%03d\n", stringVar, intVar);
 

Type casting

// double to int 
int var1 = (int)( Math.pow(2, c)*b ); 
int var1 = new Double(Math.pow(2, c)*b).intValue() 
 
// int to String
String var3 = Integer.toString(intValue);
String var4 = String.valueOf(intValue);
 
// String to char array
char[] arr = stringVar.toCharArray(); 
 

Static Initializer

public class Javaclass{
    static boolean flag = false;
    static int B=0;
 
    // this part executes before the main method
    static {
        System.out.print("Inside static initializer");
     Scanner sc = new Scanner(System.in);
    B = sc.nextInt();
  flag = true;
    }
 
    public static void main(String[] args){
        if(flag){
            // do something
        }
    
 

Currency formatting

create a NumberFormat 
NumberFormat cf 
 
If currency for your locale is available, get it 
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US) 
 
or create a new locale
Locale my_locale = new Locale("en", "LK"); // LK for Sri Lanka, extended from "en"
NumberFormat nf = NumberFormat.getCurrencyInstance(my_locale);
 
Then use the NumberFormat to print double value as a currency
double doubleValue = 20.3; // 0.22, 40, 2,45
System.out.print( nf.format(doubleValue) );
 

Probable Prime

BigInteger bigIntInstance = new BigInteger(n);
boolean isPrime = bigIntInstance.isProbablePrime(1);
 
Let's meet with the next post
Thanks for the reading
   

Saturday, October 24, 2020

How to use React Event Emitter 3

Install event emitter using this command

npm install --save eventemitter3  

This is npm page for the package we are going to use.

https://www.npmjs.com/package/eventemitter3 

Let's be patient while this npm package installed. And we are ready to proceed.

It is better if we create this event emitter related code in a one file. It is plain javascript file, emitter.js in my case.

import EventEmitter from 'eventemitter3';
const eventEmitter = new EventEmitter();
const Emitter = {
  on: (event, fn) => eventEmitter.on(event, fn),
  once: (event, fn) => eventEmitter.once(event, fn),
  off: (event, fn) => eventEmitter.off(event, fn),
  emit: (event, payload) => eventEmitter.emit(event, payload),
};
Object.freeze(Emitter);
export default Emitter;


So now we can import this event emitter (emitter.js) to any component like below

import Emitter from '<path-to-event-emitter>/emitter';

 

Now let's assume we need to fire an event based on some condition. We can emit event like in below code.

Emitter.emit(SOME_CONSTANT_EVENT_NAME_ONE, {data_object_for_the_called_function} );

 

And also we need to an event listener for this SOME_CONSTANT_EVENT_NAME_ONE. We can define that event listener in another file or same file, as defined below.

useEffect( () => {
    Emitter.on(SOME_CONSTANT_EVENT_NAME_ONE, someFunction);
    return () => {
      Emitter.off(SOME_CONSTANT_EVENT_NAME_ONE, someFunction);
    };
} )

someFunction = (data) => {
    // do something with data
}

 

That's the very simple example of using React event emitter3. We can emit and catch multiple events using different event names (like SOME_CONSTANT_EVENT_NAME_ONE).

The main advantage taken from the event emitter was communicating changes happened in a component to another component, in projects where Redux is not used. And those communicating components were far way in the component hierarchy.

Monday, May 4, 2020

Develop android applications with react-native, without installing android studio - Troubleshooting

 In this previous post we discussed about hot to install Android SDK without installing Android Studio. It is pretty much sure most of the audience couldn't complete it without facing some difficulties. This post contains the Questions and answer help for few problems you could face.

Q: Keystore file '/<project-root>/android/app/debug.keystore' not found for signing config 'debug'
A: https://github.com/facebook/react-native/issues/25629 contains this answer. You have to go <project-root>/android/app/ and run this command

keytool -genkey -v -keystore debug.keystore -storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000
and run npx react-native run-android warning-mode=all

Q: Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point to the according directory,
I have installed jdk 8 and java & javac commands also working
A: add "JAVA_HOME" system variable as "C:\Program Files\Java\jdk1.8.0_241" matching with your installation folder
Open a new terminal and try npx react-native run-android warning-mode=all

Q: I was debugging my application in real device, next time I started debugging, it fails to start debug application in the device
A: uninstall the previous installation and start debugging script in the machine
adb shell pm uninstall <your-package-name>
ex: adb shell pm uninstall com.abc
Then re-run npx react-native run-android warning-mode=all

Q. Still I cant start my debugging session
We need to retry with some advanced cleaning
adb shell pm uninstall <your-package-name>
cd <project-root>/android
.\gradlew clean
npm install --save-dev jetifier
npx jetify
npx react-native run-android warning-mode=all 


Q. Making the production release
.\gradlew clean
.\gradlew assembleRelease 


Q. Vector icons not rendered, unknown square symbol
goto: android/app/build.gradle
add: apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"








Q. Error: rngesturehandlermodule.default.direction
open android/app/src/main/java/com/ks2/MainActivity.java
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

// after protected String getMainComponentName()
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
  return new ReactActivityDelegate(this, getMainComponentName()) {
    @Override
    protected ReactRootView createRootView() {
      return new RNGestureHandlerEnabledRootView(MainActivity.this);
    }
  };
}


Saturday, May 2, 2020

Develop android applications with react-native, without installing android studio

As a React-Native developer it is not mandatory to use Android Studio to develop applications. And some people don't like to install Android Studio since it consumes lot of system resources. But it is must to have 'Android SDK tools' installed in our machine to build android applications. So we are going to install 'Android SDK tools' without installing 'Android Studio'.

I used windows 10 as my development environment in this tutorial.

Pre-requisites:
You can refer this post if you encounter problems during this tutorial

I used the 'Android-SDK-tools' zip archive, and extracted in a folder in 'C:\' drive.
Then add these items to 'system variable'.
ANDROID_HOME : 'Android-SDK-tools' zip extracted location
ANDROID_SDK_ROOT : 'Android-SDK-tools' zip extracted location






Now edit PATH variable, add (append) path to 'platform-tools' folder as below



After that open a new 'powershell window' and make sure`java`, `javac`, `adb` commands are working.

Now open SDK manager and download required SDK packages. I used https://github.com/Starotitorov/tic-tac-toe to this demonstration.






Now you can see the codebase for our 'tictactoe' app, and we need to run it in android environment. I used an actual device, which is enabled the USB debugging, since it was hard to run an emulator in my machine.
  • Run `npm install`
  • Run `npx react-native run-android`
`npx react-native run-android` it is expected to start downloading all the necessary files required for Android and Gradle, and making the app-debug.apk and install it on the device.

It is good to use `npx react-native run-android warning-mode=all` to get a detailed description of the app debugging status.

Did you get any errors when running the Android application? Check this post for the FAQ related with running react-native application. This contains answers for the following problems,
  • Keystore file '/<project-folder>/android/app/debug.keystore' not found for signing config 'debug' 
  • Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point to the according directory
  • Emulator or device not found error