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

}

}

Monday, June 3, 2013

sliding layer in android

download: http://www.mediafire.com/download/kiop9wadi05pz9k/layer.tar.gz



package com.coboltforge.slidemenuexample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.coboltforge.slidemenu.SlideMenu;
import com.coboltforge.slidemenu.SlideMenu.SlideMenuItem;
import com.coboltforge.slidemenu.SlideMenuInterface.OnSlideMenuItemClickListener;

public class MainActivity extends Activity implements
OnSlideMenuItemClickListener {

private SlideMenu slidemenu;
private final static int MYITEMID = 42;

private static final int SWIPE_MIN_DISTANCE = 50;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 1;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

RelativeLayout rlContainer;

Float previousX = 0f  , currentX = 0f;



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

setContentView(R.layout.activity_main);

rlContainer = (RelativeLayout) findViewById(R.id.rlContainer);

/*
* There are two ways to add the slide menu: From code or to inflate it
* from XML (then you have to declare it in the activities layout XML)
*/

// this is from code. no XML declaration necessary, but you won't get
// state restored after rotation.
// slidemenu = new SlideMenu(this, R.menu.slide, this, 333);
// this inflates the menu from XML. open/closed state will be restored
// after rotation, but you'll have to call init.
slidemenu = (SlideMenu) findViewById(R.id.slideMenu);
slidemenu.init(this, R.menu.slide, this, 333);

// this can set the menu to initially shown instead of hidden
// slidemenu.setAsShown();

// set optional header image
slidemenu.setHeaderImage(getResources().getDrawable(
R.drawable.ic_launcher));

// this demonstrates how to dynamically add menu items
SlideMenuItem item = new SlideMenuItem();
item.id = MYITEMID;
item.icon = getResources().getDrawable(R.drawable.ic_launcher);
item.label = "Dynamically added item";
slidemenu.addMenuItem(item);

slidemenu.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:

previousX =  event.getX();

break;
case MotionEvent.ACTION_MOVE:


break;

case MotionEvent.ACTION_UP:

currentX = event.getX();

Log.e("----previousX="+previousX, "currentX="+currentX);

if (previousX - currentX > SWIPE_MIN_DISTANCE )
{
slidemenu.show();
slidemenu.hide();
} else if (currentX - previousX > SWIPE_MIN_DISTANCE) {
slidemenu.show();
}



break;

}
return true;
}
});

// Gesture detection
gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};

// connect the fallback button in case there is no ActionBar
Button b = (Button) findViewById(R.id.buttonMenu);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// slidemenu.show();
}
});

// b.setOnTouchListener(gestureListener);



}

@Override
public void onSlideMenuItemClick(int itemId) {

switch (itemId) {
case R.id.item_one:
Toast.makeText(this, "Item one selected", Toast.LENGTH_SHORT)
.show();

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);

break;
case R.id.item_two:
Toast.makeText(this, "Item two selected", Toast.LENGTH_SHORT)
.show();
break;
case R.id.item_three:
Toast.makeText(this, "Item three selected", Toast.LENGTH_SHORT)
.show();
break;
case R.id.item_four:
Toast.makeText(this, "Item four selected", Toast.LENGTH_SHORT)
.show();
break;
case MYITEMID:
Toast.makeText(this, "Dynamically added item selected",
Toast.LENGTH_SHORT).show();
break;
}

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: // this is the app icon of the actionbar
slidemenu.show();
break;
}
return super.onOptionsItemSelected(item);
}

// ////////////////////////////////////
class MyGestureDetector extends SimpleOnGestureListener {

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.e("in", "fling");
try {

// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
slidemenu.show();
slidemenu.hide();

Toast.makeText(MainActivity.this, "Left Swipe",
Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
slidemenu.show();
Toast.makeText(MainActivity.this, "Right Swipe",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// nothing
}
return false;
}

}

}