Sunday, July 14, 2013

flood fill in android



Main.java
------------------------
package com.example.floodfill;

import java.util.LinkedList;
import java.util.Queue;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class Main extends Activity {

    private RelativeLayout dashBoard;
    private MyView myView;
    public ImageView image;

    Button b_red, b_blue, b_green, b_orange, b_clear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myView = new MyView(this);
        setContentView(R.layout.activity_main);
        findViewById(R.id.dashBoard);

        b_red = (Button) findViewById(R.id.b_red);
        b_blue = (Button) findViewById(R.id.b_blue);
        b_green = (Button) findViewById(R.id.b_green);
        b_orange = (Button) findViewById(R.id.b_orange);

        b_red.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.changePaintColor(0xFFFF0000);
            }
        });

        b_blue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.changePaintColor(0xFF0000FF);
            }
        });

        b_green.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.changePaintColor(0xFF00FF00);
            }
        });

        b_orange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.changePaintColor(0xFFFF9900);
            }
        });

        dashBoard = (RelativeLayout) findViewById(R.id.dashBoard);
        dashBoard.addView(myView);

    }

    public class MyView extends View {

        private Paint paint;
        private Path path;
        public Bitmap mBitmap;
        public ProgressDialog pd;
        final Point p1 = new Point();
        public Canvas canvas;

        // Bitmap mutableBitmap ;
        public MyView(Context context) {

            super(context);

            this.paint = new Paint();
            this.paint.setAntiAlias(true);
            pd = new ProgressDialog(context);
            this.paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(5f);
            mBitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.sepia_origin).copy(Bitmap.Config.ARGB_8888, true);
            this.path = new Path();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            this.canvas = canvas;
            this.paint.setColor(Color.RED);

            canvas.drawBitmap(mBitmap, 0, 0, paint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {

            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:

                p1.x = (int) x;
                p1.y = (int) y;
                final int sourceColor = mBitmap.getPixel((int) x, (int) y);
                final int targetColor = paint.getColor();
                new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
                invalidate();
            }
            return true;
        }

        public void clear() {
            path.reset();
            invalidate();
        }

        public int getCurrentPaintColor() {
            return paint.getColor();
        }

        public void changePaintColor(int color) {
            this.paint.setColor(color);
        }

        class TheTask extends AsyncTask<Void, Integer, Void> {

            Bitmap bmp;
            Point pt;
            int replacementColor, targetColor;

            public TheTask(Bitmap bm, Point p, int sc, int tc) {
                this.bmp = bm;
                this.pt = p;
                this.replacementColor = tc;
                this.targetColor = sc;
                pd.setMessage("Filling....");
                pd.show();
            }

            @Override
            protected void onPreExecute() {
                pd.show();

            }

            @Override
            protected void onProgressUpdate(Integer... values) {

            }

            @Override
            protected Void doInBackground(Void... params) {
                FloodFill f = new FloodFill();
                f.floodFill(bmp, pt, targetColor, replacementColor);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                pd.dismiss();
                invalidate();
            }
        }
    }

    // flood fill
    public class FloodFill {

        public void floodFill(Bitmap image, Point node, int targetColor,
                int replacementColor) {

            int width = image.getWidth();
            int height = image.getHeight();
            int target = targetColor;
            int replacement = replacementColor;

            if (target != replacement) {
                Queue<Point> queue = new LinkedList<Point>();
                do {

                    int x = node.x;
                    int y = node.y;
                    while (x > 0 && image.getPixel(x - 1, y) == target) {
                        x--;
                    }

                    boolean spanUp = false;
                    boolean spanDown = false;
                    while (x < width && image.getPixel(x, y) == target) {
                        image.setPixel(x, y, replacement);
                        if (!spanUp && y > 0
                                && image.getPixel(x, y - 1) == target) {
                            queue.add(new Point(x, y - 1));
                            spanUp = true;
                        } else if (spanUp && y > 0
                                && image.getPixel(x, y - 1) != target) {
                            spanUp = false;
                        }
                        if (!spanDown && y < height - 1
                                && image.getPixel(x, y + 1) == target) {
                            queue.add(new Point(x, y + 1));
                            spanDown = true;
                        } else if (spanDown && y < (height - 1)
                                && image.getPixel(x, y + 1) != target) {
                            spanDown = false;
                        }
                        x++;
                    }

                } while ((node = queue.poll()) != null);
            }
        }
    }
}



activity_main.xml
----------------------------------

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawingLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main" >

<RelativeLayout
    android:id="@+id/dashBoard"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/b_red"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="10dp" >

</RelativeLayout>

<Button
    android:id="@+id/b_red"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:background="#FF0000" />

<Button
    android:id="@+id/b_green"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_red"
    android:background="#00FF00" />

<Button
    android:id="@+id/b_blue"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_green"
    android:background="#0000FF" />

<Button
    android:id="@+id/b_orange"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_blue"
    android:background="#FF9900" />

<Button
    android:id="@+id/button5"
    android:layout_width="60dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Clear" />

</RelativeLayout>

Friday, July 12, 2013

image effect


package com.example.imageprocessing;

import java.util.Random;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.widget.ImageView;

//all effects are taken from http://xjaphx.wordpress.com/learning/tutorials/

public class MainActivity extends Activity {
    public static final double PI = 3.14159d;
    public static final double FULL_CIRCLE_DEGREE = 360d;
    public static final double HALF_CIRCLE_DEGREE = 180d;
    public static final double RANGE = 256d;
   
    ImageView ivBeforeEffect, ivAfterEffect;

    Bitmap bmpInput, bmpOutput;

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

        ivBeforeEffect = (ImageView) findViewById(R.id.ivBeforeEffect);
        ivAfterEffect = (ImageView) findViewById(R.id.ivAfterEffect);

        bmpInput = BitmapFactory.decodeResource(getResources(),
                R.drawable.whitechapel);

        ivBeforeEffect.setImageBitmap(bmpInput);

//        bmpInput = getGreyscale(bmpInput);
        // bmpOutput = getHighlightImage(bmpInput);
        // bmpOutput = doInvert(bmpInput);
//        bmpOutput = getSnowEffect(bmpInput);
        bmpInput = getTintImage(bmpInput, 290);
       
        bmpOutput = getGreyscale(bmpInput);

        ivAfterEffect.setImageBitmap(bmpOutput);

    }

    public static Bitmap getGreyscale(Bitmap src) {
        // constant factors
        final double GS_RED = 0.299;
        final double GS_GREEN = 0.587;
        final double GS_BLUE = 0.114;

        // create output bitmap
        Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
                src.getConfig());
        // pixel information
        int A, R, G, B;
        int pixel;

        // get image size
        int width = src.getWidth();
        int height = src.getHeight();

        // scan through every single pixel
        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                // get one pixel color
                pixel = src.getPixel(x, y);
                // retrieve color of all channels
                A = Color.alpha(pixel);
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
               
                if(x < width/2 && y<height/2)
                {
                    R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
                }
                // take conversion up to one single value
//                R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
                // set new pixel color to output bitmap
                bmOut.setPixel(x, y, Color.argb(A, R, G, B));
            }
        }

        // return final image
        return bmOut;
    }

    public static Bitmap getHighlightImage(Bitmap src) {
        // create new bitmap, which will be painted and becomes result image
        Bitmap bmOut = Bitmap.createBitmap(src.getWidth() + 96,
                src.getHeight() + 96, Bitmap.Config.ARGB_8888);
        // setup canvas for painting
        Canvas canvas = new Canvas(bmOut);
        // setup default color
        canvas.drawColor(0, PorterDuff.Mode.CLEAR);

        // create a blur paint for capturing alpha
        Paint ptBlur = new Paint();
        ptBlur.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
        int[] offsetXY = new int[2];
        // capture alpha into a bitmap
        Bitmap bmAlpha = src.extractAlpha(ptBlur, offsetXY);
        // create a color paint
        Paint ptAlphaColor = new Paint();
        ptAlphaColor.setColor(0xFFFFFFFF);
        // paint color for captured alpha region (bitmap)
        canvas.drawBitmap(bmAlpha, offsetXY[0], offsetXY[1], ptAlphaColor);
        // free memory
        bmAlpha.recycle();

        // paint the image source
        canvas.drawBitmap(src, 0, 0, null);

        // return out final image
        return bmOut;
    }

    public static Bitmap doInvert(Bitmap src) {
        // create new bitmap with the same settings as source bitmap
        Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
                src.getConfig());
        // color info
        int A, R, G, B;
        int pixelColor;
        // image size
        int height = src.getHeight();
        int width = src.getWidth();

        // scan through every pixel
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                // get one pixel
                pixelColor = src.getPixel(x, y);
                // saving alpha channel
                A = Color.alpha(pixelColor);
                // inverting byte for each R/G/B channel
                R = 255 - Color.red(pixelColor);
                G = 255 - Color.green(pixelColor);
                B = 255 - Color.blue(pixelColor);
                // set newly-inverted pixel to output image
                bmOut.setPixel(x, y, Color.argb(A, R, G, B));
            }
        }

        // return final bitmap
        return bmOut;
    }

    public static Bitmap getSnowEffect(Bitmap source) {
        // get image size
        int width = source.getWidth();
        int height = source.getHeight();
        int[] pixels = new int[width * height];
        int COLOR_MAX = 0xff;
        // get pixel array from source
        source.getPixels(pixels, 0, width, 0, 0, width, height);
        // random object
        Random random = new Random();

        int R, G, B, index = 0, thresHold = 50;
        // iteration through pixels
        for (int y = 0; y < height; ++y) {
            for (int x = 0; x < width; ++x) {
                // get current index in 2D-matrix
                index = y * width + x;
                // get color
                R = Color.red(pixels[index]);
                G = Color.green(pixels[index]);
                B = Color.blue(pixels[index]);
                // generate threshold
                thresHold = random.nextInt(COLOR_MAX);
                if (R > thresHold && G > thresHold && B > thresHold) {
                    pixels[index] = Color.rgb(COLOR_MAX, COLOR_MAX, COLOR_MAX);
                }
            }
        }
        // output bitmap
        Bitmap bmOut = Bitmap
                .createBitmap(width, height, Bitmap.Config.RGB_565);
        bmOut.setPixels(pixels, 0, width, 0, 0, width, height);
        return bmOut;
    }

    public static Bitmap getTintImage(Bitmap src, int degree) {
       

        int width = src.getWidth();
        int height = src.getHeight();

        int[] pix = new int[width * height];
        src.getPixels(pix, 0, width, 0, 0, width, height);

        int RY, GY, BY, RYY, GYY, BYY, R, G, B, Y;
        double angle = (PI * (double) degree) / HALF_CIRCLE_DEGREE;

        int S = (int) (RANGE * Math.sin(angle));
        int C = (int) (RANGE * Math.cos(angle));

        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++) {
                int index = y * width + x;
                int r = (pix[index] >> 16) & 0xff;
                int g = (pix[index] >> 8) & 0xff;
                int b = pix[index] & 0xff;
                RY = (70 * r - 59 * g - 11 * b) / 100;
                GY = (-30 * r + 41 * g - 11 * b) / 100;
                BY = (-30 * r - 59 * g + 89 * b) / 100;
                Y = (30 * r + 59 * g + 11 * b) / 100;
                RYY = (S * BY + C * RY) / 256;
                BYY = (C * BY - S * RY) / 256;
                GYY = (-51 * RYY - 19 * BYY) / 100;
                R = Y + RYY;
                R = (R < 0) ? 0 : ((R > 255) ? 255 : R);
                G = Y + GYY;
                G = (G < 0) ? 0 : ((G > 255) ? 255 : G);
                B = Y + BYY;
                B = (B < 0) ? 0 : ((B > 255) ? 255 : B);
                pix[index] = 0xff000000 | (R << 16) | (G << 8) | B;
            }

        Bitmap outBitmap = Bitmap.createBitmap(width, height, src.getConfig());
        outBitmap.setPixels(pix, 0, width, 0, 0, width, height);

        pix = null;

        return outBitmap;
    }

}

activity_main.xml
______________________
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/black"
     >

    <ImageView
        android:id="@+id/ivBeforeEffect"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
       
        android:src="@drawable/ic_launcher"
        android:layout_weight="1.0" />
   
    <ImageView
        android:id="@+id/ivAfterEffect"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
       
        android:src="@drawable/ic_launcher"
         android:layout_weight="1.0" />

</LinearLayout>

Wednesday, July 3, 2013

progress dialog in android

download: http://www.mediafire.com/download/ou7hmypj3iynwdc/ProgressDialogExample.tar.gz

package com.helloandroid.android.progressdialogexample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.TextView;

public class ProgressDialogExample extends Activity implements Runnable {

private String pi_string;
private TextView tv;
private ProgressDialog pd;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

tv = (TextView) this.findViewById(R.id.main);
tv.setText("Press any key to start calculation");
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
false);

Thread thread = new Thread(this);
thread.start();

return super.onKeyDown(keyCode, event);
}

public void run() {
pi_string = Pi.computePi(800).toString();
handler.sendEmptyMessage(0);
}

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
pd.dismiss();
tv.setText(pi_string);

}
};

}

Sunday, June 16, 2013

zipped file or directory or backup database


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.dropbox.android.sample.DropActivity;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest.ErrorCode;
import com.progmaatic.chiong.lite.R;
import com.progmaatic.chiong.lite.Utils.MyModelClass;
import com.progmaatic.chiong.lite.Utils.SharedPreferenceHelper;

public class BackupActivity extends Activity implements OnClickListener,
AdListener {
int[] mLayoutres = { R.id.layout_exportencrypted,
R.id.layout_importencrypted, R.id.layout_exportarchive,
R.id.layout_importarchive, R.id.layout_dropboxservice,
R.id.layout_sendtoemail };
OutputStream out;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_backup);
// final AdView adView = (AdView) this.findViewById(R.id.adView);
// final AdRequest adRequest = new AdRequest();
// adRequest.setTesting(true);
// // adRequest.addTestDevice(adRequest.TEST_EMULATOR);
// // adRequest.addTestDevice("5554");
// adView.setAdListener(this);
// adView.loadAd(adRequest);
for (int id : mLayoutres)
findViewById(id).setOnClickListener(this);

}

public void onClick(View v) {
// TODO Auto-generated method stub
onAction(v.getId());
}

private void onAction(int id) {
// TODO Auto-generated method stub
if (id == R.id.layout_exportencrypted) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Export in an encrypted file");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
exportEncryptDbToSdcards();
dialog.dismiss();
}

});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();

} else if (id == R.id.layout_importencrypted) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Import from encrypted file");
builder.setMessage("Warning: Actual data will be replaced by data backup. Continue?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ImportEncryptDbToApp();

dialog.dismiss();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
} else if (id == R.id.layout_exportarchive) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Export data to archive");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
exportArchiveDbToSdcards();
dialog.dismiss();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
} else if (id == R.id.layout_importarchive) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Import data from archive");
builder.setMessage("Warning: Actual data will be replaced by data backup. Continue?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
importArchiveDbToSdcards();
dialog.dismiss();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
} else if (id == R.id.layout_dropboxservice) {
if (zipMyFolder()) {
DropActivity.FileToUpload = Environment.getExternalStorageDirectory().getPath()+"/Chiong/allentries.zip";

Intent uploadStart = new Intent(BackupActivity.this,
DropActivity.class);
startActivity(uploadStart);
}else{
Toast.makeText(getApplicationContext(),
"ERROR DropActivity", Toast.LENGTH_SHORT)
.show();
}
} else if (id == R.id.layout_sendtoemail) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Send all entries to email");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (zipMyFolder()) {
Intent emailIntent = new Intent(
android.content.Intent.ACTION_SEND);
emailIntent.putExtra(
android.content.Intent.EXTRA_SUBJECT,
"Chiong  Entries");
emailIntent.putExtra(
android.content.Intent.EXTRA_TEXT,
"Chiong entries from my device");
emailIntent
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.setType("application/zip");
emailIntent.putExtra(
Intent.EXTRA_STREAM,
Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+
"/Chiong/allentries.zip")));
startActivity(Intent.createChooser(emailIntent,
"send email"));

// File file1 = new
// File("/sdcard/allentries.zip");
// boolean deleted = file1.delete();
} else {
Toast.makeText(getApplicationContext(),
"ERROR WHILE ZIP", Toast.LENGTH_SHORT)
.show();
}
dialog.dismiss();
}

});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}

}

private boolean zipMyFolder() {
ProjectDb pdb = new ProjectDb(BackupActivity.this);
Vector<MyModelClass> all = pdb.getAllProject(true, "", 0, 0);
StringBuilder sb = new StringBuilder();
for (MyModelClass mdc : all) {
sb.append(SharedPreferenceHelper.getDate(mdc.time,
"dd MM yyyy EEE hh:mm a "));
sb.append(mdc.title + " ");
sb.append(mdc.cat + " ");
sb.append(mdc.des);
sb.append("-----------"+'\n');
}
pdb.dbOpenHelper.close();
// Log.w("zxzx", sb.toString());
try {
final String dataentries = new String(sb.toString());
//File sd = new File("/sdcard/Chiong/");
String folder=Environment.getExternalStorageDirectory().getPath()+"/Chiong";
//File sd = new File(Environment.getExternalStorageDirectory().getPath()+"/Chiong/");
File sd = new File(folder);
if(!sd.exists()){
sd.mkdir();
}
File myFile = new File(sd, "allentries.txt");
FileWriter writer = new FileWriter(myFile);
writer.append(dataentries);
writer.flush();
writer.close();
// String s = "/sdcard/Chiong/allentries.txt";
String s = Environment.getExternalStorageDirectory().getPath()+"/Chiong/allentries.txt";
//String loc = "/sdcard/Chiong/allentries.zip";
String loc =Environment.getExternalStorageDirectory().getPath()+ "/Chiong/allentries.zip";
String[] fil = { s };
zip(fil, loc);
//File file = new File("/sdcard/Chiong/allentries.txt");
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/Chiong/allentries.txt");
file.delete();
} catch (IOException ioe) {
ioe.printStackTrace();
return false;
}
return true;
}

public void exportEncryptDbToSdcards() {
try {
// File sd = Environment.getExternalStorageDirectory();
String folder = Environment.getExternalStorageDirectory().getPath()+"/Chiong";
File sd = new File(folder);
if(!sd.exists()){
sd.mkdir();
}
File data = Environment.getDataDirectory();

if (sd.canWrite()) {
String currentDBPath = "/data/data/com.progmaatic.chiong.lite/databases/"
+ ProjectDb.DB_NAME;
String backupDBPath = ProjectDb.DB_NAME;
File currentDB = new File(currentDBPath);
File backupDB = new File(sd, backupDBPath);

if (currentDB.exists()) {
encrypt(new FileInputStream(currentDB),
new FileOutputStream(backupDB));
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Entries were saved on a memory card");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
// FileChannel src = new
// FileInputStream(currentDB).getChannel();
// FileChannel dst = new
// FileOutputStream(backupDB).getChannel();
// dst.transferFrom(src, 0, src.size());
// src.close();
// dst.close();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Permission denied. SD card not found");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (Exception e) {
//Log.w("xxx", e.toString());
e.printStackTrace();
}
}

public void ImportEncryptDbToApp() {
try {
// File sd = Environment.getExternalStorageDirectory();
//File sd = new File(Environment.getExternalStorageDirectory().getPath()+"/Chiong/");
// sd.mkdirs();
String folder=Environment.getExternalStorageDirectory().getPath()+"/Chiong";
File sd = new File(folder);
if(!sd.exists()){
sd.mkdir();
}
File data = Environment.getDataDirectory();

if (sd.canWrite()) {
String currentDBPath = "/data/data/com.progmaatic.chiong.lite/databases/"
+ ProjectDb.DB_NAME;
String backupDBPath = ProjectDb.DB_NAME;
File currentDB = new File(currentDBPath);
File backupDB = new File(sd, backupDBPath);
currentDB.deleteOnExit();

if (backupDB.exists()) {
decrypt(new FileInputStream(backupDB),
new FileOutputStream(currentDB));
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Entries have been restored");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
// FileChannel dst = new
// FileOutputStream(currentDB).getChannel();
// FileChannel src = new
// FileInputStream(backupDB).getChannel();
// dst.transferFrom(src, 0, src.size());
// src.close();
// dst.close();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Data is not stored");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Permission denied. SD card not found");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
}

ProjectDb db = new ProjectDb(this);
db.refreshDb(this);
db.dbOpenHelper.close();
} catch (Exception e) {
// Log.w("xxx", e.toString());
e.printStackTrace();
}
}

static void encrypt(FileInputStream fis, FileOutputStream fos)
throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
// Here you read the cleartext.
// FileInputStream fis = new FileInputStream("data/cleartext");
// This stream write the encrypted text. This stream will be wrapped by
// another stream.
// FileOutputStream fos = new FileOutputStream("data/encrypted");

// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}

static void decrypt(FileInputStream fis, FileOutputStream fos)
throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
// FileInputStream fis = new FileInputStream("data/encrypted");

// FileOutputStream fos = new FileOutputStream("data/decrypted");
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
}

public void exportArchiveDbToSdcards() {
try {
// File sd = Environment.getExternalStorageDirectory();
String folder=Environment.getExternalStorageDirectory().getPath()+"/Chiong";
File sd = new File(folder);
if(!sd.exists()){
sd.mkdir();
}
File data = Environment.getDataDirectory();

if (sd.canWrite()) {
String currentDBPath = "/data/data/com.progmaatic.chiong.lite/databases/"
+ ProjectDb.DB_NAME;
String backupDBPath = ProjectDb.DB_NAME;
File currentDB = new File(currentDBPath);
File backupDB = new File(sd, backupDBPath);
String[] file = { currentDBPath };
String loc =Environment.getExternalStorageDirectory().getPath()+ "/Chiong/Chiongdb.zip";

if (currentDB.exists()) {
zip(file, loc);
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Entries were saved on a memory card");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Permission denied. SD card not found");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (Exception e) {
//Log.w("xxx", e.toString());
e.printStackTrace();
}
}

public void importArchiveDbToSdcards() {
try {
// File sd = Environment.getExternalStorageDirectory();
String folder=Environment.getExternalStorageDirectory().getPath()+"/Chiong";
File sd = new File(folder);
if(!sd.exists()){
sd.mkdir();
}
File data = Environment.getDataDirectory();

if (sd.canWrite()) {
String currentDBPath = "/data/data/com.progmaatic.chiong.lite/databases/"
+ ProjectDb.DB_NAME;
String backupDBPath = ProjectDb.DB_NAME;
File currentDB = new File(currentDBPath);
File backupDB = new File(sd, backupDBPath);
currentDB.deleteOnExit();
String zip = Environment.getExternalStorageDirectory().getPath()+"/Chiong/Chiongdb.zip";
String locs = "/data/data/com.progmaatic.chiong.lite/databases/";
File archiveDB = new File(zip);

// unzip(zip,locs);

if (archiveDB.exists()) {
unzip(zip, locs);
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Entries have been restored");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
// decrypt(new FileInputStream(backupDB), new
// FileOutputStream(currentDB));
// FileChannel dst = new
// FileOutputStream(currentDB).getChannel();
// FileChannel src = new
// FileInputStream(backupDB).getChannel();
// dst.transferFrom(src, 0, src.size());
// src.close();
// dst.close();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Data is not stored");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
BackupActivity.this);
builder.setTitle("Warning");
builder.setMessage("Permission denied. SD card not found");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();

}
});
AlertDialog alert = builder.create();
alert.show();
}
ProjectDb db = new ProjectDb(this);
db.refreshDb(this);
db.dbOpenHelper.close();
} catch (Exception e) {
// Log.w("xxx", e.toString());
e.printStackTrace();
}
}

private final static int BUFFER_SIZE = 2048;

public void zip(String[] files, String zip) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(zip)));
try {
byte data[] = new byte[BUFFER_SIZE];

for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER_SIZE);
try {
ZipEntry entry = new ZipEntry(files[i].substring(files[i]
.lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
} finally {
origin.close();
}
}
} finally {
out.close();
}

}

public void unzip(String zipFile, String location) throws IOException {
int size;
byte[] buffer = new byte[BUFFER_SIZE];

try {
File f = new File(location);
if (!f.isDirectory()) {
f.mkdirs();
}
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(
new FileInputStream(zipFile), BUFFER_SIZE));
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = location + ze.getName();

if (ze.isDirectory()) {
File unzipFile = new File(path);
if (!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
} else {
FileOutputStream out = new FileOutputStream(path, false);
BufferedOutputStream fout = new BufferedOutputStream(
out, BUFFER_SIZE);
try {
while ((size = zin.read(buffer, 0, BUFFER_SIZE)) != -1) {
fout.write(buffer, 0, size);
}
// Toast.makeText(BackupActivity.this, "OK",
// Toast.LENGTH_LONG).show();

zin.closeEntry();
} finally {
fout.flush();
fout.close();
}
}
}
} finally {
zin.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub

}

@Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub

}

@Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub

}

@Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub

}

@Override
public void onReceiveAd(Ad arg0) {
// TODO Auto-generated method stub

}

}