Now you can Subscribe using RSS

Submit your Email

Sunday

Convert File to Byte Array in Android

Vishal Shrestha
There can be some scenarios where you will want to convert ByteArray to a File like bytearray to bitmap or audio files or any other type of file in your Android App. Simply speaking a byte array is an array of bytes, a byte consists of 8 bit. Byte array can be use dto store the collection of binary data like the contents of a file.

The following code shows how you can convert byte array to a file and a file to byte array in Android.

convert-file-to-byte-array
Convet File to Byte Array and Vice Versa

Converting File to Byte Array in Android
You can do this using input streams.
public static byte[] getByteArrayFromAudio(String filePath) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            for (int readNum; (readNum = fis.read(b)) != -1; ) {
                bos.write(b, 0, readNum);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            Log.d("mylog", e.toString());
        }
        return null;
}



Converting Byte Array to File in Android
You can do this using buffered output streams.
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(yourFile));
bos.write(fileBytes);
bos.flush();
bos.close();

For example, the code below shows how you can convert a bitmap to a byte array and vice-versa.

Bitmap to Byte Array:
public static byte[] getByteArray(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
 }


Byte Array to Bitmap:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

---------------------------------------------------------------------------------------------------------------------

How to Send Emails Using Python

Vishal Shrestha
Python has some modules in the standard library that help working with emails and email servers.
In this guide we will be using the smtplib module of python. SMPTlib defines an SMTP client session object that is used to email any Internet machine with an SMTP or ESMTP listener daemon.

By the end of this guide, you'll be able to just send emails using such a simple line of code:

# Params: from_email, password, to_email, subject, email_body
mailman.sendmail('SENDER EMAIL', 'PASSWORD', 'TO EMAIL', 'SUBJECT','BODY')

In this guide, we will be sending emails using gmail's email and smtp server as example, you can use any server according to your requirement. You can checkout the video tutorial here:



There are 4 basic steps to send email with python, those are:
  1. Set up the SMTP server and log into your account.
  2. Create a MIMEMultipart object and add appropriate headers.
  3. Add message body.
  4. Send the message using the SMTP server object.
Here's the sample code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def sendmail(from_email, password, to_email, subject, message):
    # setup the parameters of the message
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    # add in the message body
    msg.attach(MIMEText(message, 'plain'))
    try:

        # set up the SMTP server
        # host and port, you can leave port empty as 465 is the default anyway
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(msg['From'], password)
        server.sendmail(msg['From'], msg['To'], msg.as_string())
        server.close()
        return True
    except Exception as e:
        print('Something went wrong: ' + str(e))
        return False

Now you can call this method wherever you like to send emails like this:

sendmail('SENDER EMAIL', 'PASSWORD', 'TO EMAIL', 'SUBJECT',
                 'BODY')


There are a lot more things that I've not covered here, but I hope this gets you started, if you have any issues sending email from python, feel free to ask about those in the comments section below.

Saturday

Python Data Structures - Lists in Python

Vishal Shrestha
In this series we will learn about non-primitive data structures in python.
We will not go over the common primitive data structures like int, booleans, floats and string but take a deeper look into non primitive data structures that help us in organizing data and appreciate python's powerful tools a little more. In this series we will go over 4 data-structures, those are
  1. LIST
  2. DICTIONARY
  3. SET
  4. TUPLE
python lists
Lists in Python

We will learn through examples how to use them, what default methods python provides for them and which data structure to use according to our needs.

Let's go over Lists first:
Note: In case you are a video person, you can watch our full python tutorial here:




LIST

In python, Lists are similar to arrays in other languages. Lists don't always have to be homogeneous, and this it a very powerful tool for data storage in python. A single list can contain different Data types like Strings, Integers and even non primitive objects. Lists are also extremely useful for the implementation of stacks and queues. Unlike some other data structures in python that we will cover later, lists are mutable, and hence, they can be modified even after their creation.
Simply Speaking, lists are a type of container in Data Structures, which is used to store multiple data at a time. In python, lists are ordered and have a fixed count. The indexing of elements in a list are according to a definite sequence and the indexing start with 0 being the first element. Each element in the list has a fixed place in the list, this allows us to create duplicates of elements in the list, with each element having its own unique place.
Tip - Lists in python are a useful tool for preserving a sequence of data, later iterating over it and taking necessary steps. Lists can contain mutable elements unlike sets.


CREATING LISTS

Creation of Lists in Python is done by placing the sequence of data inside the square brackets[] separated by commas. Unlike Sets, we don't need a built-in function for creating list. A list can contain duplicate values with their different indexes and hence, multiple distinct or different values can be passed as a sequence we creating the list.
Let's look at the example below to understand the code better:

# Python program to demonstrate lists

# Initializing a List
List = []
print("Intialized a blank List: ")
print(List)

# Creating a List with the use of a String
List = ['python lists']
print("\nList with String: ")
print(List)

# Creating a List with multiple values
List = ["python", "list", "code"]
print("\nList with multiple values: ")
print(List[0])
print(List[1])

# Creating a Multi-Dimensional List (list inside a List)
List = [['pytho', 'list'] , ['another list']]
print("\nNested List: ")
print(List)

# Creating a List with
# the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

# Creating a List with multiple data types
List = [5, 4, 'python', 3, 'list', 2, 1]
print("\nList with the use of multiple datatypes: ")
print(List)


ADDING ELEMENTS IN LIST

To add elements in a list, we can use the built-in method append(). When using append() method, we can only add one element at the end of the list, to add multiple items using append(), we need to use loops. We can also add Tuples to the List with the using append method because tuples are immutable. Unlike Sets, We can also add lists to the existing list with the using the append() method.
One this to note about append() method is that it only works for the addition of elements at the end of the List, for addition of element at the any desired position, we can use the insert() method. Unlike append() which takes only one argument, we need to pass two parameters to the insert() method those are(position, value). Other than append() and insert() methods, there’s one more method for Addition of elements, extend(), this method can be used to add multiple elements at once at the end of the list.

Tip – append() & extend() methods can only add elements at the end, to add elements at desired position use the extend() method.

# Python program to demonstrate element addition in List

# Creating a List
List = []
print("Intialized blank List: ")
print(List)

# Addition of Elements
# in the List
List.append(5)
List.append(4)
List.append(3)
print("\nList after Adding three elements: ")
print(List)

# Adding elements to the List using iterator
for i in range(1, 4):
   List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List
List.append((5, 6))
print("\nList after adding a Tuple: ")
print(List)

# Adding list to a List
List2 = ['Python', 'List']
List.append(List2)
print("\nList after adding a List: ")
print(List)

# Adding Element at a specific Position

# 12 in 4th position, python in first position
List.insert(3, 12)
List2.insert(0, 'Python')
print("\nPerforming Insert Operation: ")
print(List)

# Addition of multiple elements at the end of list
List.extend([8, 'Python', 'List])
print("\nList after Extend Operation: ")
print(List)


ACCESSING THE ELEMENTS OF A LIST

We can access the elements of a list using the index of the element in the list. The index operator [ ] is used to access an item in a list. The index of the list must be an integer. Elements in Nested lists are accessed using nested indexing.

# Creating a List with multiple values
List = ["Python", "List"]
# accessing an element from the list using index
print("Accessing a element from the list")
print(List[0])  
print(List[1])
# Creating a Multi-Dimensional List
List = [['Python', 'List'] , ['List']]
# accessing a element from the Multi-Dimensional List using
print("Acessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])
List = [1, 2, 'Python', 4, 'List', 6, 'Data']
# Accessing a element using negative indexing
print("Element using negative indexing")
# print the last element of list
print(List[-1])
# print third from the last  
print(List[-3])


REMOVING ELEMENTS FROM THE LIST

In python lists Elements are removed from the List by using built-in remove() function. If the element doesn't exist then we get an Error message. Remove() method only removes one element at a time, we can use iterator to remove range of elements. Pop() function is also used to remove & return an element from the list, but by default it removes only the last element of the set, to remove element from a specific position in the List, we need to pass index of the element as an argument to the pop() method.

Tip – Remove method only removes the first occurrence of the searched element.


# Python program to demonstrate item removal from list
# Creating a List
List = [1, 2, 3, 4, 5, 6,  
       7, 8, 9, 10, 11, 12]
print("Intialized a List: ")
print(List)
# Removing elements from List
List.remove(5)
List.remove(6)
print("\nList after Removing two elements: ")
print(List)
# Removing elements from List using an iterator
for i in range(1, 5):
    List.remove(i)
print("\nList after removal of a range of elements: ")
print(List)
# Removing element from the list using the pop() method
List.pop()
print("\nList after popping an element: ")
print(List)
# Removing element at a location from the list using the pop() method
List.pop(3)
print("\nList after popping an element at a specific: ")
print(List)

SLICING A LIST
There are many ways to print a whole List with all elements in python, but for printing a specific range of elements from the list, we use need to use the Slice operation. We can perform the slice operation on Lists with the use of colon(:). To print elements from the start to a range use [:Index], to print elements from end use [:-Index], to print elements from specific Index till the end we use [Index:], to print elements within a range, we can use [Start Index:End Index] & to print whole List with the use of slicing operation, use [:]. Further, slicing can also be used to print whole List in reverse order like this: [::-1].

Tip – To print elements of List from the end, use Negative Indexes.


# Python program to demonstrate removing elements in a List
# Creating a List
List = ['G','E','E','K','S','F',
       'O','R','G','E','E','K','S']
print("Intialized List: ")
print(List)
# Print elements in a specific range using Slice operation
Sliced_List = List[2:7]
print("\nSlicing elements in a range 2-7: ")
print(Sliced_List)
# Print elements from beginning to a predefined
Sliced_List = List[:-5]
print("\nElements sliced till 5th element from last: ")
print(Sliced_List)
# Print elements from a fixed point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th "
     "element till the end: ")
print(Sliced_List)
# Printing all elements
Sliced_List = List[:]
print("\nPrinting all elements of the list: ")
print(Sliced_List)
# Printing elements in reverse
Sliced_List = List[::-1]
print("\nPrinting List in reverse order: ")
print(Sliced_List)

In this tutorial we have seen how we can create list in python, add items to them, remove items from list, access list items and finally how to slice list items. This should get you pretty familiar with the Lists in Python. If you have any questions or comments, feel free to drop them down below. Enjoy python lists, happy coding.

Tuesday

Upgrade PIP in Windows

Vishal Shrestha
This tutorial is a guide that will show you how you can upgrade PIP in Windows. The PIP is a tool that help to install and manage Python packages, such as the packages that can be found in the Python Package Index. If you are following this tutorial that you already have PIP installed in your windows machine.

Here are the topics that will be covered in this tutorial:
1. Check if PIP is installed in your Windows machine.
2. Check the version of PIP installed.
3. Upgrade the PIP version.
4. Downgrade the PIP version.

Tip: To Install PIP in windows, you can check out the following tutorial:


1. First of all to check if you have PIP installed in your windows machine, just open command line and type pip and hit enter. If you see a list of commands that look like the image below: Congrats, you have pip installed.



pip-commands
PIP Commands

2. Now to check the version of PIP installed you can enter one of the following commands:
    - pip --version or pip -V

You'll see an output like this:


pip-version
PIP Version

Here you can check your PIP version and decide whether you want to upgrade or not. No just not the version down so you can downgrade later if required.

3. Now finally, moving on to upgrade PIP on windows machine, use the following command:
    - For windows: python -m pip install --upgrade pip

You'll see the following in console and PIP will be upgraded.

upgrading-pip
Upgrading PIP in Windows

4. Now for some reason you again want to downgrade your PIP version, just pull up the PIP version that you had noted down before upgrading PIP in the previous step and enter the following command:
    - python -m pip intall pip=<your-older-pip-version>

So this is it, you don't have much complexities in upgrading PIP or downgrading PIP. I've covered most common things that you'd want to do with the PIP package. If you are having trouble using PIP you can just enter pip --help in the command line and you will be able to see a bunch of options that you can use with PIP. Happy coding, if you any trouble upgrading pip or downgrading pip, feel free to comment them below, I'll be happy to help.

Wednesday

Django Web Hosting in Apache Server

Vishal Shrestha
In this post, we'll discuss how to host a Django application in Apache Web server. Django has become my favorite web development tool in recent times, it provides a lot of tools that help develop an application in the shortest amount of time possible. However, deploying the Django application can be a bit tricky, so let's get started with how to host Django web application in an Apache server running on Ubuntu.

django-web-hosting-apache-server
Django web hosting in Apache


Prerequisites: (We'll discuss these in detail later in the tutorial)
1. Your Django Web Application
2. Apache web server
3. Django Installed
3. Python installed in your web server
4. mod_wsgi installed for Apache
5. Mysqlclient or mysql-connector-python (If database is mysql) 
Optional: Virtual Environment
Note: We will also go through the checklist for Django Web Server Hosting so that you can verify your configuration matches the required configuration.

Hosting Django Web Application in Apache Server

1. Assuming your Django application is ready, we will transfer it to the required server. For the sake of this tutorial, we will assume the root directory of the project (where manage.py is located) is root/django-app and settings.py,wsgi.py are located in root/django-app/django-app/.
If you don't have Apache installed, you can install it using: apt install apache2

2. If you don't already have python installed in you server, then go ahead and install it.
Note that your django application's python version, server's python version and the version of mod_wsgi python must be matching. In the current date, you are most probably using Django version > 1.5 and probably using python > 3.
So, for python > 3 compatible set up, install required component using the following commands:
Python: apt install python3
Django: apt install django==<your-django-project-version>
mod_wsgi: apt install libapache2-mod-wsgi-py3

If you need to set up for python 2.xx versions, then:
Python: apt install python
Django: apt install django==<your-django-project-version>
mod_wsgi: apt install libapache2-mod-wsgi

3: If you have mysql as the backend database for your application, then you need to install a mysqlclient. So install mysqlclient using:
apt install mysqlclient

If you have problems installing mysqlclient, then install mysql-connector:
apt install mysql-connector-python and then set the database engine in settings.py to  mysql.connector.django. Also change the other details to match the credentials of your live database.

4. We have already installed mod_wsgi in step 2, now we just create a virual-host for our web application and use the power of wsgi to serve requests to our Django app.
Create your website's virtual-host or edit and add the following:

        ServerName djangosite.com
        ServerAlias www.djangosite.com
        ServerAdmin webmaster@localhost

        DocumentRoot /root/django-site

        <Directory /root/django-site>
                Require all granted
        </Directory>

        <Directory /root/django-site/django-site>
                <Files wsgi.py>
                        Require all granted
                </Files>
        </Directory>

        WSGIDaemonProcess daemon1 python-path=/root/django-site
        WSGIProcessGroup daemon1
        WSGIScriptAlias / /root/django-site/django-site/wsgi.py
        WSGIPassAuthorization On

Note that we are assuming all the required dependencies are installed for system wide  users and not in a virtual environment. If you have installed the required dependencies in virtual-environment, then you will need to add a python-home option with WSGIDaemonProcess like this:
WSGIDaemonProcess daemon1 python-path=/root/django-site python-home=/root/your-venv-path

We are done, restart the Apache server and your Django web application is ready to be served! and yeah a gentle reminder, set Debug = False in settings.py when you go live, don't let everybody see those nasty error reports!
I have had a lot of trouble with deploying Django apps in server in the past, the most common problem was version mismatch. So make sure your Python version, django version, mod_wsgi version are all compatible with one another. Cheers! Happy coding.

Saturday

Android RecyclerView Row Slide in Animation on Scroll

Vishal Shrestha
Animations in your Android App have a huge impact on how the user perceive your app. Creating Animations have been constantly simplified with newer APIs that Google provides. Feel free to check out our tutorial on enabling default Animation of visibility changes. Now, on to the matter at hand: Animating the rows of RecyclerView when Scrolled.
You might have seen the slide in from right animation in the Official Android Apps from Google like Google Plus or Google News stand, it looks very intuitive and pleasing. Be joyful because implementing that slide in animation in your own Apps' RecyclerView is very easy and can be done in just around 10 lines of code(5 Lines of Java, 5 Lines of XML)! So lets get started:



Slide in Animation on Scroll in RecyclerView
  1. First of all we will create a slide in Animation in XML that we will use.
  2. In RecyclerViews' bindViewHolder we will set this as the Animation for each view.

1. Creating the Slide in Animation in XML:
Right click on your resources folder and create a new XML resource, select the resource type as Animation and name the file slide_in_right. Then just add the following code in the file:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="100%p"
        android:toXDelta="0" />
</set>


We are just defining the animation that will slide our row view from right to left. 100%p means the row will slide in from where the parent ends. 0 mean its ending x position will the 0.

2. Using the slide in animation in onBindViewHolder
Now that we have already defined our animation, we just need to apply in to our rows of the recyclerView. We can easily do that whenever we need to bind new rows to the RecyclerView. Add the following code in onBindViewHolder.
if (position > lastPosition) {
            Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.slide_in_right);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
}

This code just checks if the position of the row to be displayed is greater that the last row that has been already displayed, if so we just apply our animation to the view. Here lastPosition is a global variable that is initially set to -1 and we can also set the animation variable as global variable depending on your requirements.

We are done! now just add the changes mentioned above to your code, run you app and see beautiful slide in animations in the rows of your RecyclerView whenever you scroll the recyclerView. Feel free to let me know if you have any issues.

Thursday

Animate View on Visibility (Visible - Gone) Changes Android Example

Vishal Shrestha
Animations can separate your app from normal "Just Functional" app and give you app a more polished feel. There are a lot of options how you can show animations on Android, however there is a very easy way to animate layout changes that will make your app look and feel better and more natural. 
Android has some predefined animations that your app can use whenever you have to make change to your app's layout. The layout changes can be setting the visibility of a view to hidden or visible, or when you add a new view. You just need to define an Attribute in the layout that tell the Android system to show animations for these layout changes, and your app will show system-default animations whenever there are layout changes. Check the Gif below for example:

visibility-gone-visible-default-animation
Default Animations in Android


Okay, no more talking, you just need to add the following tag in your root layout:
android:animateLayoutChanges="true" 

Note: You can also do it completely programmatically with the XML, that discussed at the end.
Now don't go running to build your app and see those fluid animations, unless you want to be disappointed and come back to this tutorial and continue it. Setting the animateLayoutChanges property is important, but you also need the following code to make it all work,

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
  ((ViewGroup) findViewById(R.id.llRoot)).getLayoutTransition()
          .enableTransitionType(LayoutTransition.CHANGING);
}
 
We are now done, findViewById refrences the root layout inside which you want to show animations. Now is the time you can build and show or hide some views and test if this works or not! It will work. So wasn't that easy? Of course you can have you custom animation and not the default changeBounds and Fade animations, but for simple Visibility the default ones are the best in my opinion.
In case you want to show your custom animations, you need to create a LayoutTransition object and supply it to the layout using the setLayoutTransition() method but that the code for some other day!

Also, if you are not interested in XML, you can also apply the same animations when there are layout changes using the beginDelayedTransition method. This method was added in API level 19 so make sure the device satisfies the API level before you use this code:

if (Build.VERSION.SDK_INT >= 19) {
                TransitionManager.beginDelayedTransition((ViewGroup) yourViewOnWhichAnimationNeedsToBeShown.getParent());
            }

This is it! Now your app will show animations on layout changes, show whenever the visibility of your views is set to Hidden or Visible, they are handled gracefully, 2 minutes of your time for better UI and UX. Let me what you think below. Cheers!
Also don't forget to check out the RecyclerView Slide in Row Animation Tutorial. Have animations in your RecyclerViews in just 2 Minutes!

Sunday

Fonts in XML | Custom Fonts in Android Support Library

Vishal Shrestha
Finally, after years of dreaming and praying external fonts are fully supported in Android. By fully I mean you can use it directly in XML, add them to styles, create your own font family. Have same fonts through out the app. It is great! Yes, I am enjoying every bit of this easy font styling instead of having to write a custom class extending required view just to have the font you like, oh what a pain it was! I am happy and this post will make you happy, so lets dive right into code. Yeaaahhhh! The scream of joy!
No more of this stupid method: Custom Fonts In Android Using Custom Class.

different-fonts-letters
Just Some Random Fonts


Custom Fonts in Android
Since Android 8.0, fonts in XML has been introduced. It means fonts can be used as resources. Just add the font file in font folder in your resources directory. Alright people, let's get going. Open your resources folder, create a new folder font in it. Inside it just copy all the fonts you want. For this project I've added montserrat fonts. I like them they are sexy just like myself. HaHa. And now you can just create Styles for your Android App and use the style where you want. For example, create a style like this:

<style name="AccentTitleTextStyle" parent="AppTheme">
        <item name="android:textSize">@dimen/title_text_size</item>
        <item name="android:fontFamily">@font/montserrat_bold</item>
        <item name="android:textColor">@color/colorAccent</item>
</style> 


Now all you need to do is just use this style whereever you want through-out your Android app provided you have added montserrat_bold font in your font folder inside resources.
If you want a default font through out an Android App without applying to every single view, then you can just add the font in your default App Theme like this:

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:fontFamily">@font/montserrat_bold</item>
    </style>


Now you'll have the font mentioned in fontFamily property. But this allow only one font, wouldn't it be nice if we could create a Font family and change it just by setting fontStyle property just as we do now with the default Roboto Font? Yes, it would be. And yes we can! Yaaahhhh. Okay come back to earth and create a new XML file in font folder. I'll just call it montserrat as all the fonts I have belong to Montserrat Family. Okay let's go insiiddee the montserrat.xml file:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <font
        android:font="@font/montserrat_regular"
        android:fontStyle="normal"
        android:fontWeight="400"

        app:font="@font/montserrat_regular"
        app:fontStyle="normal"
        app:fontWeight="400" />

    <font
        android:font="@font/montserrat_light_italic"
        android:fontStyle="italic"
        android:fontWeight="400"

        app:font="@font/montserrat_light_italic"
        app:fontStyle="italic"
        app:fontWeight="400" />

</font-family>


So Simple, now if you use this file as the fontFamily in a style and use that style in views then you can just type fontStyle as italic and your view will use montserrat_light_italic as the style. To use this in Android version as low as 4.1 (API level 16), you need to use a support library >= 26. The app:font lines are so than your fonts can be used in versions lower than API level 26.
This is it. Go, cry tears of joy and use your favorite font in you app!
If you have any issues, feel free to comment below. I'll help, I am happy. :D

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha