Quantcast
Channel: CoderzHeaven
Viewing all 526 articles
Browse latest View live

Android’s new D8 dexer

$
0
0

Google has now come up with a new compiler for Android, the D8. This one is basically improved and efficient compared to the DX compiler.

Google had shipped the D8 compiler along with Android Studio 3.0 with a opt-in feature.
In the initial phase the default compiler would be DX, then Google will deprecate it in later phase.

If you want to use D8 in you builds, then modify your gradle.properties with this

android.enableD8 = false

You can read more about DX here…
File any issue related to DX in here


AutoConnect to Wi-Fi in iOS

$
0
0

Apple has introduced a new API in iOS 11 where you can directly connect to a Wi-Fi from with-in the app.

For this code to work
1. you need to enable the networking capabilities in your provisioning profile.
2. Once you enable the networking profile in the provisioning profile, you need to regenerate and sign the app with the new one.
3. Now in the Xcode, go to the capabilities and enable the “Networking Capabilities”.
4. If you want to publish this code in the AppStore, then you need to get the permission from the app.

Now use the below code. It should prompt the user to connect to the particular Wi-Fi.
You will get a callback when the connection is complete or you will get error.

This code works on iOS 11 only. For any version less than 11, user needs to manually connect.

if (@available (iOS 11.0, *)) {
    
    NEHotspotConfiguration * configuration = 
                [[NEHotspotConfiguration alloc] initWithSSID: wifiSSID];
    configuration.joinOnce = YES;
    
    /* Alert the OS that the user wants to connect to the WiFi */
    [[NEHotspotConfigurationManager sharedManager] 
                      applyConfiguration: configuration 
                      completionHandler: ^ (NSError * _Nullable error) {
      if (nil == error) {
        DLog (@ "Is Connected!!");
      } else {
        DLog (@ "Error is:%@", error);
    }}];
    
}

You need to test this on a real device. not a simulator.

You can read more about this here…
https://developer.apple.com/documentation/networkextension/nehotspotconfiguration

How to encrypt and decrypt an audio file in Android?

$
0
0

Here is a simple example to encrypt and decrypt a audio file in Android.

We will directly go to the implementation part.

Demo Video

You can check the demo video here.

Download Library

You can download the simple library from here.

Aim

  • Download an audio file from internet.
  • Encrypt and save the encrypted file in Disk, so that no one can open it.
  • Decrypt the same file.
  • Play the file.

Classes

For accomplishing the above tasks we have the below utility files.

  • EncryptDecryptUtils – The file which encrypt and decrypts a file.
  • FileUtils – This file is used for file operations.
  • PrefUtils – For saving the key.
  • Player – For playing the audio.

You would probably need the first three classes for encrypt and decrypting any type of files, not only the audio files.
Encryption and Decryption will return the file contents in terms of bytes.

Lets check how the EncryptDecryptUtils looks like

EncryptDecryptUtils


import android.content.Context;
import android.util.Base64;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.CIPHER_ALGORITHM;
import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.KEY_SPEC_ALGORITHM;
import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.OUTPUT_KEY_LENGTH;
import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.PROVIDER;

/**
 * Created by James From CoderzHeaven on 5/2/18.
 */

public class EncryptDecryptUtils {

    public static EncryptDecryptUtils instance = null;
    private static PrefUtils prefUtils;

    public static EncryptDecryptUtils getInstance(Context context) {

        if (null == instance)
            instance = new EncryptDecryptUtils();

        if (null == prefUtils)
            prefUtils = PrefUtils.getInstance(context);

        return instance;
    }

    public static byte[] encode(SecretKey yourKey, byte[] fileData)
            throws Exception {
        byte[] data = yourKey.getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length, KEY_SPEC_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, PROVIDER);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        return cipher.doFinal(fileData);
    }

    public static byte[] decode(SecretKey yourKey, byte[] fileData)
            throws Exception {
        byte[] decrypted;
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, PROVIDER);
        cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        decrypted = cipher.doFinal(fileData);
        return decrypted;
    }

    public void saveSecretKey(SecretKey secretKey) {
        String encodedKey = Base64.encodeToString(secretKey.getEncoded(), Base64.NO_WRAP);
        prefUtils.saveSecretKey(encodedKey);
    }

    public SecretKey getSecretKey() {
        String encodedKey = prefUtils.getSecretKey();
        if (null == encodedKey || encodedKey.isEmpty()) {
            SecureRandom secureRandom = new SecureRandom();
            KeyGenerator keyGenerator = null;
            try {
                keyGenerator = KeyGenerator.getInstance(KEY_SPEC_ALGORITHM);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            keyGenerator.init(OUTPUT_KEY_LENGTH, secureRandom);
            SecretKey secretKey = keyGenerator.generateKey();
            saveSecretKey(secretKey);
            return secretKey;
        }

        byte[] decodedKey = Base64.decode(encodedKey, Base64.NO_WRAP);
        SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, KEY_SPEC_ALGORITHM);
        return originalKey;
    }

}

FileUtils

Helps in file related operations.


import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.DIR_NAME;
import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.FILE_EXT;
import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.FILE_NAME;
import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.TEMP_FILE_NAME;

/**
 * Created by James From CoderzHeaven on 5/6/18.
 */

public class FileUtils {

    public static void saveFile(byte[] encodedBytes, String path) {
        try {
            File file = new File(path);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bos.write(encodedBytes);
            bos.flush();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static byte[] readFile(String filePath) {
        byte[] contents;
        File file = new File(filePath);
        int size = (int) file.length();
        contents = new byte[size];
        try {
            BufferedInputStream buf = new BufferedInputStream(
                    new FileInputStream(file));
            try {
                buf.read(contents);
                buf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return contents;
    }

    @NonNull
    public static File createTempFile(Context context, byte[] decrypted) throws IOException {
        File tempFile = File.createTempFile(TEMP_FILE_NAME, FILE_EXT, context.getCacheDir());
        tempFile.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tempFile);
        fos.write(decrypted);
        fos.close();
        return tempFile;
    }

    public static FileDescriptor getTempFileDescriptor(Context context, byte[] decrypted) throws IOException {
        File tempFile = FileUtils.createTempFile(context, decrypted);
        FileInputStream fis = new FileInputStream(tempFile);
        return fis.getFD();
    }

    public static final String getDirPath(Context context) {
        return context.getDir(DIR_NAME, Context.MODE_PRIVATE).getAbsolutePath();
    }

    public static final String getFilePath(Context context) {
        return getDirPath(context) + File.separator + FILE_NAME;
    }

    public static final void deleteDownloadedFile(Context context) {
        File file = new File(getFilePath(context));
        if (null != file && file.exists()) {
            if (file.delete()) Log.i("FileUtils", "File Deleted.");
        }
    }

}

PrefUtils

Helps in saving the values in preferences.


import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.SECRET_KEY;

public class PrefUtils {

    public static final PrefUtils prefUtils = new PrefUtils();
    public static SharedPreferences myPrefs = null;

    public static PrefUtils getInstance(Context context) {
        if (null == myPrefs)
            myPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        return prefUtils;
    }

    public void saveSecretKey(String value) {
        SharedPreferences.Editor editor = myPrefs.edit();
        editor.putString(SECRET_KEY, value);
        editor.commit();
    }

    public String getSecretKey() {
        return myPrefs.getString(SECRET_KEY, null);
    }
}

Player

Helps in MediaPlayer related operations.


import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;

import java.io.FileDescriptor;

/**
 * Created by James from CoderzHeaven on 5/7/18.
 */

public class Player implements MediaPlayer.OnCompletionListener {

    private MediaPlayer mediaPlayer;
    private Handler handler;

    public Player(Handler handler) {
        this.handler = handler;
    }

    private void initPlayer() {
        if (null == mediaPlayer) {
            mediaPlayer = new MediaPlayer();
        }
    }

    public void play(FileDescriptor fileDescriptor) {
        initPlayer();
        stopAudio();
        playAudio(fileDescriptor);
    }

    public void playAudio(FileDescriptor fileDescriptor) {
        mediaPlayer.reset();
        try {
            mediaPlayer.setOnCompletionListener(this);
            mediaPlayer.setDataSource(fileDescriptor);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {
        }
    }

    private void stopAudio() {
        if (null != mediaPlayer && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        Message message = new Message();
        message.obj = "Audio play completed.";
        handler.dispatchMessage(message);
    }

    private void releasePlayer() {
        if (null != mediaPlayer) {
            mediaPlayer.release();
        }
    }

    public void destroyPlayer() {
        stopAudio();
        releasePlayer();
        mediaPlayer = null;
    }
}

MainActivity

Finally the main activity that does the implementation.
The layout for the activity is pasted below.

package encrypt_decrypt.coderzheaven.com.encryptdecryptandroid;

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

import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.PRDownloader;

import java.io.FileDescriptor;
import java.io.IOException;

import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.DOWNLOAD_AUDIO_URL;
import static encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.Constants.FILE_NAME;

public class MainActivity extends AppCompatActivity implements OnDownloadListener, Handler.Callback {

    private Player player;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        player = new Player(new Handler(this));
    }

    public final void updateUI(String msg) {
        ((TextView) findViewById(R.id.statusTv)).setText(msg);
    }

    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.download:
                downloadAudio();
                break;
            case R.id.encrypt:
                if (encrypt()) updateUI("File encrypted successfully.");
                break;
            case R.id.decrypt:
                if (null != decrypt()) updateUI("File decrypted successfully.");
                break;
            case R.id.play:
                playClicked();
                break;
            default:
                updateUI("Unknown Click");
        }
    }

    private void playClicked() {
        try {
            playAudio(FileUtils.getTempFileDescriptor(this, decrypt()));
        } catch (IOException e) {
            updateUI("Error Playing Audio.\nException: " + e.getMessage());
            return;
        }
    }

    private void downloadAudio() {
        // Delete the old file //
        FileUtils.deleteDownloadedFile(this);
        updateUI("Downloading audio file...");
        PRDownloader.download(DOWNLOAD_AUDIO_URL, FileUtils.getDirPath(this), FILE_NAME).build().start(this);
    }

    /**
     * Encrypt and save to disk
     *
     * @return
     */
    private boolean encrypt() {
        updateUI("Encrypting file...");
        try {
            byte[] fileData = FileUtils.readFile(FileUtils.getFilePath(this));
            byte[] encodedBytes = EncryptDecryptUtils.encode(EncryptDecryptUtils.getInstance(this).getSecretKey(), fileData);
            FileUtils.saveFile(encodedBytes, FileUtils.getFilePath(this));
            return true;
        } catch (Exception e) {
            updateUI("File Encryption failed.\nException: " + e.getMessage());
        }
        return false;
    }

    /**
     * Decrypt and return the decoded bytes
     *
     * @return
     */
    private byte[] decrypt() {
        updateUI("Decrypting file...");
        try {
            byte[] fileData = FileUtils.readFile(FileUtils.getFilePath(this));
            byte[] decryptedBytes = EncryptDecryptUtils.decode(EncryptDecryptUtils.getInstance(this).getSecretKey(), fileData);
            return decryptedBytes;
        } catch (Exception e) {
            updateUI("File Decryption failed.\nException: " + e.getMessage());
        }
        return null;
    }

    private void playAudio(FileDescriptor fileDescriptor) {
        if (null == fileDescriptor) {
            return;
        }
        updateUI("Playing audio...");
        player.play(fileDescriptor);
    }

    @Override
    public void onDownloadComplete() {
        updateUI("File Download complete");
    }

    @Override
    public void onError(Error error) {
        updateUI("File Download Error");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.destroyPlayer();
    }

    @Override
    public boolean handleMessage(Message message) {
        if (null != message) {
            updateUI(message.obj.toString());
        }
        return false;
    }
}

Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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" android:animateLayoutChanges="true" android:orientation="vertical" android:padding="20dp" tools:context="encrypt_decrypt.coderzheaven.com.encryptdecryptandroid.MainActivity">

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="20dp" android:gravity="center" android:text="[ Tap the buttons in order for the demo ]" android:textColor="@android:color/holo_red_dark" />

    <Button android:id="@+id/download" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent" android:gravity="left|center" android:onClick="onClick" android:text="1. Download Audio" />

    <Button android:id="@+id/encrypt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent" android:gravity="left|center" android:onClick="onClick" android:text="2. Encrypt Audio" />

    <Button android:id="@+id/decrypt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent" android:gravity="left|center" android:onClick="onClick" android:text="3. Decrypt Audio" />

    <Button android:id="@+id/play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent" android:gravity="left|center" android:onClick="onClick" android:text="4. Play" />

    <TextView android:id="@+id/statusTv" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center" android:layout_weight="0.7" android:gravity="center" android:textColor="@android:color/holo_green_dark" android:textSize="20sp" />

    <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="bottom" android:layout_marginBottom="20dp" android:layout_weight="1" android:gravity="center" android:text="coderzheaven.com" />

</LinearLayout>

Source Code

You can download the complete source code from here.

Reverse a byte array in Android

$
0
0

Here is a simple function to reverse a byte array in android.

public static void reverse(byte[] array) {
        
        if (null == array) {
            return;
        }

        int i = 0;
        int j = array.length - 1;
        byte tmp;  
        while (j > i) {
            tmp = array[j];
            array[j] = array[i];
            array[i] = tmp;
            j--;
            i++;
    }
}

How to get the IP Address of the iOS Device?

$
0
0

Typically when an device is connected to WiFi, it will be assigned an IP. Here we will see how we can extract the IP of an iOS device.

Below is the sample code for that


#include <ifaddrs.h>
#include <arpa/inet.h>

// Returns the IPAddress of the device
+(NSString *) getDeviceIpAddress
{
  NSString *address = nil;
  struct ifaddrs *interfaces = NULL;
  struct ifaddrs *temp_addr = NULL;
  int success = 0;
  
  // retrieve the current interfaces - returns 0 on success
  success = getifaddrs(&amp;interfaces);
  if (success == 0)
  {
    
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL)
    {
      if(temp_addr->ifa_addr->sa_family == AF_INET)
      {
        // Check if interface is en0 which is the wifi connection on the iPhone
        if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
        {
          // Get NSString from C String
          address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
        }
      }
      
      temp_addr = temp_addr->ifa_next;
    }
  }
  
  // Free memory
  freeifaddrs(interfaces);
  
  NSLog(@"IP Address: %@", address);
  return address;
}

How to show a Snackbar in Flutter? iOS and Android.

$
0
0

Here is a simple example where the user clicks a button to show a Snackbar.
We know that there is no inbuilt snackbar for iOS. But Flutter makes it easy to do without any custom native code.

Flutter SnackBar in Android/iOS

You can see a Demo video here.

Here we use two main elements

  • Scaffold
  • Snackbar

The Scaffold Widget from the material library creates this visual structure for us and ensures important Widgets don’t overlap!. You can read more about Scaffold from here.

Snackbar is the class which helps you to show Snackbar widget in iOS/Android with a single code.

Lets see how it is done.
I am assuming that you have setup Flutter upfront.
If not, go to flutter.io and know more about Flutter.

InShort Flutter is a framework from Google with which you can create iOS/Android Mobile Applications with single source code using dart language.

Once you have created a new Flutter project.
I am using Android Studio for creating Flutter Project.

Once you have created the Flutter Project, navigate to lib/main.dart

Show SnackBar

final snackBar = new SnackBar(content: new Text('Yay! A SnackBar!'));

// Find the Scaffold in the Widget tree and use it to show a SnackBar
Scaffold.of(context).showSnackBar(snackBar);

But Gettign a Scaffold Widget can be messy sometimes.
But we have a solution here.

We will have a GlobalState like this.

final GlobalKey<ScaffoldState> mScaffoldState = new GlobalKey<ScaffoldState>();

Complete code

Have a look how the Scaffold is used.
We have wrapped the content inside a Scaffold and gave the key as the Global Scaffold.

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Snackbar Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Snackbar Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final GlobalKey<ScaffoldState> mScaffoldState = new GlobalKey<ScaffoldState>();

  void buttonClick() {
    final snackBar = new SnackBar(content: new Text('Yay! A SnackBar!'));
    mScaffoldState.currentState.showSnackBar(snackBar);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: mScaffoldState,
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new RaisedButton(
                child: const Text('Show Snackbar'),
                color: Theme
                    .of(context)
                    .accentColor,
                elevation: 4.0,
                splashColor: Colors.blueGrey,
                textColor: Colors.white,
                onPressed: () {
                  buttonClick();
                })
          ],
        ),
      ),
    );
  }
}

 

How Image Loading Libraries work in Android?

$
0
0

In this article, Lets find out how the image loading libraries like Picasso, Glide and Fresco works.

We know that images are the one which takes most of the space in our application either in App size or
the memory at runtime.

Also using large number of images often kicks off Garbage Collection (GC) Events.
The more number of GCs, the more your application is going to suffer.
Remember that when the GC is running, your application is not running, resulting in frame drops and
ultimately bad experience to the user.

Lets look at the problems while loading images and the solutions to solve it.

1. Out of Memory Error

This is the nightmare of Android Developers. The best solution is to load images based on the need.
Scale the images to what you need. All popular libraries scale the image to the image dimensions.
So when you scale the image, it takes lesser memory and no OOM error.

2. Threading

All popular libraries use threading mechanism to download and process bitmaps. They use ThreadPools to manage threads.
So they will have a pool of threads that gets reused every time. In that the threads will be reused and when done they are released to the pool.
If the ImageView is not visible to the user, then the thread gets cancelled and released to the pool. The pools will have size depending on the hardware
configuration of the device. So this approach will perform better on different spec devices.

3. Caching

This is one of the most important part of the library. The image downloaded are cached in the memory or in the disk. They will first check for
memory cache to load the image, if it is not present in the image cache, it checks for the disk cache, if the image is not present in the disk
cache, then the downloads starts from the internet.

4. Bitmap Reuse

The image loading libraries use a pool of Bitmaps. These gets used until the pool is full. The second thing is use of Bitmap that is released.
When a bitmap is ready for recycle, then it is pushed to the pool.
There is another option to reuse the Bitmap memory.
Use of inBitmap in Bitmap options helps reuse of the old bitmap.

Lets look at an example


   Bitmap bitmapOne = BitmapFactory.decodeFile(filePathOne);
   imageView.setImageBitmap(bitmapOne);

   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(filePathTwo, options);
   options.inMutable = true;
   options.inBitmap = bitmapOne;
   options.inJustDecodeBounds = false;
   
   Bitmap bitmapTwo = BitmapFactory.decodeFile(filePathTwo, options);
   imageView.setImageBitmap(bitmapTwo);

Reuse of memory and reusing the reference helps GC not to be triggered.

However inBitmap has some limitations.
Have a look at the below video for more information.

Simple way to create a Rounded Corner Image in Android

$
0
0

RoundRectCornerImageView

Rounded Image - Android


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;

public class RoundRectCornerImageView extends android.support.v7.widget.AppCompatImageView {

    private float radius = 14.0f;
    private Path path;
    private RectF rect;

    public RoundRectCornerImageView(Context context) {
        super(context);
        init();
    }

    public RoundRectCornerImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RoundRectCornerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        path = new Path();
        rect = new RectF();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        rect.set(0, 0, this.getWidth(), this.getHeight());
        path.addRoundRect(rect, radius, radius, Path.Direction.CW);
        canvas.clipPath(path);
        super.onDraw(canvas);
    }
}

Usage in XML

 <your_package.RoundRectCornerImageView 
      android:id="@+id/image" 
      android:layout_width="@dimen/thumbnail_dimension" 
      android:layout_height="@dimen/thumbnail_dimension" />

Done


Free Daily News App

$
0
0

Download our free news app and get instant news from popular news channels instantly.

Get the app from here…
https://play.google.com/store/apps/details?id=app.mobile.daily_news

Please download and leave your valuable feedback as well.

Why you will download this app?

  • Fast and efficient.
  • Incorporates news from all famous news channels.
  • Consumes minimal battery.
  • No intruding ads or notifications.
  • Completely free.

https://play.google.com/store/apps/details?id=app.mobile.daily_news

 

Daily News for you..
Download the app and get the latest news in your fingertips.

Daily news is a mobile application which will provide in one place all the breaking news and updates. It brings you all the latest , most essential news and images from India and all over the world. With enhanced speed and simplicity Daily News is the best reader available now. The app loads fast and offer a simple and clean reading experience which will make your eyes happy. It delivers a more evolved experience for reviewing updates from across the world.
It provides latest news and updates from leading news channels such as CNN ,BBC , NY TIMES , REUTERS ,FOCX NEWS, CNBC ,NDTV ,ESPN CRIC INFO etc. For getting more comfort it is divided into various categories such as Entertainment , Health , Life Style , Politics , Science , Sports , Technology , Travel , Business etc. This app asks you to select the categories of news you would be interested and delivers suggestions and notifications accordingly. It delivers timeless wisdom and let users share these updates to others.
Moreover it also offers light and dark theme options for your convenience. Because of utilizing modern technology it supplying high number of content in less time.

Watch the full app video here…

Top 10 most downloaded and used mobile apps

$
0
0

Studies show that we spend more time with our mobile devices every day, either working or enjoying our leisure time. And we use apps in these devices . But what are the ones that we use the most?

Sensor Tower is a company dedicated to the marketing of mobile applications, which periodically publishes a report that collects the most popular apps among users, based on its number of downloads.

Based on data collected this year by Sensor Tower, marketing company specialized in mobile apps, the list of the most widely used apps in the world is the following:

10. Netflix
The video service on demand for films and serials, and which has begun to produce its content as well as offering those of third parties, is an indisputable reference in the sector. Saying Netflix is almost like telling a synonym of video on your demand.

9. Twitter
The microblogging service is introducing new features to forced marches to try to capture new users, since, according to the statistics, it has remained stuck, and although in very remarkable figures, it is not progressing further, which is what finally ends counting on investors.

8. Spotify
We can say that it’s like the Netflix of the music on demand. The Swedish company became equal with sucg giants like Apple or Google, who also have their own music services. Although the significant pros of Spotify is that it is available on all platforms and in the cloud.

7. Uber
Controversial and famous in equal parts, it is prohibited in some countries or cities. Uber has emerged as one of the references of a new type of economy (known as shared) in which some trust as a model of a future in which robots could take most of the jobs that humans currently carry.

6. YouTube
A classic and great service based on the content created by the user, since anyone can upload a video to YouTube. It has caused a true viral phenomena, being this service responsible for a large part of the minting of the viral term in this regard.

5. Instagram
The first app in the list of Facebook. Overcoming Flickr, it became the social network of reference in the visual field, for the lovers of photography, creating a whole genre in itself. It is being watched, however, overcome by the first four numbers from our listing.

4. Snapchat
It is based on a postulate that, from good to first, may seem curious, but has proven to be terribly successful, especially among young Americans, which is where it began to spread like wildfire: the content, whether it be photographs or Videos, have an expiration date, and can be deleted automatically.

3. Facebook
The answer to the question – if anyone did it – why Mark Zuckerberg guys spend so much time not only on their mobile apps, but also bringing mobile Internet to the whole world? Because they are increasingly more Users who access the social network from their smartphones and, therefore, ask for an increasingly complete experience.

2. Messenger
Who is not Mark Zuckerberg’s social network yet on his cell phone? Although it is not obligatory to use the app, if we want to communicate with instant messaging (one of the “thanks” of Facebook, we are forced to install this other app.

1. WhatsApp
The ranking closes the instant messaging app owned by Facebook, thus closing an exclusive podium of Facebook, which places four of its mobile apps in the “top 5”.

WhatsApp is, for the operators (who have made a mistake to bring to the market another app that makes them the competition), the service that “killed” the SMS and, therefore, has received constant attacks for that reason from the industrial fabric.

Also criticized for its lack of security, lately the developers have added the encrypted message between its functionalities, as well as supporting sending among users of more types of files and adding options to connect to the service from one computer.

About the Author – Carol James is a writer and senior editor at papers writing company EssayLab. She has MA degree in social sciences and writes articles, reviews on the different actual subjects. So, if you have any questions regarding the writing, feel free to ask her.

 

Author:

Carol

All About React Native Animation

$
0
0

Animations are achieved in React Native using the Animation API.

Below are the methods

  • Animated.timing() — Maps time range to easing value.
  • Animated.decay() — starts with an initial velocity and gradually slows to a stop.
  • Animated.spring() — Simple single-spring physics model (Based on Rebound and Origami). Tracks velocity state to create fluid motions as the toValue updates, and can be chained together.

Here we are going to see all the below functions in Animated React Native

  • decay()
  • parallel()
  • timing()

We are jumping directly to the code…
Lets have all the variables for above animations in the constructor of the component.

  constructor(){
    super();
    this.spinValue = new Animated.Value(0)
    this.animatedValue = new Animated.Value(0)
    this.springValue = new Animated.Value(0.3)
    this.decayValue = new Animated.Value(0)

    // for Parallel animation
    this.animatedValue1 = new Animated.Value(0)
    this.animatedValue2 = new Animated.Value(0)
    this.animatedValue3 = new Animated.Value(0)
  }

Animation Functions

Below are the animations functions that you may want to apply to a view.

	 decay(){
		this.decayValue.setValue(0);
		Animated.decay(
		  this.decayValue,
		  {
			velocity: 0.01,
			useNativeDriver: true
		  }
		).start()
	  }

	  spring () {
		this.springValue.setValue(0.3)
		Animated.spring(
		  this.springValue,
		  {
			toValue: 1,
			friction: 1
		  }
		).start()
	  }

	  animate () {
		this.animatedValue.setValue(0)
		Animated.timing(
		  this.animatedValue,
		  {
			toValue: 1,
			duration: 2000,
			easing: Easing.linear
		  }
		).start(() => this.animate())
	  }

	  spin () {
		this.spinValue.setValue(0)
		Animated.timing(
		  this.spinValue,
		  {
			toValue: 1,
			duration: 4000,
			easing: Easing.linear
		  }
		).start(() => this.spin())
	  }

	  animateParellel () {
		this.animatedValue1.setValue(0)
		this.animatedValue2.setValue(0)
		this.animatedValue3.setValue(0)
		const createAnimation = function (value, duration, easing, delay = 0) {
		  return Animated.timing(
			value,
			{
			  toValue: 1,
			  duration,
			  easing,
			  delay
			}
		  )
		}
		Animated.parallel([
		  createAnimation(this.animatedValue1, 2000, Easing.ease),
		  createAnimation(this.animatedValue2, 1000, Easing.ease, 1000),
		  createAnimation(this.animatedValue3, 1000, Easing.ease, 2000)
		]).start()
	  }

Call the functions in the componentDidMount

  componentDidMount () {
    this.spin()
    this.animateParellel()
    this.decay();
    this.animate()
  }

Its that simple.
Please leave your valuable comments below.

Awesome React Native Image Caching Libraries

$
0
0

Image Loading and caching had been a little bit pain in react native.
In-fact react native didn’t had native support for caching.

But after the recent release, there is now support for caching in iOS only. Still not for Android.

You can read more about this from here
https://facebook.github.io/react-native/docs/images.html#cache-control-ios-only

<Image
  source={{
    uri: 'https://facebook.github.io/react/logo-og.png',
    cache: 'only-if-cached',
  }}
  style={{width: 400, height: 400}}
/>

Now these are the variety of options available.

default: Use the native platforms default strategy.
reload: The data for the URL will be loaded from the originating source. No existing cache data should be used to satisfy a URL load request.
force-cache: The existing cached data will be used to satisfy the request, regardless of its age or expiration date. If there is no existing data in the cache corresponding the request, the data is loaded from the originating source.
only-if-cached: The existing cache data will be used to satisfy a request, regardless of its age or expiration date. If there is no existing data in the cache corresponding to a URL load request, no attempt is made to load the data from the originating source, and the load is considered to have failed.

Libraries

Below are some third party libraries that does the same job, but it has support for both android and iOS.

1. React-native-cached-image

Example Source Code

import React from 'react';
import {
    CachedImage,
    ImageCacheProvider
} from 'react-native-cached-image';

const images = [
    'https://example.com/images/1.jpg',
    'https://example.com/images/2.jpg',
    'https://example.com/images/3.jpg',
    // ...
];

export default class Example extends React.Component {
    render() {
        return (
            <ImageCacheProvider
                urlsToPreload={images}
                onPreloadComplete={() => console.log('hey there')}>

                <CachedImage source={{uri: images[0]}}/>

                <CachedImage source={{uri: images[1]}}/>

                <CachedImage source={{uri: images[2]}}/>

            </ImageCacheProvider>
        );
    }
}

2. React Native Image Cache

import {CustomCachedImage} from "react-native-img-cache";

import Image from 'react-native-image-progress';
import ProgressBar from 'react-native-progress/Bar';

<CustomCachedImage
  component={Image}
  source={{ uri: 'http://loremflickr.com/640/480/dog' }} 
  indicator={ProgressBar} 
  style={{
    width: 320, 
    height: 240, 
  }}/>
  

You can explore more options from the respective pages.

How to Monitor network requests in a React Native/React Application?

$
0
0

So how do we normally monitor all the operations in a react native applications. All the networks, redux state etc.

So you will need a plugin/package for this. Its called Reactotron.

Here is the github page for Reactotron.

What is Reactotron?

A macOS, Windows, and Linux app for inspecting your React JS and React Native apps.

Use it to:

  • view your application state
  • show API requests & responses
  • perform quick performance benchmarks
  • subscribe to parts of your application state
  • display messages similar to console.log
  • track global errors with source-mapped stack traces including saga stack traces!
  • dispatch actions like a government-run mind control experiment
  • hot swap your app’s state using Redux or mobx-state-tree
  • track your sagas
  • show image overlay in React Native
  • track your Async Storage in React Native
  • You plug it into your app as a dev dependency so it adds nothing to your product builds.

Reactotron for React

Installation

You can follow this link for the installation intructions.

 

 

How to create a custom native ImageView/View in Android or iOS for ReactNative?

$
0
0

Many times we need custom components from native.

Here is a simple example on how to create a custom imageview in Android for react native.

First we will start with the Android Version

Android

  • Create a class that extends SimpleViewManager.
  • Write a setSrc method which accepts the source url from React Native.
  • Implement ‘createViewInstance’ method in which you can create the ImageView instance.
  • Listen for the setter to set the url and then start downloading the image.
  • Require the Native Component and set the import the ImageView just created from Native to React Native.
  • Pass the properties

and you are done.

Lets Start…

Java Class

Here is the complete class that creates the imageview and downloads the image.


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.image.ReactImageView;

import java.net.URL;

public class ReactImageManager extends SimpleViewManager<ReactImageView> {

    public static final String REACT_CLASS = "RCTImageView1";
    private final @Nullable
    Object mCallerContext = null;
    private ImgStartListener imgStartListener;

    /* Interface Listener to start loading the image if the source is set */
    private interface ImgStartListener {
        void startLoading(String imgUrl);
    }

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    /* Method which sets the source from React Native */
    @ReactProp(name = "src")
    public void setSrc(ReactImageView view, String uri) {
        imgStartListener.startLoading(uri);
    }

    @Override
    protected ReactImageView createViewInstance(ThemedReactContext reactContext) {

        final ReactImageView reactImageView = new ReactImageView(reactContext, Fresco.newDraweeControllerBuilder(), null, mCallerContext);

        final Handler handler = new Handler();
        imgStartListener = new ImgStartListener() {
            @Override
            public void startLoading(final String imgUrl) {
                startDownloading(imgUrl, handler, reactImageView);

            }
        };

        return reactImageView;
    }

    private void startDownloading(final String imgUrl, final Handler handler, final ReactImageView reactImageView) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(imgUrl);
                    final Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                    setImage(bmp, handler, reactImageView);
                } catch (Exception e) {
                    Log.e("ReactImageManager", "Error : " + e.getMessage());
                }
            }
        }).start();
    }

    private void setImage(final Bitmap bmp, Handler handler, final ReactImageView reactImageView) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                reactImageView.setImageBitmap(bmp);
            }
        });
    }
}

You can improve this view the way you want. This is only a simple implementation of an image.

Add to ViewManagers

Next step is to add this to a viewmanagers list.
Create a class named say “AnExampleReactPackage” and implement ReactPackage.
Add the above class to the ‘createViewManagers’ method.


import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.helloworld.ToastModule;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AnExampleReactPackage implements ReactPackage {

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Arrays.<ViewManager>asList(
                new ReactImageManager()
        );
    }

}

Add to MainApplication List

This is final step where you add the package so that React Native can detect your view.

public class MainApplication extends Application implements ReactApplication {

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    new VectorIconsPackage(),
                    // add here
                    new AnExampleReactPackage()
            );
        }

        @Override
        protected String getJSMainModuleName() {
            return "index";
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
    }
}

In React Native

Create a file named ‘ImageView.js’ and copy the below code into it.

import PropTypes from 'prop-types';
import {requireNativeComponent, ViewPropTypes} from 'react-native';

var iface = {
  name: 'ImageView',
  propTypes: {
    src: PropTypes.string,
    borderRadius: PropTypes.number,
    resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch']),
    ...ViewPropTypes, // include the default view properties
  },
};

module.exports = requireNativeComponent('RCTImageView1', iface);

Usage

  <ImageView
        src={ 'your_img_url' }
        style={{width: 100, height: 100}}
  />

Now we will look at ios. Here instead of creating an ImageView, I am creating just a view in iOS.

iOS

Create new Files inside your application say”NativeView”.

Create Cocoa Files NativeView.m and .h

Now open NativeView.h and copy this code

    #import <Foundation/Foundation.h>

    #import <React/RCTViewManager.h>

    @interface NativeView : RCTViewManager

    @end

RCTViewManager is the base class for view in React Native for iOS.

Now in NativeView.m

    #import "NativeView.h"

    @implementation NativeView

    RCT_EXPORT_MODULE()
    - (UIView *)view
    {
      UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
      view.backgroundColor = [UIColor blueColor];
      return view;
    }

    @end

Use it same like android

    import { requireNativeComponent } from 'react-native';

    // requireNativeComponent automatically resolves 'RNTMap' to 'RNTMapManager'

    module.exports = requireNativeComponent('NativeView', null);

How to extend styles in React-Native?

$
0
0

We will create different styles to style different components, correct?

And most of them will have duplicate elements, correct?

What are the disadvantages of this problem?

  • You will clutter your file with duplicate lines of code.
  • It will increase the file size and increase the application size.
  • Not very efficient way of coding.
  • Limited reusability.

How to fix that?

Example

Here I am going to style two text components and this is my style…

	const text1Style = {
	  fontFamily: myFont,
	  marginTop: '15%',
	  textAlign: 'center'
	  fontSize: 28,
	  fontWeight: 'bold'
	};

	const text2Style =  {
	  fontFamily: myFont,
	  marginTop: '15%',
	  textAlign: 'center'
	  marginBottom: '20%',
	  fontSize: 20
	};
  

Now what we can do to fix it?

Its simple…create a parent style and inherit from it. Its not hard as it seems…
The above code can be transformed like this.

	// Common style for two texts //
	const parentTextStyle = {
	  fontFamily: myFont,
	  marginTop: '15%',
	  textAlign: 'center'
	};

	const text1Style = {
	  ...parentTextStyle,
	  fontSize: 28,
	  fontWeight: 'bold'
	};

	const text2Style =  {
	  ...parentTextStyle,
	  marginBottom: '20%',
	  fontSize: 20
	};
  

In this way you can extend it to any number of components and even across the application by defining it in a styles file.

Render

The render will look like this

  render() {
    return (
      <View style={containerStyle}>
          <Text style={text1Style}>
              { text1 }
          </Text>
          <Text style={text2Style}>
              { text2 }
          </Text>
      </View>
    );
    

Much cleaner code. Thats it…
Please leave your valuable comments.


How to listen to events from react native?

$
0
0

Hi friends,

This is essentially a continuation of this post
http://www.coderzheaven.com/2018/08/10/how-to-create-a-custom-native-imageview-in-android-for-reactnative/

Now we will listen to a click event from the image we just created.

For that we have to add the ClickListener to the image in Android.

reactImageView.setOnClickListener(this); // implement the ClickListener to the class.

Add below methods to the java class

@Override
public void onClick(View v) {
WritableMap params = Arguments.createMap();
params.putInt("ID", v.getId());
sendEvent(reactContext, "clickEvent", params);
}

private void sendEvent(ReactContext reactContext,
String eventName,
@Nullable WritableMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}

On the React Native Side

DeviceEventEmitter.addListener("clickEvent", function(e: Event) {

alert("Clicked :: " + e.ID);

});

The whole java class will look like this.


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.image.ReactImageView;

import java.net.URL;

public class ReactImageManager extends SimpleViewManager&lt;ReactImageView&gt; implements View.OnClickListener {

public static final String REACT_CLASS = "RCTImageView1";
private final @Nullable
Object mCallerContext = null;
private ImgStartListener imgStartListener;
private Callback clickCallback;
private ThemedReactContext reactContext;

/* Interface Listener to start loading the image if the source is set */
private interface ImgStartListener {
void startLoading(String imgUrl);
}

@Override
public String getName() {
return REACT_CLASS;
}

/* Method which sets the source from React Native */
@ReactProp(name = "src")
public void setSrc(ReactImageView view, String uri) {
imgStartListener.startLoading(uri);
}

@Override
protected ReactImageView createViewInstance(ThemedReactContext reactContext) {
this.reactContext = reactContext;
final ReactImageView reactImageView = new ReactImageView(reactContext, Fresco.newDraweeControllerBuilder(), null, mCallerContext);
final Handler handler = new Handler();
imgStartListener = new ImgStartListener() {
@Override
public void startLoading(final String imgUrl) {
startDownloading(imgUrl, handler, reactImageView);

}
};

reactImageView.setOnClickListener(this);
return reactImageView;
}

private void startDownloading(final String imgUrl, final Handler handler, final ReactImageView reactImageView) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(imgUrl);
final Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
setImage(bmp, handler, reactImageView);
} catch (Exception e) {
Log.e("ReactImageManager", "Error : " + e.getMessage());
}
}
}).start();
}

private void setImage(final Bitmap bmp, Handler handler, final ReactImageView reactImageView) {
handler.post(new Runnable() {
@Override
public void run() {
reactImageView.setImageBitmap(bmp);
}
});
}

@Override
public void onClick(View v) {
WritableMap params = Arguments.createMap();
params.putInt("ID", v.getId());
sendEvent(reactContext, "clickEvent", params);
}

private void sendEvent(ReactContext reactContext,
String eventName,
@Nullable WritableMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}

}

Project Treble – Android Version Fragmentation Solved

$
0
0

Solved

Yes, a longtime problem with Android has been solved.
Yes, version fragmentation problem.

Version fragmentation is often Android from different manufacturers had been stuck on different versions which makes it difficult for developers to support all variety of devices. Hopefully the problem is going to be solved.

From Google’s perspective, an OS rollout is actually a three-stage process — starting first with Google, then progressing to the chipset vendor and finally to the phone-maker before reaching us, the users. In looking at those areas, Google realized it had an opportunity to streamline the process and make it more efficient.

And that’s where Treble began. With Oreo, Google laid the foundation by separating Android at the source level and creating a boundary between the main operating system and all that lower-level stuff. With Pie, Google filled in some missing pieces and worked closely with the chipset vendors to make sure they were ready for the new arrangement.

You can think of it like, well, a pie: In the past, all of Android was mixed together, and that meant each ingredient had to be updated and baked into the batter from scratch every single time an OS update came along. With Treble, all the hardware-specific elements exist as a crust — and that crust then remains in place for the life of a device. The phone-maker can then just focus on its part of the process without having to worry about waiting for someone else to provide and mix in an updated base with each new release.

Check if your Android 8.0+ Device Supports Project Treble

Enable USB Debugging for your device. Go to developer options in your device and enable it. Make sure it is available in “adb devices”.

Then, we’ll proceed to start the Android terminal inside ADB. For this, use:

  adb shell

then, use the following command:

  getprop ro.treble.enabled

if it returns true, great, your device supports project Treble.

This flag is needed by Google Play to detect devices which will support project treble and deliver vendor updates to the device.

8 things you need to know before becoming a blockchain developer

$
0
0

The blockchain is one of the fastest-growing markets in the entire IT industry. According to the report, the global blockchain technology market is predicted to reach $2.3 billion by 2021, creating a big demand for more engineers and software developers.

It obviously represents a colossal career potential for talented blockchain specialists. An average software developer in the US earns almost $80 thousand a year, but a blockchain-focused professional could easily go beyond $100 thousand.

If these figures deem interesting, you better start thinking about a career in this emerging industry. This post will show you 8 things you need to know before becoming a blockchain developer. Let’s take a look!

Figure out the blockchain basics
Before you delve deeper into programming, you need to understand how blockchain as a system functions. The subject is incredibly vast, but you can start with essentials such as:

Decentralization

The blockchain is not governed by any kind of central authority.

Immutability: Every little piece of information added to the chain of blocks remains the same forever.
Transparency: The technology is public, so everyone can see any info out there.

This is just a speck of the blockchain universe, which means you’ll have to invest a lot of time into basic research.

Check Out Online Courses

The Internet is a massive resource of blockchain-related learning materials, with online courses being the most productive way to gain knowledge about this industry. Before you enter the battlefield, we recommend you check out a couple of options.

Firstly, there is Udemy as an all-encompassing guide to the blockchain ecosystem. Taking this course, you can fully understand how the blockchain works, but you will also learn about other technologies that surround it.

Secondly, you can explore Coursera. This course will teach you about the cryptocurrency world. With Coursera, you can embrace the conceptual foundations needed to engineer secure software that interacts with the Bitcoin network.

Understand Data Structure

The blockchain is decentralized, and as such it requires a thorough understanding of data structure. You have to get acquainted with structures like Tree or Stack, but you also need to understand the issues of timing and resources.

Master a Programming Language

Skilled blockchain developers perfectly know at least one programming language. A majority of beginner-level engineers focus on C++ to enhance their crypto programming proficiency. However, there are dozens of options besides this one. For instance, you can take a look at JavaScript, Python, Perl, Solidity, or any other programming language that meet your needs in a given moment.

Learn Cryptography

Cryptography is one of the blockchain essentials that gives developers the possibility to protect digital assets. This is extremely important in the digital universe where users create incredible volumes of data each minute.

Given the fact that the value of all Bitcoins has reached over $1.2 trillion, you can easily figure out the importance of cryptography. And that’s not all since there are hundreds of other cryptocurrencies, while a bunch of other industries also depend on the blockchain technology.

Learn Distributed Computing
Distributed computing enables developers to design large-scale networks. Security plays a major role in this field since earlier versions of global networking – aka torrents – allowed peers to upload anything, including viruses and malicious software.

Things have changed with distributed computing because participants got a motive to contribute to network quality in the era of Bitcoin and other digital currencies. But the real investments in this field are still about to come. The system is not perfect yet, so it requires additional testing and more experts to work on it.

Learn Mechanism Design
Mechanism design establishes a connection between cryptography and distributed computing. It’s a model that has the purpose of creating more complex and secure algorithms. The goal is to involve as many peers as possible in the global crypto network such as Bitcoin. The more you learn about mechanism design, the easier it will be for you to design productive blockchain systems.

Familiarize with Development Platforms
There are dozens of development platforms to work on with your blockchain, with the most popular being Ethereum and NEO. The two platforms have slightly different objectives: while NEO promotes the digital business, Ethereum is more interested in developing blockchain systems.

The former is based on programming languages like JavaScript and C++, while Ethereum has its own program version called Solidity. You should check out both platforms and decide which one suits your professional interests more.

Conclusion
If you are thinking about building a career in blockchain development, you are not making a mistake. The new technology is growing rapidly, and you should seize the opportunity to capitalize on the expanding market.

In this post, we explained to you 8 things you need to know before becoming a blockchain developer. Keep our suggestions in mind and don’t hesitate to invest time and effort in learning – it can make you a superstar blockchain developer sooner than you think!

About author: Olivia is an incurable optimist who always sees the glass as half-full. She likes nature, knows how to enjoy silence and is keen on writing for various websites as well as for https://www.aussiewritings.com. Meet her on Twitter.

Things to Know About Mobile UX

$
0
0

Mobile user experience is not only related to design something to use on the mobile devices. It is a process that requires brainstorming, research and development to find out how you can better consider the UX and apply it in your UI.

Keep in mind that the number of mobile internet users is increasing day by day. So, improving the experience of mobile users is just as important as improving the experience of laptop or desktop users. You need to understand how mobile users behave first. Then you should find a good website design company to create an engaging experience for mobile users.

Understand the User Behavior Based On Mobile Device

Not every mobile user behaves the same way. While a Blackberry user responds better to mouse-like functionality, users of touchscreen smartphones will not return to that because they are used to ‘touch interface.’

When a user logs on to the internet through their mobile device, they tend to lose their patience much faster than they would if they were using a desktop. It’s a factor you cannot afford to overlook. If your site is slow, mobile users will consider it as a problem of the website and may even blame their internet connection!

If your web pages are stuffed with multimedia content, they will take more time to download.

But to prevent it you can found out this information in our guide on how images loading libraries work.

When Considering Longer Pages

Do not fill one page with all the content you have. Sure, mobile users are fine with scrolling down the web pages, but it does not mean you should pack every content into one page and offer it to your mobile users. It could yield a negative result for you.

Go creative

Find new ways to structure the content and present it in an appealing manner with things like accordion panels and drop down menus. However, if you have any problems with content writing then visit essays.vip to find writing tips.

Do Not Take All the Multimedia Away

Just because multimedia content takes time to download on mobile devices, you should not take all the multimedia away and leave the users with a plain text website. That would make the site load very fast, but that would also create a feeling of boredom as there will be no visual variety. For example, you can add the nice animation following our guide.

Mobile Internet Is Here to Stay

Yes. It is not some trend that will fade away with time. It is the future of internet surfing, downloading and everything we do on a desktop or laptop. So, conduct your website programming based on that fact. It is the age of mobile users who will not settle for inferior user experience than desktops. So it is your responsibility to give them a good experience while they are on your mobile website.

Encourage Your Users to Explore

It’s how you can do when your users feel at home on your website. Comfortable and happy users want to delve deeper into your website. But do not make things complex in the process of helping your users ‘discover’ something on your site. Keep it simple so that your users can experience the joy of discovering.

Conclusion

Mobile devices are being improved, technology is advancing, and users are expecting more from their mobile devices. However, bear in mind that high-end technology and inventive features are not as important to users as you consider. Users are much more concerned with finding the information that they are looking for. So, before handing your mobile web designing project to a website design company, talk to everyday mobile users. Understand their needs. Then only should you begin the project?

 

About the Author – Carol James is a writer and senior editor at papers writing company EssayLab. She has MA degree in social sciences and writes articles, reviews on the different actual subjects. So, if you have any questions regarding the writing, feel free to ask her.

How to do Unit Test of functions and Widgets in Flutter?

$
0
0

Lets see how we can test Flutter Apps.

It would be easy if we continue from the previous example…

 

Start unit Testing

We will create a test file named ‘widget_test.dart’ inside the ‘test’ folder.

To test Widgets, we will use the ‘testWidgets’ function.

Lets see how it will look like…

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import '../../flutter_demo1/lib/Pages/init_page.dart';
import '../../flutter_demo1/lib/Pages/home.dart';

void main() {
  testWidgets('Counter increments smoke test', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget(new MyApp());

    // Verify that our counter starts at 0.
    expect(find.text('0'), findsOneWidget); // this ensures that there is a widget
    expect(find.text('1'), findsNothing); // this ensures that there is no widget

    // Tap the '+' icon and trigger a frame.
    await tester.tap(find.byIcon(Icons.add));
    await tester.pump();

    // Verify that our counter has incremented.
    expect(find.text('0'), findsNothing); 
    expect(find.text('1'), findsOneWidget);
  });

  test('my simple unit test', () {
    var answer = 42;
    expect(answer, 42);
  });

  test('Testing Square function in  MyApp page...', (){
    expect(new MyApp().findSquare(), 10);
  });

  test('Testing function in HomePage...', (){
    expect(new MyHomePage().testFunction(), 50);
  });

  test('Testing State test function...', (){
    expect(new MyHomePage().createState().testStateFunction(), 60);
  });
  
}

The test function in MyHomePage will look like this

    int testStateFunction(){
        return 60;
    }

Run Tests

To run test we have to run ‘flutter test test/widget_test.dart’ in the terminal.
To run all the tests, run ‘flutter test’.

If you are using VSCode, then you can see the ‘Run‘ link above each test case. You can simple click on it to run. You can see a sample screenshot below.

You should see “All tests passed!” when all tests are successful.

Viewing all 526 articles
Browse latest View live