Sunday, 5 March 2017

Android: Decoding a Base64 encoded string

Sometimes in your application you contain some data which is very useful to you or its so sensitive that you don't want anyone else to have it. In that you need to encode or encrypt your data while transferring it through your application.
So for encoding your data and use it in your android application, we have android.util.Base64 class which is used to encode/decode your data.
First of all encoding is not the same thing as encryption. If you’re storing or using useful and sensitive information, you should be encrypting, not simply Base64 encoding. But android.util.Base64 class is also a very useful tool for this purpose.
The use of this class is very simple as depicted in the below example:

1. First import the required class:

                         import android.util.Base64;

2. Now just use the below code: 

String str = "Hello, world!";
       
byte[] encodedStr = Base64.encode(str.getBytes(), Base64.DEFAULT);    
byte[] decodedStr = Base64.decode(encodedStr, Base64.DEFAULT);
       
Log.d("Android Castle", "Android Castle Default Value =  " + str);
Log.d("Android Castle", "Android Castle Encoded Value =  " + new String(encodedStr));
Log.d("Android Castle", "Android Castle Decoded Value =  " + new String(decodedStr));


3. The following will be out put of the above snippet:

Android Castle Default Value = Hello, world!
Android Castle Encoded Value  = SGVsbG8sIHdvcmxkIQ==
Android Castle Decoded Value = Hello, world!

But in many case we have some highly secure data where the data is encoded and then compressed and then its being transferred to your application. In that case being a developer you have to decode the data and decompress it as well to make it useful for your application. The solution for this problem is as follows:

1. Import as follows:

                    import  org.java_websocket.util.Base64;

2. Use the following code snippet:

            String st = "YOUR ENCODE STRING";

            byte[] decodedByte = new byte[0];
            byte[] result = new byte[0];
            int resultLength = 0;
            try {
                decodedByte = Base64.decode(st, Base64.GZIP);
                Inflater decompresser = new Inflater();
                decompresser.setInput(decodedByte, 0, decodedByte.length);
                result = new byte[decodedByte.length];
                resultLength = decompresser.inflate(result);
                decompresser.end();
                String outputString = new String(result, 0, resultLength, "UTF-8");
               
                System.out.println("Your decode string: " + outputString);

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

That's all.

Share and comment if any issues.




Monday, 20 February 2017

Android ViewPager with page animation

In reference to my last post here, this post will show how to implement animation in your viewPager while sliding your pages in a very simple way with a few steps as follows:

1. Add a class that contains the page transformation code as follows:
In this class, the page slide animation is ZoomOutPage transformation which means that your new page will zoom out while you slide it to either side. You will be able to understand it more clearly once you implement it. So now add a class as follows:

public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.85f;
        private static final float MIN_ALPHA = 0.5f;

        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();
            int pageHeight = view.getHeight();

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);

            } else if (position <= 1) { // [-1,1]
                // Modify the default slide transition to shrink the page as well
                float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                if (position < 0) {
                    view.setTranslationX(horzMargin - vertMargin / 2);
                } else {
                    view.setTranslationX(-horzMargin + vertMargin / 2);
                }

                // Scale the page down (between MIN_SCALE and 1)
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);

                // Fade the page relative to its size.
                view.setAlpha(MIN_ALPHA +
                        (scaleFactor - MIN_SCALE) /
                                (1 - MIN_SCALE) * (1 - MIN_ALPHA));

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }


2. Add another class that implements another page slide animation:
In this class, the page slide animation is ZoomInPage transformation which means that your new page will zoom in while you slide it to either side. First let's implement it and then see the changes.

    public class ZoomInPageTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.75f;

        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);

            } else if (position <= 0) { // [-1,0]
                // Use the default slide transition when moving to the left page
                view.setAlpha(1);
                view.setTranslationX(0);
                view.setScaleX(1);
                view.setScaleY(1);

            } else if (position <= 1) { // (0,1]
                // Fade the page out.
                view.setAlpha(1 - position);

                // Counteract the default slide transition
                view.setTranslationX(pageWidth * -position);

                // Scale the page down (between MIN_SCALE and 1)
                float scaleFactor = MIN_SCALE
                        + (1 - MIN_SCALE) * (1 - Math.abs(position));
                view.setScaleX(scaleFactor);
                view.setScaleY(scaleFactor);

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }

3. Now just after the implementation of your viewPager in your class as stated in my previous post here, add the following line:

mPager = (ViewPager) findViewById(R.id.pager);
.......             ..............
mPager.setPageTransformer(true, new ZoomOutPageTransformer());
or
mPager.setPageTransformer(true, new ZoomInPageTransformer());

That's all. Now run your code and see how it works.

Comment if any issues.



Sunday, 12 February 2017

Android: Implementing ViewPager

This post is regarding the implementation of ViewPager in Android. ViewPager is basically the layout manager that allows you to flip(swipe) pages of data left or right or you can say with the help of ViewPager you can swipe left or right your view/screen containing some data.
ViewPager is most often used with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are FragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.
Let's start the steps to implement a ViewPager:

-Create the Views
Create a layout file fragment_screen_slide_page.xml which will be used for the content of a fragment with the following snippet:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView style="?android:textAppearanceMedium"
        android:padding="16dp"
        android:lineSpacingMultiplier="1.2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Your data to be displayed in your view." />
</ScrollView>


-Add a ViewPager
ViewPagers have built-in swipe gestures for transition through pages, and they display screen slide animations by default, so you don't need to create any. ViewPagers use PagerAdapters as a supply for new pages to display, so the PagerAdapter will use the fragment class that we created above.

Create a layout file activity_screen_slide.xml that contains a ViewPager:

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

-Create an activity the does the following:
- Sets the content view to be the layout with the ViewPager.
- Creates a class that extends the FragmentStatePagerAdapter abstract class and implements the getItem() method to supply instances of ScreenSlidePageFragment as new pages. The pager adapter also requires that you implement the getCount() method, which returns the amount of pages the adapter will create (five in the example).
- Hooks up the PagerAdapter to the ViewPager.
- Handles the device's back button by moving backwards in the virtual stack of fragments. If the user is already on the first page, go back on the activity back stack.


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
...
public class ScreenSlidePagerActivity extends FragmentActivity {

    private static final int NUM_PAGES = 5;
    private ViewPager mPager;
    private PagerAdapter mPagerAdapter;

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

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
    }

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

    /**
     * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
     * sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new ScreenSlidePageFragment();
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }
}


-Create the Fragment
Create a Fragment class that returns the layout that you just created in the onCreateView() method. You can then create instances of this fragment in the parent activity whenever you need a new page to display to the user:

import android.support.v4.app.Fragment;
...
public class ScreenSlidePageFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragment_screen_slide_page, container, false);

        return rootView;
    }
}

That's all. You are done with ViewPager. Now run your app and swipe left or right to see changes in your data. You can customize the ViewPager according to your requirements as well.
I'll show you some hacks like page swipe animation in the ViewPager in my next post.




Thursday, 2 February 2017

Android Studio AVD issue in Ubuntu 16.10

As you all know Android Studio is the IDE used for developing android applications. Android Studio has a lot of built-in components and one of the most useful of them is your Android Virtual Device(AVD) Emulator. It helps you to test your applications in an easy way and without using a real device.
Now after downloading and setting up your Android Studio on your Ubuntu 16.10, you might face a problem saying something like:

Cannot launch AVD in emulator.
Output:
libGL error: unable to load driver: radeonsi_dri.so
libGL error: driver pointer missing
libGL error: unable to load driver: i965_dri.so
libGL error: driver pointer missing
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  155 (GLX)
  Minor opcode of failed request:  24 (X_GLXCreateNewContext)
  Value in failed request:  0x0
  Serial number of failed request:  33
  Current serial number in output stream:  34

or may be saying: Unable to work with the Android Emulator.

This is basically a libGL error and libstdc++ issue.
It’s a known bug and you can easily fix it with some simple steps as follows:

1. First install some packages and libs:
    Type the following in your terminal

          $ sudo apt-get install lib64stdc++6:i386  

          $ sudo apt-get install mesa-utils  


2. Second, proceed with these commands:

         $ cd YOURPATH/Android/Sdk/tools/lib64  // In my case YOURPATH = /home/nishant  

         $ mv libstdc++/ libstdc++.bak  

         $ ln -s /usr/lib64/libstdc++.so.6  libstdc++  

3. Now relaunch your AVD device and test it.

That's all.
Its a tested solution for Ubuntu 16.10 64bit.

Comment if any issues.







Sunday, 22 January 2017

Animate a view with TranslateAnimation in android

TranslateAnimation class inherited from Animation class, is basically an animation that controls the position of an object.
The public constructors are:

-    TranslateAnimation(Context context, AttributeSet attrs)
     Constructor used when a TranslateAnimation is loaded from a resource.

-   TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
    Constructor to use when building a TranslateAnimation from code

-   TranslateAnimation(int fromXType, float fromXValue, int toXType, float toXValue, int                         fromYType, float fromYValue, int toYType, float toYValue)
    Constructor to use when building a TranslateAnimation from code

In this post I will show you how to move your view from one point to another on your screen with the help of TranslateAnimation class.
There are basically two ways to use this class which are as follows:

1. You can simple call the constructor, mentioned above to apply your transition as follows:

                        TranslateAnimation animation = new TranslateAnimation(0, 0, 100, 0);  
                        animation.setDuration(1000);                                                                     
                        yourImageView.startAnimation(animation);                                              

(called constructor:
TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
fromXDelta       float: Change in X coordinate to apply at the start of the animation
toXDelta               float: Change in X coordinate to apply at the end of the animation
fromYDelta       float: Change in Y coordinate to apply at the start of the animation
toYDelta               float: Change in Y coordinate to apply at the end of the animation)

2. You can use the following method: (Recommended)


public void moveViewToCenter( View view ) {                                                       
                                                                                                                                    
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );        
    DisplayMetrics dm = new DisplayMetrics();                                                       
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );                      
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();                   
                                                                                                                                  
    int originalPos[] = new int[2];                                                                              
    view.getLocationOnScreen( originalPos );                                                             
                                                                                                                                       
    int xDest = dm.widthPixels/2;                                                                                  
    xDest -= (view.getMeasuredWidth()/2);                                                                     
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;   
                                                                                                                                              
    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );                                                                                                        
    anim.setDuration(1000);                                                                                      
    anim.setFillAfter( true );                                                                                      
    view.startAnimation(anim);                                                                                  
                                                                                                                                   
}                                                                                                                               

While using the above method just place your view(to be moved) in a full screen layout. By doing so you won't have to worry about overlapping and clipping other views.
The method moveViewToCenter gets the View's absolute coordinates and calculates how much distance it has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

This is how you can use TranslateAnimation and move your views.
That's all.


Thursday, 12 January 2017

Handling Screen Configuration changes

Handling the screen orientation changes on your android device is sometimes the most irritating and frustrating part in your development cycle. So in this post i will try to remove that frustration and will tell you what exactly happens during the screen orientation process.

When we rotate our device and the screen changes orientation, android system usually destroys our application’s existing activities or fragments and restarts the running activity/fragment(onDestroy() is called, followed by onCreate()). Android System do this so that our application can reload all the resources based on the new configuration.

To work around this thing, Android gives us the option to save our app’s state before destroying all of our activities and fragments, and also to restore that state when recreating them. Thus, proper handling of orientation changes centers around saving this state and also avoiding memory leaks.
So to properly handle a restart, it is important that our activity restores its previous state through the normal activity lifecycle, in which Android calls onSaveInstanceState() before it destroys our activity so that we can save our data about the application state. We can then restore the state during onCreate() or onRestoreInstanceState().

While it may seem a bit hectic to implement this all, handling screen orientation changes properly provides you with several benefits as well:
- You will be able to easily use alternate layouts in portrait and landscape orientations, and you will be able to handle many exceptional states such as low memory situations and interruptions from incoming phone calls without any extra code.

Implementation:
The first thing that you should do is set the android:configChanges flag on your Activity in AndroidManifest.xml as shown below:

<activity
    android:name=".YourActivity"
    android:label="@string/activity_one"
    android:configChanges="orientation|screenSize|keyboardHidden" />

This flag signals to the Android platform that you are going to manually handle your screen orientation, screenSize and keyboard appearance/disappearance changes for this Activity.

Now, when one of these above mentioned configurations change, YourActivity does not restart. Instead, the YourActivity receives a call to onConfigurationChanged() method. This method has a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // Do your stuff in landscape mode
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
       // Do your stuff in portrait mode 
       Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

The Configuration object represents all of the current configurations, not just the ones that have changed.
If you don't need to update your application based on these configuration changes, you can instead not implement onConfigurationChanged(). In this case, all of the resources used before the configuration change are still used and you've only avoided the restart of your activity.

Note: When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().

That's all.
Share and comment if any issues.
References: https://developer.android.com/guide/topics/resources/runtime-changes.html

Thursday, 5 January 2017

Android: DateTimePicker

This post is regarding how to use/implement DateTimePicker in your android app.
DateTimePicker in android is a UI control which is very useful in your app and gives a nice feel to your app if your app contains some date or time related usage.

https://developer.android.com recommend that you use DialogFragment to host each time or date picker. The DialogFragment manages the dialog lifecycle for you and allows you to display the pickers in different layout configurations, such as in a basic dialog on your handsets or as an embedded part of the layout on large screens.
So let's start with the implementation of this UI control which is as simple as follows:

-Create a Time Picker
Create a static class to show your TimePicker by extending DialogFragment as follows:

public static class TimePickerFragment extends DialogFragment
                            implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hour, int minute) {
        // Do something with the time chosen by the user
        // Your selected time will be (hour:minute)          
    }
}

-Show the time picker
Now add a button to your layout xml file as follows:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pick_time"
    android:onClick="showTimePickerDialog" />

-When you will click this button, the system will call the following method:

public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");
}

That's all. After this you will be able to see a TimePicker from where you can select your time. After selecting the time you can get your selected time (callback) in the onTimeSet() method of your TimePicker class that you just created above.    

-Create a Date Picker
Create a static class to show your DatePicker by extending DialogFragment as follows:

public static class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        // Your selected date will be (day/month/year)    
    }
}

-Show the date picker
Now add another button to your layout xml file as follows:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pick_date"
    android:onClick="showDatePickerDialog" />

-When you will click this button, the system will call the following method:

public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}


That's all. After this you will be able to see a DatePicker from where you can select your date. After selecting the date you can get your selected date (callback) in the onDateSet() method of your DatePicker class that you just created above.

Share and comment if any issues.