Friday, August 8, 2014

Programming Design Pattern - Builder Pattern Applied - Best Practise

Hi there!

Today i'm gonna share the first of a brand new programming design pattern series i made. The builder pattern is a very useful and common pattern while developing serious apps. In this post i'll give a tiny builder pattern framework, so you can always come back here and get it to work with.

A mnemonic, while dealing with builder pattern, is to think about customization. I always think about it, when i'm figuring out if i should use it or if i better take a factory. That's the way it works better for me. try yourself.

The UML Builder Pattern

Here is how the little framework looks like. Simple, nice and straightforward.


The code behind it

The code is also very simple, small, clean and self-explanatory. I like to code expressive, so i don't need to comment a lot. In this sample here i did, because it has a tutorial character. While developing i created some convention to my self. I think it is very important to do so. It is like applying the right grammar on a language while developing. 

For example: If i'm using the Builder Pattern, i always put the suffix Builder at the end. Well you may say or think now: what? But thats in fact a very, very, important info for beginners and expirienced developers. They will automatically see the idea behind it and will try not to break the pattern. In fact expirienced developers will love it and try to continue a good work, because they know, that the developer who wrote this, knows what he did and for sure there was a reason for it.

So always try to be clear enough and give the right information on the right places. Someone else will thank you later.  But now to the code... :)

// 1. EXAMPLE: PARTS OF THE CUSTOMIZABLE PRODUCT WE WANT
public interface Part {
    // DEFINE THE METHODS YOUR PARTS WILL HAVE...
    void anyMethodNameYouLike();
}

// 2. THE BUILDER METHOD WILL ADD 
// PARTS RETURNING THE BUILDER ITSELF
public interface BuildContract < B > {
    B mount(Part part);
}

// 3. DEFINE THE BUILDER'S CONTRUCTION METHOD
// WHICH BUILDS AND RETURNS THE FINAL PRODUCT "T"
public interface Builder < T > extends BuildContract < Builder < T > > {
    T build();
}

A real example

Nothing better then that to fix it and understand it better. Let´s implement a cake bakery. A colleague of yours wants to open a bakery and asked you to program a bakery's software for him. Let's do it.. :)
And by the way, I commend you heartily, using a UML diagram tool is as visualization mechanism to show your ideas and improve your design skills. Lets start by the UML:


The analogy

Let's now use our tiny framework and make the analogy for our bakery. Ingredient is the Part, Recipe is the BuilderContract and  Builder is the builder itself. Cake is the final, customizable product. CakeBuilder is the class which actually creates the product after customization (after the addition of as many parts - ingredients - as you want). The client would be the final client or your colleague taking the order. Just use or imagination... :) Let's dive into code now... 

The Ingredients (Parts)

The parts in our example are the ingredients. Let's implement some ingredients to use it later to make a cake. 
 
// 1. EXAMPLE: PART TO CUSTOMIZATE "INGREDIENTS"
public interface Ingredient {
    // INGREDIENTS WILL HAVE...
    void printName();
    String getUnitPrice();
    void printCalories();
}
public class LightMilk implements Ingredient {

    private int deciLiter;
    private int calories;
    private String unitPrice;
    
    public LightMilk(int deciLiter){this.deciLiter=deciLiter;}
    
    public LightMilk(int deciLiter, int calories, String unitPrice) {
        super();
        this.deciLiter = deciLiter;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }

    @Override public void printName() {System.out.printf(" Light Milk");}
    @Override public String getUnitPrice() {return unitPrice;}
    @Override public void printCalories() {System.out.printf(" 76kc");}
    public int getDeciLiter() {return deciLiter;}
    public void setDeciLiter(int deciLiter) {this.deciLiter = deciLiter;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}
}
public class Sugar implements Ingredient {

    private int gram;
    private int calories;
    private String unitPrice;
    
    public Sugar(int deciLiter){this.gram=deciLiter;}
    
    public Sugar(int gram, int calories, String unitPrice) {
        super();
        this.gram = gram;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }

    @Override public void printName() {System.out.printf(" Sugar");}
    @Override public String getUnitPrice() {return unitPrice;}
    @Override public void printCalories() {System.out.printf(" 40kc");}
    public int getGram() {return gram;}
    public void setGram(int gram) {this.gram = gram;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}
}
public class Choco implements Ingredient {
    private int gram;
    private int calories;
    private String unitPrice;
    public Choco(int gram, int calories, String unitPrice) {
        super();
        this.gram = gram;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }
    public int getGram() {return gram;}
    public void setGram(int gram) {this.gram = gram;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}

    @Override public void printName() {System.out.printf(" Chocolate");}
    @Override public void printCalories() {System.out.printf(" 389kc");}
    @Override public String getUnitPrice() {return unitPrice;}
}
public class NoSugar implements Ingredient {

    private int gram;
    private int calories;
    private String unitPrice;
    
    public NoSugar(int deciLiter){this.gram=deciLiter;}
    
    public NoSugar(int gram, int calories, String unitPrice) {
        super();
        this.gram = gram;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }

    @Override public void printName() {System.out.printf(" No Sugar");}
    @Override public String getUnitPrice() {return unitPrice;}
    @Override public void printCalories() {System.out.printf(" 0kc");}
    public int getGram() {return gram;}
    public void setGram(int gram) {this.gram = gram;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}
}
public class Milk implements Ingredient {

    private int deciLiter;
    private int calories;
    private String unitPrice;
    
    public Milk(int deciLiter){this.deciLiter=deciLiter;}
    
    public Milk(int deciLiter, int calories, String unitPrice) {
        super();
        this.deciLiter = deciLiter;
        this.calories = calories;
        this.unitPrice = unitPrice;
    }

    @Override public void printName() {System.out.printf(" Milk");}
    @Override public String getUnitPrice() {return unitPrice;}
    @Override public void printCalories() {System.out.printf(" 128kc");}
    public int getDeciLiter() {return deciLiter;}
    public void setDeciLiter(int deciLiter) {this.deciLiter = deciLiter;}
    public int getCalories() {return calories;}
    public void setCalories(int calories) {this.calories = calories;}
    public void setUnitPrice(String unitPrice) {this.unitPrice = unitPrice;}
}

The Builder's Contract

This is the Recipe in our example.

// 2. THE BUILDER METHOD WILL ADD 
// INGREDIENTS RETURNING THE BUILDER ITSELF
public interface Recipe < B > {
    B addIngredient(Ingredient ingredient);
}
// 3. DEFINE THE BUILDER CONTRUCTION METHOD
// WHICH BUILDS AND RETURNS THE FINAL PRODUCT "T"
public interface Builder < T > extends Recipe < Builder < T > > {
    T build();
}
import java.util.ArrayList;
import java.util.List;
// 4. IMPLEMENT THE BUILDER ACC. TO YOUR NEEDS
public class CakeBuilder implements Builder < Cake > {
    // IN THIS CASE THE PARTS ARE THE INGREDIENTS
    private List < Ingredient > ingredients=new ArrayList < Ingredient > ( );
    @Override
    public Cake build() {
        if(!ingredients.isEmpty()){
            // THE FINAL PRODUCT IS A CHOCO-MUFFIN
            return new Cake(ingredients);
        }
        return new Cake(null);
    }
    @Override
    // BECAUSE I ALWAYS GET A BUILDER BACK, I'M ABLE TO
    // ADD A LOT OF PARTS BEFORE I CALL "BUILD()"
    public Builder < Cake > addIngredient(Ingredient ingredient) {
        if(ingredient!=null){
            ingredients.add(ingredient);
        }
        return this;
    }
}

The product

In our example the product to build is a cake.
import java.util.List;

public class Cake {
    public Cake(List < Ingredient > ingredients){
        String muffin = "";
        if(ingredients==null){
            System.out.println(" zero cake "+muffin);
            return;
        }
        // PRINT OUT MUFFIN INGREDIENTS
        System.out.printf(" Cake with: ");
        for (Ingredient ingredient : ingredients) {
            ingredient.printName();
        }
        // PRINT OUT PART PRICES
        for (Ingredient ingredient : ingredients) {
            muffin+=" "+ingredient.getUnitPrice();//NOPMD
        }
        System.out.println(" - Price: "+muffin);
    }
    public void printResult(){
        System.out.println(" Cake is ready!");
    }
}

Testing it

Finally the client test. Here we can see the usage of it:
// 5. TESTING THE CHOCO-BUILDER
public class Client {
    public static void main(String[] args) {
        Builder < Cake > chocoMuffinBuilder = new CakeBuilder();
        chocoMuffinBuilder.addIngredient(new Choco(10, 23, "3.39"));
        chocoMuffinBuilder.addIngredient(new Milk(34, 67, "1.57"));
        chocoMuffinBuilder.addIngredient(new Sugar(34, 67, "2.00"));
        final Cake chocoMuffin = chocoMuffinBuilder.build();
        chocoMuffin.printResult();
    }
}
That's all! Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Wednesday, August 6, 2014

How to send email with attachment over android and how to import files from download folder

Hi there!

Today i'm gonna show how to attach a file as attachment and send it over your smartphone using Android. This is specially good if you want users to send you feedbacks or you are trying to backup something.

I had specially problems with attachments because out there was a lot of content but no one completed. Just code snippets and fragments. Here you'll find a complete and working example!


Preparing Attachments

Before you can send attachments, you must create a file in an external directory of your choice before trying to send it. I tryed several approaches and no one has worked for me. Only this one! So, first of all save your data, for example, like this bellow:

    private static final String DATABASE_NAME = "yourDatabaseName.db";
    private static final String SEPARATOR = File.separator;
    public static final String BACKUP = SEPARATOR+DATABASE_NAME;
    public final String packageName = context.getPackageName();
    public static final String DB_FILEPATH = "/data/data/" + packageName + "/databases/"+DATABASE_NAME;
 
    public void backupDatabase() throws IOException {

        if (isSDCardWriteable()) {
            // Open your local db as the input stream
            String inFileName = DB_FILEPATH;
            File dbFile = new File(inFileName);
            FileInputStream fis = new FileInputStream(dbFile);

            String outFileName = Environment.getExternalStorageDirectory()+ BACKUP;
            // Open the empty db as the output stream
            OutputStream output = new FileOutputStream(outFileName);
            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            // Close the streams
            output.flush();
            output.close();
            fis.close();
        }
    }
    

    private boolean isSDCardWriteable() {
        boolean rc = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            rc = true;
        }
        return rc;
    }

Email Intent

Das is the method responsible for sending emails.

    public void backupOverEmail(String[] toEmails) throws IOException {
        backupDatabase();
        String fileName = BACKUP;
        File file = new File(Environment.getExternalStorageDirectory() + fileName);
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("application/octet-stream");
        intent.putExtra(Intent.EXTRA_SUBJECT, "Backup");
        intent.putExtra(Intent.EXTRA_EMAIL, toEmails);
        intent.putExtra(Intent.EXTRA_TEXT, "Backup database\n");
        intent.putExtra(Intent.EXTRA_STREAM, path);
        context.startActivity(Intent.createChooser(intent, "Send mail..."));
    }

Importing Files 

To import your files, you may use this:

    public void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = fromFile.getChannel();
            toChannel = toFile.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }
    public boolean importDatabase() throws IOException {

        // import backup from download folder
        String dbPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + BACKUP;
        // Close the SQLiteOpenHelper so it will
        // commit the created empty database to internal storage.
        close();
        File newDb = new File(dbPath);
        File oldDb = new File(DB_FILEPATH);
        if (newDb.exists()) {
            copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
            // Access the copied database so SQLiteHelper
            // will cache it and mark it as created.
            getWritableDatabase().close();
            return true;
        }
        return false;
    }

That's alll. Hope you like it.

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Tuesday, August 5, 2014

How to create an AsyncTask with visual ProgressBar and displaying icon and custom message Android

Hi There!

Today i'm gonna show how to create and run an AsyncTask with a visual ProgressBar with displaying loading icon and custom message. This is a very often task while developing apps for Android.

It is used everytime we have to run a task in background. This is specially useful, if the task takes more then 10 seconds to prevent ARN (Application Not Responding) errors.

The example bellow is very streight forward and can be used whenever you may need it.

Anonymous AsyncTask

Let's say we have an alert dialog or a button click in which you fire an action which performs a long process computation or web request. Whatever... let's say it is an AlertDialog.
    final String yourCustomMessage;
    final Context cxt = YourAppContext;
    new AsyncTask < Void,  Void, Void > ( ) {
        private ProgressDialog dialog;
        protected void onPreExecute() {
            dialog = new ProgressDialog(cxt);
            String loading = cxt.getString(R.string.alert_buy_languages_loading);
            dialog.setMessage(loading + yourCustomMessage);
            dialog.show();
        }
        @Override
        protected void onPostExecute(Void result) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            //do something here after processing if needed
        }
        @Override
        protected Void doInBackground(Void... params) {
            // heavy weitht process goes here...
            return null;
        }
    }.execute();

That's all! Hope you like it! This AsyncTask has been used in the available app bellow:

Syntaxionary - Programming Language Dictionary


Syntaxionary - Programming Language Dictionary


😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

How to customize / change ActionBar font, text, color, icon, layout and so on with Android

Hi there!

Today i'm gonna share a very coomon task with you. How to customize an ActionBar on Android. We will change layout, font, textsize, textcolor, add listener to it, navigate back, hide title and home icon.

At the end we will have something like this:

syntaxionary - programming language dictionary

Well, lets start by changing some some API provided settings.

Downloading Font

First of all, go to 1001freefonts and donwload a font you want to apply to your text. It is free! :)
After downloading, create a folder called font into the folder assets in your projetct's root. (create it, if not exists already) It looks like this: projectname>assets>font>yourfont.fft


Creating custom colors

We want to change the color of our font also. So for this reason, create two colors in your strings.xml file like this:
<color name="selected">#824986</color>
    <color name="unselected">#E4DFEC</color>

Creating custom ActionBar Layout

As we want to customize our actionBar, we will need to create a customized layout for it. So in your layout folder, create a new layout.xml file called custom_action_bar.xml like this:
< ?xml version="1.0" encoding="utf-8"? >
 < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/actionBar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:paddingLeft="5dp"
    android:paddingTop="7dp"
    android:orientation="horizontal" >
    < TextView
        android:id="@+id/titleFragment1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Syntax"
        android:textSize="20sp"
        android:textColor="@color/selected" / >

    < TextView
        android:id="@+id/titleFragment2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="ionary" / >
< / LinearLayout>

Create createCutomActionBarTitle() in your Activity

create this method and enable setDisplayShowCustomEnable to true and setDisplayShowTitleEnable to false. Then inflate the above created custom_action_bar.xml file. Read your new downloaded font and set it to the textviews. At least add it to the actionBar. Done with the layout.
    private void createCutomActionBarTitle(){
        this.getActionBar().setDisplayShowCustomEnabled(true);
        this.getActionBar().setDisplayShowTitleEnabled(false);

        LayoutInflater inflator = LayoutInflater.from(this);
        View v = inflator.inflate(R.layout.custom_action_bar, null);

        Typeface tf = Typeface.createFromAsset(getAssets(),"font/yourfont.ttf");
        ((TextView)v.findViewById(R.id.titleFragment1)).setTypeface(tf);
        ((TextView)v.findViewById(R.id.titleFragment2)).setTypeface(tf);

        //assign the view to the actionbar
        this.getActionBar().setCustomView(v);
    } 

Adding behaviors and navigate back funcions

A disavantage of customized actionBars is that you have to worry about everything. Including default behaviors like navigating back and enabling actions on the new inserted TextViews. We will do this now. Normally you navigate from activity to activity and after doing something you'd like to give the possibility to the users to navigate back over touching the actionBars title. To do so, enhance the method createCustomActionBarTitle like this:
    private void createCutomActionBarTitle(){
        this.getActionBar().setDisplayShowCustomEnabled(true);
        this.getActionBar().setDisplayShowTitleEnabled(false);

        LayoutInflater inflator = LayoutInflater.from(this);
        View v = inflator.inflate(R.layout.action_bar_contribution, null);

        Typeface tf = Typeface.createFromAsset(getAssets(),"font/fat_tats.ttf");
        TextView frag1 = (TextView)v.findViewById(R.id.titleFragment1);
        frag1.setTypeface(tf);
        TextView frag2 = (TextView)v.findViewById(R.id.titleFragment2);
        frag2.setTypeface(tf);
        
        frag1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(YourCurrentActivity.this, YourTargetActivity.class));
                finish();
            }
        });
        frag2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(YourCurrentActivity.this, YourTargetActivity.class));
                finish();
            }
        });

        //assign the view to the actionbar
        this.getActionBar().setCustomView(v);
    }
    

Adding MetaData to the Manifest file

We are almost done. To be able to navigate back, we need to write an entry in the manifest file. The "YourTargetActivity" is the activity that will be called, wenn we press the actionBars title. In our case it would look like this:

< activity android:label="yourActivityLabelName" 
android:name="your.package.YourActivity" 
android:parentactivityname="your.package.YourTargetActivity" 
android:screenorientation="landscape" 
android:windowsoftinputmode="stateHidden" >

            
            < meta-data android:name="android.support.PARENT_ACTIVITY" 
                 android:value="your.package.YourTargetActivity" >
        < / meta-data> 
< / activity>

That's all! hope you like it! The application to download is here:

syntaxionary - programming language dictionary


😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Wednesday, July 30, 2014

How to create an AdMod AD_UNIT_ID / MY_AD_UNIT_ID on Android

Hi there!

Today i'm gonna show how to create / get an AdMob banner AD_UNIT_ID. I've got some problems while using it. For this reason i'm publishing this article here and sharing my expirience with you.

First of all make sure you have a valid account on AdMob. Go to AdMob and create one if you don't have it yet. Otherwise go further with the next steps.

AD_UNIT_ID

This is the ID you'll need to be able to publish advertisement in your app getting money for user's clicks on it. This is a good way to monetize your apps. In case you don't sale digital contents or in case your apps are free. To obtain such an ID, just do the steps bellow. Just follow the picture series and you should be good :)














That's all. Hope you like it. If you want to see on a real example, how to display full sized advertisement, take a look at the available app bellow:

Syntaxionary - Programming Language Dictionary

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†



Wednesday, July 23, 2014

How to import / export or backup sqlite db dump in your Android App

Hi there!

Today i'm gonna share with you how to import and export your database date using sqlite in your android application.

We will see how to create a sqlite database using SQLiteOpenHelper, how to populate it once while initializing and how to import and export it.

First Step: Defining an Entity

For this example we will implement a LanguageEntitty like shown bellow.
 
public class LanguageEntity {
    
    private int id;
    private String language;
    
    public int getId() {
        return this.id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getLanguage() {
        return this.language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }
} 

Defining our DbFactory

The DbFactory will be responsible for defining all database and table data in a central place. It is also responsible for creating the first database instance and tables if it not exits already. It has the methods to import or export the database as you need.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;


/**
 * Class responsible for defining and creating, updating or deleting DB, tables and its columns.
 * 
 * @author Ricardo Ferreira
 * @version 1.0
 * @since 17/07/2014
 */
public class DbFactory extends SQLiteOpenHelper {

    // Database & Name Version
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "yourdatabasename.db";

    // your table name. In this example language
    public static final String LANGUAGE = "language";
    public static final String LANGUAGE_ID = "language_id";
    public static final String LANGUAGE_NAME = "language_name";
    
    // used SQL statements
    private static final String UNIQUE = " UNIQUE ";
    private static final String INTEGER = " INTEGER ";
    private static final String TEXT = " TEXT ";
    private static final String INTEGERC = " INTEGER, ";
    private static final String TEXTC = " TEXT, ";
    private static final String PARENTHSE_LEFT = " ( ";
    private static final String PARENTHSE_RIGHT = " ) ";
    private static final String CREATE_TABLE_IF_NOT_EXISTS = "CREATE TABLE IF NOT EXISTS ";
    private static final String INTEGER_PRIMARY_KEY = " INTEGER PRIMARY KEY, ";
    private static final String DROP_TABLE_IF_EXISTS = "DROP TABLE IF EXISTS ";

    private final String DB_FILEPATH;

    public DbFactory(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        final String packageName = context.getPackageName();
        DB_FILEPATH = "/data/data/" + packageName + "/databases/yourdatabasename.db";
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createLanguageTable(db);
        populateLanguageOnce(db);
    }

    private void populateLanguageOnce(SQLiteDatabase db) {
        String [ ] languages = new String [ ] { "C", "C++", "C#", "Java" };
        for (String language : languages) {
            insertLanguages(db, language);
        }
    }

    private void insertLanguages(SQLiteDatabase db, String value) {
        ContentValues columnValuePair = new ContentValues();
        columnValuePair.put(LANGUAGE_NAME, value);
        db.insert(LANGUAGE, null, columnValuePair);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         dropTables(db);
         recreateTables(db);
    }

    private void dropTables(SQLiteDatabase db) {
        db.execSQL(DROP_TABLE_IF_EXISTS + LANGUAGE);
    }

    private void recreateTables(SQLiteDatabase db) {
        onCreate(db);
    }

    private void createLanguageTable(SQLiteDatabase db) {
        final StringBuilder sql = new StringBuilder();
        sql.append(CREATE_TABLE_IF_NOT_EXISTS);
        sql.append(LANGUAGE);
        sql.append(PARENTHSE_LEFT);
        sql.append(LANGUAGE_ID);
        sql.append(INTEGER_PRIMARY_KEY);
        sql.append(LANGUAGE_NAME);
        sql.append(TEXTC);
        sql.append(UNIQUE); // ensures uniqueness for languages
        sql.append(PARENTHSE_LEFT);
        sql.append(LANGUAGE_NAME);
        sql.append(PARENTHSE_RIGHT);
        sql.append(PARENTHSE_RIGHT);
        Log.d("CREATE_TABLE_LANGUAGE", sql.toString());
        db.execSQL(sql.toString());
    }

    /**
     * Copies the database file at the specified location 
     * over the current internal application database.
     * */
    public boolean importDatabase(String dbPath) throws IOException {

        // Close the SQLiteOpenHelper so it will
        // commit the created empty database to internal storage.
        close();
        File newDb = new File(dbPath);
        File oldDb = new File(DB_FILEPATH);
        if (newDb.exists()) {
            copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
            // Access the copied database so SQLiteHelper
            // will cache it and mark it as created.
            getWritableDatabase().close();
            return true;
        }
        return false;
    }

    private void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = fromFile.getChannel();
            toChannel = toFile.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }

    public void backupDatabase() throws IOException {

        if (isSDCardWriteable()) {
            // Open your local db as the input stream
            String inFileName = DB_FILEPATH;
            File dbFile = new File(inFileName);
            FileInputStream fis = new FileInputStream(dbFile);

            String outFileName = Environment.getExternalStorageDirectory() + "/syntaxionary";
            // Open the empty db as the output stream
            OutputStream output = new FileOutputStream(outFileName);
            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            // Close the streams
            output.flush();
            output.close();
            fis.close();
        }
    }

    private boolean isSDCardWriteable() {
        boolean rc = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            rc = true;
        }
        return rc;
    }
}

Creating a DAO (Data Access Object)

Before you can use the DbFactory, we must create a DAO who knows how to open and close the database properly. We will see how to query, insert and delete rows in the database. The DAO is designed as a singleton, because it can be used anywhere in your application and because we don't need many instances of it. Let's do it in the next section:

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.treslines.syntaxionary.entity.LanguageEntity;


/**
 * Use this class to manipulate the DB created over DbFactory.
 * Usage example: Db.open(...).insert(...);
 * After execution the Db will always be closed automatically. 
 * @author Ricardo Ferreira
 * @version 1.0
 * @since 17/07/2014
 */
public class DAO {

    private static final String TAG = "TAG";
    private static final long INSERT_ERROR = -1;
    private static final int UPDATE_ERROR = 0;
    private static final String DB_QUERY_SIGN = "= ?";
    private static DAO instance;

    private DbFactory dbFactory;
    private SQLiteDatabase db;//NOPMD

    // singleton
    private DAO(Context context) {
        super();
        this.dbFactory = new DbFactory(context);
        this.db = this.dbFactory.getWritableDatabase();
    }

    /** always start a new db transaction over DAO.open(...) */
    public synchronized static DAO open(Context context) {
        if (instance == null) {
            instance = new DAO(context);
        } 
        return instance;
    }
    
    public long insertLanguage(LanguageEntity language) {
        final String columnName = DbFactory.LANGUAGE_NAME;
        ContentValues values = new ContentValues();
        values.put(columnName, language.getLanguage());
        long newRowId = db.insert(DbFactory.LANGUAGE, null, values);
        close();
        return newRowId;
    }
    
    public int getLanguageCounter() {
        final String tableName = DbFactory.LANGUAGE;
        final Cursor result = db.query(tableName, null, null,null,null,null,null);
        int counter = result.getCount();
        close();
        return counter;
    }
    
    public boolean hasLanguage(String newLanguage) {
        final String tableName = DbFactory.LANGUAGE;
        String where = DbFactory.LANGUAGE_NAME+DB_QUERY_SIGN;
        String [ ] languages = new String [ ] {newLanguage};
        final Cursor result = db.query(tableName, null, where,languages,null,null,null);
        boolean canInsert = result.moveToNext();
        close();
        return canInsert;
    }
    
    public int queryLanguageIdByName(String language) {
        final String tableName = DbFactory.LANGUAGE;
        String where = DbFactory.LANGUAGE_NAME+ DB_QUERY_SIGN;
        Cursor result = db.query(tableName, null,where,new String [ ] {language},null,null,null,null);
        while(result.moveToNext()){
            int columnIndex = result.getColumnIndex(DbFactory.LANGUAGE_ID);
            return result.getInt(columnIndex);
        }
        return 0;
    }
    
    public boolean insertLanguage(String newLanguage) {
        final String tableName = DbFactory.LANGUAGE;
        ContentValues tableValues = new ContentValues();
        tableValues.put(DbFactory.LANGUAGE_NAME, newLanguage);
        long newRowId = db.insert(tableName, null, tableValues);
        close();
        return newRowId != INSERT_ERROR;
    }
    
    public List < String > queryLanguages() {
     Cursor result = db.query(DbFactory.LANGUAGE, new String [ ]{DbFactory.LANGUAGE_NAME}, null, null, null, null, null);
     List< String > languages = new ArrayList< String >();
     while(result.moveToNext()){
      int nameIndex = result.getColumnIndex(DbFactory.LANGUAGE_NAME);
      languages.add(result.getString(nameIndex));
     }
     return languages;
    }

    public int deleteLanguage(String language) {
        final String tableName = DbFactory.LANGUAGE;
        String where = DbFactory.LANGUAGE_NAME + DB_QUERY_SIGN;
        String [ ] languages = new String [ ] { language };
        int result = db.delete(tableName,  where, languages);
        close();
        return result;
    }

    /** Use Db.open(...) to open a new connection */
    public void close() {
        if (db != null && db.isOpen()) {
            db.close();
            db = null;
        }
        if (dbFactory != null) {
            dbFactory.close();
            dbFactory = null;
        }
        instance =null;
    }

}

Usage of the DbFactory and DAO together

Here we can see how we could use it in the practise. In the DbFactory we have methods to import or export the database as you may need.

//... more code omitted ...
DAO.open(getContext()).queryLanguageIdByName("Java"); 
//... more code omitted ...
 
Thats all. Hope you like it!

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†

Thursday, July 10, 2014

How to implement a dynamic dotted line around a view android

Hi there!

Today i'm gonna share a cool think with you. A way to implement a dotted line that grows dynamically around a view. I tryed to resolve it using a nine patch (.9.png) but without success. The end result will look like this:


Resource definition

Define a resource called dotted_pattern.xml in the folder drawable

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape>
            <stroke
                android:dashGap="6dp"
                android:dashWidth="6dp"
                android:width="3dp"
                android:color="#ec9a87" />
        </shape>
    </item>
</layer-list>


Layout definition (your view)

Create in your layout a view like this. Set the defined resource like shown bellow

<FrameLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center"
 android:background="@drawable/dotted_pattern"
android:layerType="hardware" /> 


That's all. hope you like it.

😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘‡

Be sure to read, it will change your life!
Show your work by Austin Kleonhttps://amzn.to/34NVmwx

This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practiceshttps://amzn.to/30WQSm2

Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv

This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp

Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy

😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO ðŸ˜±ðŸ‘†