Which Activity should we use?

android

There are four different activities:

1- android.app.Activity

Every activity inherits from this one.

This class doesn’t support fragment until API level 11.

This class doesn’t support nested fragments until API level 17.

2- android.support.v4.app.FragmentActivity

This class is from appcompact-v4 library.

Features:

  • Supporting nested fragments
  • Loader

To use this class you should add below dependency to gradle.build

compile 'com.android.support:appcompat-v4:x.x.x'

3- android.support.v7.app.AppCompatActivity

This class is from appcompact-v7 library.

Features:

  • Supporting all v4 features
  • Material Design

To use this class you should add below dependency to gradle.build

compile 'com.android.support:appcompat-v7:x.x.x'

4- android.support.v7.app.ActionBarActivity

This class is the old name of AppCompatActivity. For various reasons they changed the name.

Conclusion

  • If you want support Material Design look and fragment under API level 21 you should use AppCompatActivity
  • If you want support nested fragments under API level 17 you should use FragmentActivity
  • If you want support fragment under API level 11 you should use FragmenActivity
  • Else use Activity

Quick Overview on Java 8 Features

android_development

After all we have some features of java 8 on android :D, lets look at them.

Default Methods

Default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface (For more information please check this link).

Important Note: This feature just work on API level 24.

Static Methods

A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.

Important Note: This feature just work on API level 24

Repeating Annotations

There are some situations where you want to apply the same annotation to a declaration or type use. Repeating annotations enable you to do this.

Important Note: This feature just work on API level 24

Lambda Expressions

Lambda expression facilitates functional programming, and simplifies the development a lot.
Important characteristics of a lambda expression:

  • Optional type declaration
  • Optional parenthesis around parameter
  • Optional curly braces
  • Optional return keyword

This feature is available on API level 24 and lower.

Method References

You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by name.

This feature is available on API level 24 and lower.

 

lambda

Migrating to Jack compiler

jackjill

What is Jack?
Google says:

Jack is a new Android toolchain that compiles Java source into Android dex bytecode. It replaces the previous Android toolchain, which consists of multiple tools, such as javac, ProGuard, jarjar, and dx.

What about existing .jar libraries?
Jill tool translates the existing jar libraries into new library format 😀

Why we need migrating to Jack compiler?

  • Speeds compilation time
    Jack compiler can compile java code to .dex in one step

    • Old toolchain: javac (java -> .class) -> dx (.class -> .dex)
    • Jack toolchain: Jack (java -> .jack -> .dex)
  • Using Java8 features
  • Shrinking, obfuscation, repacking without using different tools

 

Note: Make sure your Android Studio is updated to the last available version.

To enabling Java 8 and Jack for your project your build.gradle file should be like this:

android {
   ...
   defaultConfig {
      ...
      targetSdkVersion 24
      jackOptions{
         enabled true
      }
   }
   compileOptions {
      sourceCompatibility JavaVersion.VERSION_1_8
      targetCompatibility JavaVersion.VERSION_1_8
   }
}

Rebuild your project and it’s should work without any error, But if you see below error:

Error:Could not get unknown property ‘classpath’ for task ‘:app:transformJackWithJackForDebug’ of type com.android.build.gradle.internal.pipeline.TransformTask.

It’s means you should use annotationProcessor dependency scope instead of apt.

 

Important Note: Instant Run doesn’t work with Jack.

Cropping Video In Android

crop_video

Hey guyz, First of all to cropping video we need to use TextureView and this component available from android API 14.

Step 1: Create activity/fragment layout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextureView
        android:id="@+id/textureView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

Step 2: Add video file

If you want to add video to your project you should add it to /res/raw directory

Step 3: Add below code to activity/fragment

    ...

    public static final int MY_VIDEO_WIDTH = 1920;
    public static final int MY_VIDEO_HEIGHT = 1080;

    // I'm using ButterKnife binding my views you can use findViewById instead
    @BindView(R.id.textureView)
    TextureView textureView;
    MediaPlayer mediaPlayer;

    ...

    @Override
    public void onStart() {
        super.onStart();
        textureView.setSurfaceTextureListener(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
        Surface surface = new Surface(surfaceTexture);
        scaleToCropCenter(MY_VIDEO_WIDTH, MY_VIDEO_HEIGHT, this.textureView.getWidth(), this.textureView.getHeight());

        try {
            mediaPlayer = MediaPlayer.create(getActivity(), R.raw.video);
            mediaPlayer.setSurface(surface);
            mediaPlayer.setLooping(true);
            mediaPlayer.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void scaleToCropCenter(int videoWidth, int videoHeight, int viewWidth, int viewHeight) {
        float scaleX = 1.0f;
        float scaleY = 1.0f;

        if (videoWidth > viewWidth && videoHeight > viewHeight) {
            scaleX = division(videoWidth, viewWidth);
            scaleY = division(videoHeight, viewHeight);
        } else if (videoWidth < viewWidth && videoHeight < viewHeight) {             scaleY = division(viewWidth , videoWidth);             scaleX = division(viewHeight , videoHeight);         } else if (viewWidth > videoWidth) {
            scaleY = division(division(viewWidth, videoWidth), division(viewHeight, videoHeight));
        } else if (viewHeight > videoHeight) {
            scaleX = division(division(videoWidth, viewWidth), division(viewHeight, videoHeight));
        }

        int pivotPointX = viewWidth / 2;
        int pivotPointY = viewHeight / 2;

        Matrix matrix = new Matrix();
        matrix.setScale(scaleX, scaleY, pivotPointX, pivotPointY);

        textureView.setTransform(matrix);
        textureView.setLayoutParams(new FrameLayout.LayoutParams(viewWidth, viewHeight));
    }

    private float division(float value1, float value2) {
        if (value1 > value2)
            return value1 / value2;
        else return value2 / value1;
    }

    ...

That’s it 😉

My best Ubuntu applications

Who-we-are-Mendeley

Mendely

I’m using Mendeley to read and annotate PDFs on my desktop and mobile. It can sync your PDFs annotates too 🙂

 

Screenshot from 2016-05-01 19:28:41

Guake Terminal

If you are using terminal frequently, Guake Terminal can help you a lot because Guake is faster than launching a new terminal because the program is already loaded into memory and so can be useful to people who frequently find themselves opening and closing terminals.

 

Screenshot from 2016-05-01 19:31:48

Indicator MultiLoad

Via this tool I can check my systems recourses like CPU, Memory, Network and etc

 

Screenshot from 2016-05-01 19:24:41

Chromium

I’m using Chromium Browser instead chrome because it’s open-source 😀

 

hero-poster-vfl1gZOAd.png

Dropbox

If you want to accessing your files from different devices or sharing files between co-workers it’s bestest solution

 11563shuttlef1.jpg

sshuttle

Best Command-line proxy, it’s can send all traffic to your remote Server.

 

Screenshot from 2016-05-01 19:29:18

VLC

VLC can play everything 😀

Simple Practices for Designing RESTful API

RESTful-Area

Following these standards means:

  • Documentation will make more sense and so developers will understand your API quicker.
  • Developers will therefore be able to integrate quicker and therefore deliver products faster and at lower cost.
  • Many of the principles will make your clients faster, improving product quality

1. Use nouns but not verb

For an easy understanding use this structure for every resources:
Screenshot from 2016-04-06 01:11:33

Note: Do not mix up singular and plural nouns, Keep it simple and use only plural nouns for all resources

2. Use sub-resources for relations

If a resource is related to another resource use subresources
Example: GET /cars/711/drivers/4  Return driver #4 for car 711

3. Provide filtering, sorting and paging for collections

Filtering:

Use a unique query parameter for all fields.
Example: GET /cars?color=red

Sorting:

Allow ascending and descending sorting over multiple fields.
Example: GET /cars?sort=-model

Pagination

Use limit and next URL. It is easy for the client to showing items.
Example: /cars?limit=10

Response:
{
items:[…],
nextURL:”…”
}

4. Version your API

Make the API Version mandatory and do not release an unversioned API.
Note: Use a simple ordinal number and avoid dot notation such as 2.5

5. Error handling

Error responses should include a common HTTP status code, message for developer, message for the end-user (when appropriate).
For example:

{
“status”:400,
“developerMessage”:”Verbose, plain language description of the problem”,
“userMessage”:”This is a message that can be passed along to end-users, if needed.”
}

Use three simple, common response codes indicating (1) success, (2) failure due to client-side problem, (3) failure due to server-side problem:

  1. 200 – OK
  2. 400 – Bad Request
  3. 500 – Internal Server Error

6. Using actions

Sometimes, it is required to expose an operation in the API that inherently is non RESTful. Actions are basically RPC-like messages to a resource to perform a certain operation.

Example: POST /users/12/follow   Following user #12

Note: The actions should only be used as an exception, when there is a good reason that an operation cannot be mapped to one of the standard RESTful methods.

Thank you guys:

https://github.com/WhiteHouse/api-standards
http://mark-kirby.co.uk/2013/creating-a-true-rest-api/#comments
http://restful-api-design.readthedocs.org/en/latest/methods.html
http://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/

بکش تا بروز شه (SwipeRefreshLayout)



قدم اول: اضافه کردن support library v4

کد زیر رو به gradle اضافه می کنیم

dependencies {
compile ‘com.android.support:support-v4:23.1.0’
}

قدم دوم: اضافه کردن SwipeRefreshLayout به Layout

android:id=”@+id/swipe_refresh”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>

android:id=”@+id/recycler_view”
android:layout_width=”match_parent”
android:layout_height=”match_parent” />

قدم سوم: نمایش SwipeRefresh در هنگام لود

هنگامی که از سرور داده ای رو درخواست می کنیم SwipeRefreshLayout رو فعال می کنیم و در زمانی که درخواست ناموفق و یا موفق بود غیر فعال می کنیم

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
swipeRefresh.setRefreshing(true);
}
}, ۱۰۰);

قدم چهارم: پیاده سازیه OnRefreshListener
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//دریافت داده ها از سرور
}
});

قدم آخر: تغییر رنگ SwipeRefreshLayout
swipeRefresh.setColorSchemeResources(R.color.accent);