Pages

Thursday, 21 December 2017

ListView with Custom BaseAdapter in Kotlin - Android Studio 3.0.1


>> Sample to demonstrate the use of Kotlin in Android

package com.db.listviewbaseadapterkotlin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ListView
class MainActivity : AppCompatActivity() {
var lv : ListView? = null;
var emojis = arrayOf(
"Smile :) ",
"Wink ;) ",
"Laugh :D ",
"Sad :( ",
"Tongue :p ",
"Angry :@ ",
"Confused :-s ",
"Crying :'( ",
"Evil >D ",
"Surprised :o ",
"Speechless :-|",
"Kiss :* ",
"Devil (6) ",
"Angel (a) ",
"Tired (:| ",
"Sick :-& ",
"Love <3 ",
"Heartbroken (u) ",
"Dont Tell :-# ",
"Sweat #:-S ",
"Blushing :$ ",
"Flower (f) ",
"Sleeping I-) ",
"Afraid :-SS ",
"Jawdrop 8[] "
)
var emojxImg = intArrayOf(
R.drawable.emoticon_smile,
R.drawable.emoticon_wink,
R.drawable.emoticon_laugh,
R.drawable.emoticon_sad,
R.drawable.emoticon_tongue,
R.drawable.emoticon_angry,
R.drawable.emoticon_confused,
R.drawable.emoticon_crying,
R.drawable.emoticon_evil,
R.drawable.emoticon_surprised,
R.drawable.emoticon_speechless,
R.drawable.emoticon_kiss,
R.drawable.emoticon_devil,
R.drawable.emoticon_angel,
R.drawable.emoticon_tired,
R.drawable.emoticon_sick,
R.drawable.emoticon_love,
R.drawable.emoticon_heartbroken,
R.drawable.emoticon_dont_tell,
R.drawable.emoticon_sweat,
R.drawable.emoticon_blushing,
R.drawable.emoticon_flower,
R.drawable.emoticon_sleeping,
R.drawable.emoticon_afraid,
R.drawable.emoticon_jawdrop
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lv = findViewById<View>(R.id.list) as ListView
val emojisAdapter = EmojisAdapter(applicationContext, emojis, emojxImg)
lv!!.setAdapter(emojisAdapter)
}
}
view raw MainActKot.kt hosted with ❤ by GitHub


package com.db.listviewbaseadapterkotlin
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
/**
* Created by DB on 21-12-2017.
*/
class EmojisAdapter(applicationContext: Context?, emojis: Array<String>, emojxImg: IntArray) : BaseAdapter() {
var context: Context? = applicationContext
var emojis: Array<String>? = emojis
var emojxImg: IntArray? = emojxImg
var inflater: LayoutInflater? = null
init {
this.inflater = LayoutInflater.from(context)
}
override fun getView(position: Int, convertView: View?, viewGroup: ViewGroup?): View {
val view : View?
val vh : ListRowHolder
if(convertView == null){
view = this.inflater!!.inflate(R.layout.list_item, viewGroup, false)
vh = ListRowHolder(view)
view?.tag = vh
}else{
view = convertView
vh = view.tag as ListRowHolder
}
vh.emoTxt.setText(emojis!![position])
vh.emoImg.setImageResource(emojxImg!![position])
return view!!
}
override fun getItem(position: Int): Any {
return emojis!![position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return emojis!!.size
}
private class ListRowHolder(row : View?){
val emoTxt : TextView
val emoImg : ImageView
init {
this.emoTxt = row?.findViewById<View>(R.id.emojiName) as TextView
this.emoImg = row?.findViewById<View>(R.id.emojiImg) as ImageView
}
}
}


Github Source: Download Source Here

Thursday, 7 December 2017

Rockerheiui Emoji Library For Android (Slight Modifications)




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:emojicon="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context="com.db.emojitest.MainActivity">
<com.db.nimbuzzrockerheiuiemojibydb.EmojiconTextView
android:id="@+id/txtEmojicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
emojicon:emojiconSize="28sp"
android:text="Hello World!!! I \ue32d emojicon"
emojicon:emojiconAlignment="baseline" />
<com.db.nimbuzzrockerheiuiemojibydb.EmojiconEditText
android:id="@+id/editEmojicon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
emojicon:emojiconSize="28sp"
android:layout_above="@+id/emojicons"
android:hint="Type a message"
android:textColorHint="#bdbdbd"
android:maxHeight="80dp" />
<FrameLayout android:id="@+id/emojicons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<fragment
android:id="@+id/emoji_fragment"
android:layout_width="match_parent"
android:layout_height="220dp"
class="com.db.nimbuzzrockerheiuiemojibydb.EmojiconsFragment"/>
</FrameLayout>
</RelativeLayout>
view raw main_emoji.xml hosted with ❤ by GitHub


Usage:

>> EmojiconTextView: a TextView which can render emojis.
>> EmojiconEditText: a EditText which can render emojis.
>> EmojiconMultiAutoCompleteTextView: a MultiAutoCompleteTextView which can render emojis.
>> EmojiconGridFragment: a fragment contains emojis in a GridView for the user to choose.
>> EmojiconsFragment: a fragment contains many set of emojis for the user to choose.


Gradle Build:
implementation 'com.dbh4ck:nimbuzzrockerheiuiemojibydb:1.0'

Maven:


NOTE:

Your Target Activity must " implements EmojiconsFragment.OnEmojiconBackspaceClickedListener, EmojiconGridFragment.OnEmojiconClickedListener " as shown in code Below:

package com.db.emojitest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import com.db.nimbuzzrockerheiuiemojibydb.EmojiconEditText;
import com.db.nimbuzzrockerheiuiemojibydb.EmojiconGridFragment;
import com.db.nimbuzzrockerheiuiemojibydb.EmojiconTextView;
import com.db.nimbuzzrockerheiuiemojibydb.EmojiconsFragment;
import com.db.nimbuzzrockerheiuiemojibydb.emoji.Emojicon;
public class MainActivity extends AppCompatActivity implements EmojiconsFragment.OnEmojiconBackspaceClickedListener, EmojiconGridFragment.OnEmojiconClickedListener{
private EmojiconEditText msg_edt_txt;
private EmojiconTextView msg;
private FrameLayout emojicons;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.emojicons = (FrameLayout) findViewById(R.id.emojicons);
msg_edt_txt = (EmojiconEditText) findViewById(R.id.editEmojicon);
msg = (EmojiconTextView) findViewById(R.id.txtEmojicon);
msg.setText(msg_edt_txt.getText());
}
@Override
public void onEmojiconClicked(Emojicon emojicon) {
EmojiconsFragment.input(msg_edt_txt, emojicon);
msg.setText(msg_edt_txt.getText());
}
@Override
public void onEmojiconBackspaceClicked(View v) {
EmojiconsFragment.backspace(msg_edt_txt);
msg.setText(msg_edt_txt.getText());
}
}


Github Source: Full source code available at my Github here

Bintray Repo: Click Here for Bintray Repo

Sunday, 30 April 2017

A Simple Android Library For Multiple Themes Support in Android Apps



Packaging:  AAR
Name:  apk-app-theme
Developer:  dbh4ck
Description:  APK Theme Changer Library
Url:  https://github.com/dbh4ck/db-apk-theme-changer
License:  The Apache Software License, Version 2.0
Version: 1.0
Support: Android API 14 or above
Download: available offline(.aar file) Download Here & can be compiled Online with Gradle (2.3 or higher) via jcenter repo.
Year: 2017
Details: A Simple Android AAR Library for the Support of Multi-Theming in Android Applications enhanching users to customize their apps as per the requirements of UI Designing. This Library contains a Dialog Fragment which popup from the bottom screen of the app & let you choose which color theme you want to apply to your apk. Total available themes are 20 by default which can further be modified and used as per the requirements.

How to IMPORT this Library in your android project?

METHOD 1:  Download Library as AAR And Import it in your project as per following steps in order.

In order to import a .aar library:

Step 1: Open Android Studio, Go to File > New > New Module. Select "Import .JAR/.AAR Package" and click next.
Step 2: Enter the path to .aar file and click finish.
Step 3: Go to File > Project Structure (Ctrl+Shift+Alt+S). Under "Modules," in left menu, select "app"
Step 4: Go to "Dependencies" tab. Click the green "+" in the upper right corner.
Step 5: Select "Module Dependency" Select the new module from the list and click ok. Youre done importing this library succesfully in your project.



METHOD 2: This Method involve online downloading & compiling library by Gradle using your project's default (jcenter) repositories

Step 1: Go to app-level build.gradle file and add following dependency:

// app-level build.gradle


dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:design:25.2.0'
    testCompile 'junit:junit:4.12'


   compile 'com.dbh4ck:dbtheme:1.0'   // This is our APK Theme Changer Library

}


Step 2: Hit "Sync Now" and you're done compiling this Library from my maven repo.


How to USE this Library:

After importing, now you can use this Library in your Activities as follow:

Step 1:

dbThemeDialog dialog = dbThemeDialog.newInstance();    // Create the new Instance of Dialog in an onCreate Method of your Activity

dialog.show(getSupportFragmentManager(), "dialog");     // Show the DialogFragment

Step 2:

Extend your "AppCompatActivity" to BaseActivity of this Library. (Dont Forget to make onCreate method as Public if you got error while building your project)



Open Android Studio >> Create New Project >> Create New Class named BaseActivity and extends it as AppCompatActivity as shown below. Paste following Code :

package com.blogspot.dbh4ck.dbtheme;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
/**
* Created by DB on 22-04-2017.
*/
public class BaseActivity extends AppCompatActivity {
private final static int THEME_PINK_1 = 0;
private final static int THEME_PINK_2 = 1;
private final static int THEME_PINK_3 = 2;
private final static int THEME_BLUE_1 = 3;
private final static int THEME_BLUE_2 = 4;
private final static int THEME_BLUE_3 = 5;
private final static int THEME_RED_1 = 6;
private final static int THEME_RED_2 = 7;
private final static int THEME_GREEN_1 = 8;
private final static int THEME_GREEN_2 = 9;
private final static int THEME_GREEN_3 = 10;
private final static int THEME_GREEN_4 = 11;
private final static int THEME_PURPLE_1 = 12;
private final static int THEME_PURPLE_2 = 13;
private final static int THEME_BLACK_1 = 14;
private final static int THEME_YELLOW_1 = 15;
private final static int THEME_BROWN_1 = 16;
private final static int THEME_BROWN_2 = 17;
private final static int THEME_GREEN_SHADE = 18;
private final static int THEME_GREY_SHADE = 19;
private final static int THEME_DEFAULT = 20;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateTheme();
}
public void updateTheme() {
if (Utility.getTheme(getApplicationContext()) == THEME_PINK_1 ) {
setTheme(R.style.theme_pink1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_pink1dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_PINK_2) {
setTheme(R.style.theme_pink2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_pink2dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_PINK_3) {
setTheme(R.style.theme_pink3);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_pink3dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_BLUE_1) {
setTheme(R.style.theme_blue1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_blue1dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_BLUE_2) {
setTheme(R.style.theme_blue2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_blue2dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_BLUE_3) {
setTheme(R.style.theme_blue3);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_blue3dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_RED_1) {
setTheme(R.style.theme_red1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_red1dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_RED_2) {
setTheme(R.style.theme_red2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_red2dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_GREEN_1) {
setTheme(R.style.theme_green1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_green1dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_GREEN_2) {
setTheme(R.style.theme_green2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_green2dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_GREEN_3) {
setTheme(R.style.theme_green3);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_green3dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_GREEN_4) {
setTheme(R.style.theme_green4);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_green4dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_PURPLE_1) {
setTheme(R.style.theme_purple1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_purple1dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_PURPLE_2) {
setTheme(R.style.theme_purple2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_purple2dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_BLACK_1) {
setTheme(R.style.theme_black1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_black1dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_YELLOW_1) {
setTheme(R.style.theme_yellow1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_yellow1dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_BROWN_1) {
setTheme(R.style.theme_brown1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_brown1dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_BROWN_2) {
setTheme(R.style.theme_brown2);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_brown2dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_GREEN_SHADE) {
setTheme(R.style.theme_green_shade);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_green_shade_dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_GREY_SHADE) {
setTheme(R.style.theme_grey);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.theme_grey_shade_dark));
}
}
else if (Utility.getTheme(getApplicationContext()) == THEME_DEFAULT) {
setTheme(R.style.NimbuzzTheme);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.app_color_primary_dark));
}
}
}
}


Create another class Utility to get the last saved Theme value Paste the code shown under:

package com.blogspot.dbh4ck.dbtheme;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Created by DB on 22-04-2017.
*/
public class Utility {
public static void setTheme(Context context, int theme) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putInt(context.getString(R.string.prefs_theme_key), theme).apply();
}
public static int getTheme(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getInt(context.getString(R.string.prefs_theme_key), -1);
}
}
view raw Utility.java hosted with ❤ by GitHub


Create a DialogFragment which will display list of colors for users to select and apply the selected color theme to the app

package com.blogspot.dbh4ck.dbtheme;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by DB on 22-04-2017.
*/
public class dbThemeDialog extends DialogFragment implements View.OnClickListener {
RecyclerView themesList;
TextView cancelTxt;
private int[] themes_colors;
private MyRecycleAdapter adapter;
public static dbThemeDialog newInstance(){
dbThemeDialog f = new dbThemeDialog();
return f;
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, DialogFragment.STYLE_NO_TITLE);
}
@Override
public void onActivityCreated(Bundle arg0) {
super.onActivityCreated(arg0);
getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
getDialog().getWindow().setGravity(Gravity.BOTTOM);
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.main, container, false);
cancelTxt = (TextView) v.findViewById(R.id.cancel);
cancelTxt.setOnClickListener(this);
themesList = (RecyclerView) v.findViewById(R.id.recyclerViewThemes);
themes_colors = new int[]{
R.color.theme_pink1,
R.color.theme_pink2,
R.color.theme_pink3,
R.color.theme_blue1,
R.color.theme_blue2,
R.color.theme_blue3,
R.color.theme_red1,
R.color.theme_red2,
R.color.theme_green1,
R.color.theme_green2,
R.color.theme_green3,
R.color.theme_green4,
R.color.theme_purple1,
R.color.theme_purple2,
R.color.theme_black1,
R.color.theme_yellow1,
R.color.theme_brown1,
R.color.theme_brown2,
R.color.theme_green_shade,
R.color.theme_grey_shade,
R.color.app_color_primary
};
adapter = new MyRecycleAdapter(themes_colors, getContext());
LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
themesList.setLayoutManager(horizontalLayoutManagaer);
themesList.setAdapter(adapter);
return v;
}
public class MyRecycleAdapter extends RecyclerView.Adapter<MyRecycleAdapter.MyViewHolder> {
private int[] horizontalList;
Context context;
public MyRecycleAdapter(int[] horizontalList, Context context) {
this.horizontalList = horizontalList;
this.context = context;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView imgView;
public MyViewHolder(View view) {
super(view);
imgView = (ImageView) view.findViewById(R.id.circle_themes);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (getPosition()){
case 0:
Utility.setTheme(getActivity().getApplicationContext(), 0);
recreateActivity();
break;
case 1:
Utility.setTheme(getActivity().getApplicationContext(), 1);
recreateActivity();
break;
case 2:
Utility.setTheme(getActivity().getApplicationContext(), 2);
recreateActivity();
break;
case 3:
Utility.setTheme(getActivity().getApplicationContext(), 3);
recreateActivity();
break;
case 4:
Utility.setTheme(getActivity().getApplicationContext(), 4);
recreateActivity();
break;
case 5:
Utility.setTheme(getActivity().getApplicationContext(), 5);
recreateActivity();
break;
case 6:
Utility.setTheme(getActivity().getApplicationContext(), 6);
recreateActivity();
break;
case 7:
Utility.setTheme(getActivity().getApplicationContext(), 7);
recreateActivity();
break;
case 8:
Utility.setTheme(getActivity().getApplicationContext(), 8);
recreateActivity();
break;
case 9:
Utility.setTheme(getActivity().getApplicationContext(), 9);
recreateActivity();
break;
case 10:
Utility.setTheme(getActivity().getApplicationContext(), 10);
recreateActivity();
break;
case 11:
Utility.setTheme(getActivity().getApplicationContext(), 11);
recreateActivity();
break;
case 12:
Utility.setTheme(getActivity().getApplicationContext(), 12);
recreateActivity();
break;
case 13:
Utility.setTheme(getActivity().getApplicationContext(), 13);
recreateActivity();
break;
case 14:
Utility.setTheme(getActivity().getApplicationContext(), 14);
recreateActivity();
break;
case 15:
Utility.setTheme(getActivity().getApplicationContext(), 15);
recreateActivity();
break;
case 16:
Utility.setTheme(getActivity().getApplicationContext(), 16);
recreateActivity();
break;
case 17:
Utility.setTheme(getActivity().getApplicationContext(), 17);
recreateActivity();
break;
case 18:
Utility.setTheme(getActivity().getApplicationContext(), 18);
recreateActivity();
break;
case 19:
Utility.setTheme(getActivity().getApplicationContext(), 19);
recreateActivity();
break;
case 20:
Utility.setTheme(getActivity().getApplicationContext(), 20);
recreateActivity();
break;
}
}
});
}
}
@Override
public MyRecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
return new MyRecycleAdapter.MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyRecycleAdapter.MyViewHolder holder, final int position) {
holder.imgView.setImageResource(horizontalList[position]);
}
@Override
public int getItemCount() {
return horizontalList.length;
}
}
private void recreateActivity() {
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().finish();
getActivity().overridePendingTransition(0, 0);
startActivity(intent);
getActivity().overridePendingTransition(0, 0);
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.cancel) {
getDialog().dismiss();
}
}
}

Sunday, 19 February 2017

AES (Advanced Encryption Standard) Encryption / Decryption of 'Strings' in Android using Cipher Cryptography in Java

Encrypt / Decrypt String Flush Encrypted String to External Storage



Download APK

Source Github

package com.blogspot.dbh4ck.aes_encrypt_decrypt_android;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Base64;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class Nav_AES_Android extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
EditText input_aes, file_name;
Button btn_aes_enc, btn_aes_dec, btn_write_file;
TextView result_aes, dec_Txt;
String output= "";
String plainText;
AboutAesDialog aboutAesDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav__aes__android);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(android.R.color.holo_blue_light));
}
input_aes = (EditText) findViewById(R.id.txtInput);
file_name = (EditText) findViewById(R.id.txtFileName);
btn_aes_enc = (Button) findViewById(R.id.btnEncrypt);
btn_aes_enc.setOnClickListener(this);
btn_aes_dec = (Button) findViewById(R.id.btnDecrypt);
btn_aes_dec.setOnClickListener(this);
btn_write_file = (Button) findViewById(R.id.btnSaveEncryptFile);
btn_write_file.setOnClickListener(this);
result_aes = (TextView) findViewById(R.id.txtOutput);
dec_Txt = (TextView) findViewById(R.id.txtOriginal);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav__aes__android, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_exit) {
System.exit(0);
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
}else if (id == R.id.nav_blog) {
dbBlog();
} else if (id == R.id.nav_about) {
About();
} else if (id == R.id.nav_exit) {
System.exit(0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void About() {
aboutAesDialog = new AboutAesDialog(this);
aboutAesDialog.show();
aboutAesDialog.setCanceledOnTouchOutside(false);
}
private void dbBlog() {
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnEncrypt:
String strInput = input_aes.getText().toString();
if (strInput.trim().equals("")) {
Toast.makeText(getApplicationContext(), "Input must not be blank!", Toast.LENGTH_SHORT).show();
return;
}
else{
Encryption();
}
break;
case R.id.btnDecrypt:
Decryption();
break;
case R.id.btnSaveEncryptFile:
try {
String strName = file_name.getText().toString();
if (strName.trim().equals("")) {
Toast.makeText(getApplicationContext(), "File name is required!", Toast.LENGTH_SHORT).show();
return;
}
else{
if(strName.matches("^[a-zA-Z0-9_+-]*$")){
String data = input_aes.getText().toString();
writeToFile(data);
return;
}
Toast.makeText(getApplicationContext(), "File name should contain only a-z A-Z 0-9 +-_ and no spaces.", Toast.LENGTH_SHORT).show();
}
} catch (IOException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
}
break;
}
}
private void writeToFile(String data) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/AES-Android-Example");
dir.mkdir();
File newFrm = new File(dir + File.separator);
File file = new File(newFrm, file_name.getText() +".txt");
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(data);
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
File outfile = new File(file+".enc.txt");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(outfile);
Cipher encipher = Cipher.getInstance("AES");
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
encipher.init(Cipher.ENCRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, encipher);
CipherOutputStream cos = new CipherOutputStream(fos, encipher);
byte[] bArr = new byte[8];
Toast.makeText(getApplicationContext(), "File is Ecrypted and Saved!", Toast.LENGTH_SHORT).show();
while (true) {
int read = fis.read(bArr);
if (read != -1) {
cos.write(bArr, 0, read);
} else {
cos.close();
fis.close();
return;
}
}
}
private void Decryption() {
try {
Cipher decipher = Cipher.getInstance("AES");
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
decipher.init(Cipher.DECRYPT_MODE, sks);
byte[] decodedValue = Base64.decode(output.getBytes(), Base64.DEFAULT);
byte[] decryptedVal = decipher.doFinal(decodedValue); // Finish
output = new String(decryptedVal);
dec_Txt.setText(output);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
e.printStackTrace();
}
}
private void Encryption() {
try {
plainText = input_aes.getText().toString();
Cipher encipher = Cipher.getInstance("AES");
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
encipher.init(Cipher.ENCRYPT_MODE, sks);
byte[] results = encipher.doFinal(plainText.getBytes("UTF-8"));
output = Base64.encodeToString(results, Base64.DEFAULT);
result_aes.setText(output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


package com.blogspot.dbh4ck.aes_encrypt_decrypt_android;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
/**
* Created by DB on 18-02-2017.
*/
public class AboutAesDialog extends Dialog implements View.OnClickListener {
Button OkBtn;
public AboutAesDialog(Context context) {
super(context);
}
public AboutAesDialog(Context context, int themeResId) {
super(context, themeResId);
}
protected AboutAesDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
}
protected void onStart() {
super.onStart();
setContentView(R.layout.about_aes);
getWindow().setFlags(4,4);
setTitle("About AES");
OkBtn = (Button) findViewById(R.id.OkBtn);
OkBtn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
this.dismiss();
}
}