Wednesday, 14 February 2018

Espresso Check for the Youtube URL



//Using Espresso Intent to check whether the appropriate URL is openedIntents.init();
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData("req_url"));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withText(startsWith("Video"))).perform(click());
intended(expectedIntent);
Intents.release();

Add this dependency in build.gradle
androidTestCompile 'com.android.support.test.espresso:espresso-intents:3.0.1'

Start and Send data to Activity from ADB

1)Navigate to platform-tools which is inside sdk android
2)Then type adb shell am start -n yourpackagename/.activityname
3)Starts the Activity
4)To send the data
adb shell am start -n yourpackagename/.activityname -e myKey test
5)You can retrieve from App Side
getIntent().getStringExtra("myKey")
6)Done

Friday, 2 February 2018

Nexus not detecting in android studio

1.Update Android SDK (Google USB Driver)

2.From PC Control Panel, System -> Device manager -> Right click Nexus 4 -> Update driver.

3.Set android-sdk-folder\extras\google\usb_driver as path to search, include subfolders checked.

If windows tells you that the driver is up to date, just uninstall the driver (right click on nexu4 -> uninstall driver) and start from step 2 again.
After that, open a cmd and type adb kill-server and then a adb devices, now it will include your device.


More details
https://stackoverflow.com/questions/20343014/adb-doesnt-show-nexus-5-device

Git in Android Studio

How to get all changes of release branch to developer branch?


1)Navigate to VCS-->Git--->Merge Changes
There make sure you are on your current branch
2)Branvhes to merge:select the appropriate branch which you want to incorporate
3)Commit
4)Push

Sunday, 28 January 2018

SSL Pinning OverView


Certificate Pinning:

To summarize, pinning a certificate means that your app is verifying that the site the app is communicating with is the actual site by comparing the certificate presented by the site to one bundled in the app. This prevents a man-in-the-middle attack on your app.

SSL pinning isn’t something you want to implement in all your applications, but it makes sense when developing high-risk apps that need strong protection

HOW DOES THIS WORK ON ANDROID ?

  • obtain a certificate for the desired host (preferably the whole certificate chain)
  • make sure the certificate is in .bks format - this step is crucial in order for pinning to work properly across all devices
  • use Apache HTTP client shipped with Android - initialize it to use the obtained .bks keystore for SSL connections

Risks Involved

There is a downside to pinning a certificate. If the site rotates its certificate on a regular basis, then your application would need to be updated regularly. For example, Google rotates its certificates, so you will need to update your application about once a month (if it depended on Google services).

Example of a Failure Scenario
1. App has pinned certificate(s) to some domain name.
2. Certificates get updated on the server side.
3. Version of the app that pinned to old certificate(s) and doesn't know about new certificate(s) won't allow connection
.


Links





Challenges






https://dev.to/drankolq/certificate-pinning-your-android-and-ios-apps

Wednesday, 10 January 2018

Room Persistence Library

The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
The library helps you create a cache of your app's data on a device that's running your app. This cache, which serves as your app's single source of truth, allows users to view a consistent copy of key information within your app, regardless of whether users have an internet connection.

Components of RoomWe have 3 components they are
Entity : It’s nothing but a model class annotated with @Entity where all the variable will becomes column name for the table and name of the model class becomes name of the table.Database: This is an abstract class where you define all the entities that means all the tables that you want to create for that database.Dao: This is an interface which acts is an intermediary between the user and the database. All the operation to be performed on a table has to be defined here.

Sample Example is shown below

Following dependencies in build.gradle file

 // ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:1.0.0"    
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
// Room    
implementation "android.arch.persistence.room:runtime:1.0.0"    
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
// Paging    
implementation "android.arch.paging:runtime:1.0.0-alpha4-1"
// Test helpers for LiveData    
testImplementation "android.arch.core:core-testing:1.0.0"
// Test helpers for Room    
testImplementation "android.arch.persistence.room:testing:1.0.0"

Java Classes

@Entity(tableName = "user")
public class User {

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @PrimaryKey(autoGenerate = true)
    private int uid;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;


}


@Dao
public interface  UserDao {

    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user where first_name LIKE  :firstName AND last_name LIKE :lastName")
    User findByName(String firstName, String lastName);

    @Query("SELECT COUNT(*) from user")
    int countUsers();

    @Insert    
    void insertAll(User... users);

    @Delete    
    void delete(User user);
}


@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {


    private static AppDatabase INSTANCE;

    public abstract UserDao userDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "user-database")
                            // allow queries on the main thread.                            // Don't do this on a real app! See PersistenceBasicSample for an example.                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }

}


public class MainActivity extends AppCompatActivity {

    List<User> usersList;

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

        //Storing sample Data       // populateWithTestData(AppDatabase.getAppDatabase(MainActivity.this));        //Retrieving the data for specific user        User testUser = findUser(AppDatabase.getAppDatabase(MainActivity.this), "Abhi", "Sai");
        Toast.makeText(MainActivity.this, String.valueOf(testUser.getUid()), Toast.LENGTH_LONG).show();
        //Retrieving all users data        usersList = getUsersList(AppDatabase.getAppDatabase(MainActivity.this));
        for (User testUserItems : usersList) {
            Log.i("User ", testUserItems.getFirstName() + "  " + testUserItems.getLastName());
        }

    }

    private static void populateWithTestData(AppDatabase db) {
        User user = new User();
        user.setFirstName("Sanjay");
        user.setLastName("Shah");
        addUser(db, user);
        user.setFirstName("Abhi");
        user.setLastName("Sai");
        addUser(db, user);

    }


    private static User addUser(final AppDatabase db, User user) {
        db.userDao().insertAll(user);
        return user;
    }


    private static User findUser(final AppDatabase db, String fName, String lName) {
        User tUser;
        tUser = db.userDao().findByName(fName, lName);


        return tUser;
    }

    private static List<User> getUsersList(final AppDatabase db) {

        List<User> userList;
        userList = db.userDao().getAll();


        return userList;
    }
}

Thursday, 5 October 2017

MVC and MVVM

MVP design pattern is a set of guidelines that if followed, decouples the code for reusability and testability. It divides the application components based on its role, called separation of concern.


Model: It is responsible for handling the data part of the application.
View: It is responsible for laying out the views with specific data on the screen.
Presenter: It is a bridge that connects a Model and a View. It also acts as an instructor to the View.


MVP lays few ground rules for the above mentioned components, as listed below:
A View’s sole responsibility is to draw UI as instructed by the Presenter. It is a dumb part of the application.
View delegates all the user interactions to its Presenter.
The View never communicates with Model directly.
The Presenter is responsible for delegating View’s requirements to Model and instructing View with actions for specific events.
Model is responsible for fetching the data from server, database and file system.


3.5. Comparison to Model View Controller
In the Model View Presenter pattern, the views more separated from the model. The presenter communicates between model and view. This makes it easier to create unit tests Generally there is a one to one mapping between view and Presenter, but it is also possible to use multiple presenters for complex views.

In the Model View Controller pattern the controllers are behavior based and can share multiple views. View can communicate directly with the model.

MVVM

Also know as model view binder

The view binds to observable variables and actions exposed by the view model typically using the data binding framework.

The view is responsible for handling for example:

Menus

Permissions

Event listeners

Showing dialogs, Toasts, Snackbars

Working with Android View and Widget

Starting activities

All functionality which is related to the Android Context

4.2. The view model
The view model contains the data required for the view. It is an abstraction of the view and exposes public properties and commands. It uses observable data to notify the view about changes. It also allows to pass events to the model. It is also a value converter from the raw model data to presentation-friendly properties)

The view model has the following responsibilities:

Exposing data

Exposing state (progress, offline, empty, error, etc)

Handling visibility

Input validation

Executing calls to the model

Executing methods in the view

The view model should only know about the application context. the application context can:

Start a service

Bind to a service

Send a broadcast

Register a broadcast receiver

Load resource values

It cannot:

Show a dialog

Start an activity

Inflate a layout

4.3. The model
Contains a data provider and the code to fetch and update the data. The data can be retrieved from different sources, for example:

REST API

Realm db

SQLite db

Handles broadcast

Shared Preferences

Firebase

etc.

Basically the same as the model in the MVP.

4.4. Differences to MVP
MVVM uses data binding and is therefore a more event driven architecture. MVP typically has a one to one mapping between the presenter and the view, while MVVM can map many views to one view model In MVVM the view model has no reference to the view, while in MVP the view knows the presenter.

More info
https://blog.mindorks.com/essential-guide-for-designing-your-android-app-architecture-mvp-part-1-74efaf1cda40

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...