Sunday, 17 December 2017

ExpandableListView - notifyDataSetChanged() - Tricky

In general, we use to call the notifyDataSetChanged() method for updating the list view with our new data sets i.e. objects with either array list or any collections. This data set updations made in course of load more or pull to refresh etc.

While using the listview we can simply update the data-set object and call the notifyDataSetChanged() method from the adapter. It will take care the necessary action of updating the listview.  But this will not been happens in the case of ExpandableListView, hence it requires few thread based handling and again need to set the updated adapter to the ExpandableListView.  Please find below the code snippet for the same.


if (dataList.size() > 0) {
 if (!isShowMore) {
  dataListGlobal = dataList;
  dataListExpandableAdapter = new DataListExpandableAdapter(getActivity(), dataListGlobal);
  expandabaleDataListView.setAdapter(dataListExpandableAdapter);
 } else {
  dataListGlobal.addAll(dataList);
  getActivity().runOnUiThread(new Runnable() {
   public void run() {
    if (dataListExpandableAdapter != null) {
     dataListExpandableAdapter.notifyDataSetChanged();
     expandabaleDataListView.setAdapter(dataListExpandableAdapter);
    }
   }
  });
 }
}

Happy Coding :-)

Tuesday, 12 December 2017

Add/Remove View on the Top of Activity or Fragment Android


Add view on to the top of your activity or fragment i.e. in simple to add custom view above the AppCompact/Support Toolbar.

FrameLayout rootLayout = (FrameLayout) findViewById (android.R.id.content);
View v = View.inflate(this, R.layout.overlay_layout, rootLayout);

Then when you want to remove it, below use the below code snippet

FrameLayout rootLayout = (FrameLayout)findViewById(android.R.id.content);
rootLayout.removeViewAt(rootLayout.getChildCount()-1);


Happy Coding :-)

Sunday, 26 November 2017

Sunday, 22 October 2017

Code Practice: Library Vs Framework

Most of the tyro programmers are every time wants to impress their leads/superiors, also want to show-up their code practices among their teammates, they use few terminologies to explain about their codes, tells they wrote a generic code and some of the dev's tells they have did a code and it is kinda libraries, frameworks and reusable components etc...  but they are not sure about those terminologies.  

In reality, the code which they have written is really a good and consider to be copy and paste into the other projects, and reuse those in other projects, by sure it reduce efforts.  But it is not a library or frameworks. 

Then what is Library and Framework?  Both smells like a same nuts, but it is not right?  It is a nut but the shells were different.


The key difference between a library and a framework is "Inversion of Control". When you call a method from a library, you are in control. But with a framework, the control is inverted: the framework calls you.

Library:
A library is just a collection of class definitions. The reason behind is simply code reuse, i.e. get the code that has already been written by other developers. The classes and methods normally define specific operations in a domain specific area. For example, there are some libraries of mathematics which can let developer just call the function without redo the implementation of how an algorithm works.

Framework:
In framework, all the control flow is already there, and there's a bunch of predefined white spots that you should fill out with your code. A framework is normally more complex. It defines a skeleton where the application defines its own features to fill out the skeleton. In this way, your code will be called by the framework when appropriately. The benefit is that developers do not need to worry about if a design is good or not, but just about implementing domain specific functions.


Courtesy: Programcreek

Monday, 2 October 2017

Android Resource Layout Sub-folder

Right now, we are probably storing every xml layout file inside the layout/ folder. It is feasible and simple to manage in small projects, but when i'm developing a large and heavy projects/products i.e. more .xml files, we feel difficult in search and finding the files and the things will get messy.

So, is there any way to solve this problem?

Yes, after a long search i found the plugin called "Android File Grouping Plugin" but this not gives me the expected solution, this virtually group the layout files into folder and this can visualized only in the android studio which need to be enabled with the plugin, as like as we have it in the XCode for iOS Projects.

Solution:
Hence after the deep dive into the gradle's ground and found the solution for the same without using any third-party plugins and therefore it also directly reflects on the code and folder hierarchy.

here its go like this, please keenly follow the steps

1. Prepare the folder structure in the below way,  inside the res folder, create your own directory and
inside those folders keep the root folder named as "layout" and then keep on adding your .xml files as to your convenient. For EG: In the below example, i have made the designed the Boarding and Dashboard, under to that created the layout as root directory, then added my .xml files.

res/
  layout/
    boarding/
      layout/
        onboarding_activity.xml
        onboarding_fragment_guest.xml
        onboarding_fragment_user.xml
    dashboard/
      layout/
        dashboard_activity.xml
        dashboard_details.xml

2. The trick is to use gradle’s ability to merge multiple resource folders and set the res/ folder as well as the nested subfolders in the sourceSets block.  The quirk is that you can’t declare a container resource folder before you declare that folder’s child resource folders. Below is the sourceSets block from the build.gradle file. Notice that the subfolders are declared first.

sourceSets {
        main {
            res.srcDirs = [
                    'src/main/res/layout/boarding',
                    'src/main/res/layout/dashboard',
                    'src/main/res/layout',
                    'src/main/res'
            ]
        }
    }

Saturday, 30 September 2017

Android Flags Launch Mode

These flags has been setted programmatically, it can be used depends upon to the situation and it does overrides the behaviour which has defined in the AndroidManifest.xml file.

The following are the list of launch mode flags

FLAG_NEW_TASK
FLAG_CLEAR_TASK
FLAG_SINGLE_TOP
FLAG_CLEAR_TOP



FLAG_NEW_TASK:

Eg 1:
Assume Activity Stack
D
C
B
A

We are starting E from D with flag
Output:
E
-------
D
C
B
A
Note:  A , B , C , D will be in one task and E will be in another task

Eg 2:
Assume Activity Stack
D
C
B
A

We are starting B from D with flag
Output:
B
-------
D
C
B
A
Note:  A , B , C , D will be in one task and and another B will be in another task

FLAG_CLEAR_TASK: It works in conjugation with FLAG_NEW_TASK

Assume Activity Stack
D
C
B
A

We are starting E from D with flag
Output:
E

Note: All other activities will be get destroyed, every time it creates the new instance of the activity. Importantly, even if the activity already exist in the stack, it won't encourage the updating of the same activity with onNewIntent(...)

FLAG_SINGLE_TOP:
This works same as launch mode="singleTop" (Refer this link)

FLAG_CLEAR_TOP: It works similar to the SingleTop Flag, but it has one unique feature of destroying the activities on the top of the stack

Assume Activity Stack
D
C
B
A

We are starting B from D with flag
Output:
B -old instance gets extras data through onNewIntent(Intent intent);
A
Note: All the other activities on top of the B will be destroyed.

Courtesy: Link

Sunday, 20 August 2017

Android RTL Feature

Android provides a feature to make our application bidirectional (LTR & RTL). This feature was introduced in android 4.1 (Jelly Bean) for TextView and EditText elements, allowing apps to display and edit text in both left-to-right (LTR) and right-to-left (RTL).

There was full support for RTL feature in android 4.2 version. It makes the exact mirror image of our existing layout.

Our application will continue to appear as we have set it in default direction. But, with a few simple changes, application will be automatically mirrored when the user switches the system language to a right-to-left script (such as Arabic, Hebrew, or Persian).


Android 4.2 includes the following APIs to help manage View components:
android:layoutDirection — attribute for setting the direction of a component’s layout.
android:textDirection — attribute for setting the direction of a component’s text.
android:textAlignment — attribute for setting the alignment of a component’s text.
getLayoutDirectionFromLocale() — method for getting the Locale-specified direction

Make these changes to support bidirectional feature by android:
  1. Add - android:supportsRtl="true" to the <application>element in manifest file.
  2. Change all of app’s “left/right” layout properties to new “start/end” equivalents.
·        If you are targeting your app to Android 4.2 (the app’s targetSdkVersion or minSdkVersion is 17 or higher), then you should use “start” and “end” instead of “left” and “right”. For example, android:paddingLeft should become android:paddingStart

·        If you want your app to work with versions earlier than Android 4.2 (the app’s targetSdkVersion or minSdkVersion is 16 or less), then you should add “start” and end” in addition to “left” and “right”. For example, you’d use both android:paddingLeft and android:paddingStart

Or

·        If you are using Android studio, then open your project in Android Studio and follow the steps:
                       1. Click on “Refactor” in android studio’s menu bar.
                       2. There will be a pop with options, reach to the end of the menu and click on
“Add RTL Support where possible”.
                       3. Now, you will get a popup. Tick the checkbox accordingly.

Note: If you are not a developer and still want to see the miracle then follow the steps:
  1. In your android phone, tap on “Settings” icon.
  2.   Scroll down the list. You will get “Developer options”, if not then no need to worry follow: Settings > About device > Build number
  3. Once you’ve found the Build number section of the settings, tap on the section 7 times. Now there will be “developer options” before “about phone”
  4.  Now tap on developer options and search for “Force RTL layout direction”.
  5. Tap on it to enable RTL feature.
This RTLUtils class helps us to know given View or Locale is RTL

package com.manakular.rajendhiran.lang;

import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import android.support.v4.view.ViewCompat;
import android.view.View;

public class RTLUtils
{

    private static final Set<String> RTL;

    static
    {
        Set<String> lang = new HashSet<String>();
        lang.add("ar"); // Arabic
        lang.add("dv"); // Divehi
        lang.add("fa"); // Persian (Farsi)
        lang.add("ha"); // Hausa
        lang.add("he"); // Hebrew
        lang.add("iw"); // Hebrew (old code)
        lang.add("ji"); // Yiddish (old code)
        lang.add("ps"); // Pashto, Pushto
        lang.add("ur"); // Urdu
        lang.add("yi"); // Yiddish
        RTL = Collections.unmodifiableSet(lang);
    }

    public static boolean isRTL(Locale locale)
    {
        if(locale == null)
            return false;

        // Character.getDirectionality(locale.getDisplayName().charAt(0))
        // can lead to NPE (Java 7 bug)
        // https://bugs.openjdk.java.net/browse/JDK-6992272?page=com.atlassian.streams.streams-jira-plugin:activity-stream-issue-tab
        // using hard coded list of locale instead
        return RTL.contains(locale.getLanguage());
    }

    public static boolean isRTL(View view)
    {
        if(view == null)
            return false;

        // config.getLayoutDirection() only available since 4.2
        // -> using ViewCompat instead (from Android support library)
        if (ViewCompat.getLayoutDirection(view) == View.LAYOUT_DIRECTION_RTL)
        {
            return true;
        }
        return false;
    }
}

To Identify RTL in Android:

public static boolean isRTL() {
    return isRTL(Locale.getDefault());
}

public static boolean isRTL(Locale locale) {
    final int directionality = Character.getDirectionality(locale.getDisplayName().charAt(0));
    return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT ||
           directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
}

Also, you can takes the Android Lint's help to fix up the RTL.   Please refer and make use of the artifacts or library
Happy Coding :)