Friday, March 8, 2013

listening swipe event for any view-Android

"Android Code Snippet":

listening swipe event for any view

First Let me introduce you to the class that will be responsible for listening for swipe event.


import android.app.Activity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class OnSwipeTouchListener implements OnTouchListener {

private final GestureDetector gestureDetector = new GestureDetector(
new GestureListener());

public boolean onTouch(final View v, final MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

private final class GestureListener extends SimpleOnGestureListener {

private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;

@Override
public boolean onDown(MotionEvent e) {
return true;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD
&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
} else {
if (Math.abs(diffY) > SWIPE_THRESHOLD
&& Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}

public void onSwipeRight() {
}

public void onSwipeLeft() {
}

public void onSwipeTop() {
}

public void onSwipeBottom() {
}


///////////////////////////////////////////////////////


public class ActivitySwipeDetector implements OnTouchListener {

private Activity activity;
static final int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;

public ActivitySwipeDetector(final Activity activity) {
this.activity = activity;
}

public final void onRightToLeftSwipe() {
Log.i("RightToLeftSwipe!", null);
}

public void onLeftToRightSwipe() {
Log.i("LeftToRightSwipe!", null);
}

public void onTopToBottomSwipe() {
Log.i("onTopToBottomSwipe!", null);
}

public void onBottomToTopSwipe() {
Log.i("onBottomToTopSwipe!", null);
}

public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
downY = event.getY();
// return true;
}
case MotionEvent.ACTION_UP: {
upX = event.getX();
upY = event.getY();

float deltaX = downX - upX;
float deltaY = downY - upY;

// swipe horizontal?
if (Math.abs(deltaX) > MIN_DISTANCE) {
// left or right
if (deltaX < 0) {
this.onLeftToRightSwipe();
return true;
}
if (deltaX > 0) {
this.onRightToLeftSwipe();
return true;
}
} else {
Log.i("Swipe was only " + Math.abs(deltaX)
+ " long, need at least " + MIN_DISTANCE, null);
}

// swipe vertical?
if (Math.abs(deltaY) > MIN_DISTANCE) {
// top or down
if (deltaY < 0) {
this.onTopToBottomSwipe();
return true;
}
if (deltaY > 0) {
this.onBottomToTopSwipe();
return true;
}
} else {
Log.i("Swipe was only " + Math.abs(deltaX)
+ " long, need at least " + MIN_DISTANCE, null);
}

// return true;
}
}
return false;
}

// public void rihjtToLeft() {
// Log.e("swipping ", "left from width");
//
// }
//
// public void LeftTorihjt() {
//
// }


public void onSwipeRight() {
}

public void onSwipeLeft() {
}
}



}

Now clearly this is the class we are going to use for listening any swipe event.For that we need to attach this listener to any view that we need swipe event from.

For me when i wanted to listen swipe from entire screen , so here is what i did:

        MyActivity.this.getWindow().getDecorView().setOnTouchListener(new OnSwipeTouchListener() {

   public void onSwipeRight() {
   // ScoreGroup.group.onBackPressed();
    //Log.e("No left View ","left");
    Toast.makeText(AntlerMetrixActivity.this, "No left View ", Toast.LENGTH_SHORT).show();
   }
   public void onSwipeLeft() {
    Log.e("swipping ","left");
    next();
   }

});

But if you want to listen swipe from any button or any kind of other view just replace         MyActivity.this.getWindow().getDecorView() with the instance of your view.

When using this swipe listener you need to be careful in some cases. Those view who already have scrolling effect with touch. Bcz in that case if you use this one with say for example with ScrollView this definitely will conflict.For those view one work around can be is to extend that view[ScrollView/ListView] override their touch handling and do some coding in there so that when swipe it does not conflit with the existing touch handling mechanism of ScrollView/... views.

Hope this helps anyone out there.


get file path from gallery-Android

"Android Code Snippet":

Get any selected file path from gallery,[example used only for png/jpg]



public String getSelectedGalleryImagePath(Intent dataIntent){
 String filePath = "";
try {
         if(dataIntent == null){
    return filePath;
         }else{         
          Uri selectedImage = null;
          try {
           if(dataIntent.getData().toString().contains(".png")||dataIntent.getData().toString().contains(".jpg")){
                  filePath = dataIntent.getData().toString()
                  filePath = filePath.replace("file:///", "");
                  return filePath;
           }else{
            selectedImage = Uri.parse(dataIntent.getDataString());
           }
    } catch (NullPointerException e) {
     // TODO: handle exception
     selectedImage = null;
    }
          
             if(selectedImage == null){
              Log.e("mUri"," null");
             }else{         

              Log.e("dataIntent.getDataString()","aa: "+dataIntent.getDataString());

                 String[] filePathColumn = {MediaStore.Images.Media.DATA};

                 Cursor cursor = getContentResolver().query(
                                    selectedImage, filePathColumn, null, null, null);
                 if(cursor==null){
                  Log.e("cursor","is null");
                  
                  filePath = dataIntent.getDataString();
                  filePath = filePath.replace("file:///", "");
                 }else{                  
                  cursor.moveToFirst();
                  
                  int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                  filePath = cursor.getString(columnIndex);
                  cursor.close();
                 
                 }
    return filePath;
              Log.e("mUri","not null :"+filePath);                
             }
         }
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
   Toast.makeText(this, "Something went wrong.Please check again", Toast.LENGTH_LONG).show();
  }
 return filePath;
}

Monday, March 4, 2013

get text as bitmap-Android

"Android Code Snippet"

Handy method to receive text as bitmap, so later on someone can draw that into another view.


public Bitmap getTextAsBitmap(Context gContext,
 String gText,int mColor,boolean boldenabled,boolean italicenabled,Typeface myFontType) {
 Resources resources = gContext.getResources();
 float scale = resources.getDisplayMetrics().density;

 // new antialised Paint
 Paint paint = new Paint();

if(boldenabled && italicenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC));
paint.setTextSkewX(-0.25f);
}else if(boldenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
paint.setTextSkewX(0.0f);
}else if(italicenabled){
paint.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC));
paint.setTextSkewX(-0.25f);
}else{
paint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
paint.setTextSkewX(0.0f);
}

// text size in pixels
paint.setTextSize((int) (textSize*3 * scale));
if (myFontType != null) {
paint.setTypeface(myFontType);
}

paint.setColor(mColor);

 // draw text to the Canvas center
 Rect bounds = new Rect();
 paint.getTextBounds(gText, 0, gText.length(), bounds);
 Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), android.graphics.Bitmap.Config.ARGB_8888);    
 Canvas canvas = new Canvas(bitmap);
 int x = (bitmap.getWidth() - bounds.width())/2;
 int y = (bitmap.getHeight())/2;
 canvas.drawText(gText, x * scale, y * scale, paint);
 return bitmap;
}

share intent-Android

"Android Code Snippet"

Share intent for android


public void shareImageToFriend(String filepath){
if(filepath.length()>0){
        File opt = new File(filepath);
        Intent intent = new Intent(Intent.ACTION_SEND);
            File file = new File(opt.getPath());
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath());
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            intent.setType(mimetype);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            startActivityForResult(Intent.createChooser(intent, "Share this using"), 100);
}
}

Save bitmap as file-Android

"Android Code Snippet"

Save bitmap as file to sdcard in android:


private String saveBitmapAsImageInSdcard(Bitmap bm) {
String pathis = "";
   Bitmap cstemp = null;
   cstemp = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
   Canvas comboImage = new Canvas(cstemp);
   comboImage.drawBitmap(bm,0, 0,null);

   String tmpImg = "filename.png";
   OutputStream os = null;
   try {
       pathis = TEMPPATH + tmpImg;
       os = new FileOutputStream(pathis);
       cstemp.compress(CompressFormat.PNG, 100, os);
   }
   catch (IOException e) {
       Log.e("combineImages", "problem combining images", e);
   }
   return pathis;
}

media scanner update action-Android

"Android Code Snippet"

Start media scanner so gallery or other android system app can update themselves if new file has been added or downloaded:


    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
                    + Environment.getExternalStorageDirectory())));

intent action available or not-Android

"Android Code Snippet"

Check if the action is available or not:


public boolean isIntentAvailable(Context context, String action) {
   final PackageManager packageManager = context.getPackageManager();
   final Intent intent = new Intent(action);
   List resolveInfo =
           packageManager.queryIntentActivities(intent,
                   PackageManager.MATCH_DEFAULT_ONLY);
  if (resolveInfo.size() > 0) {
    return true;
   }
  return false;
}

getting device width-height programmatically-Android

"Android Code Snippet"

Getting device width-height programmatically:



 public int getDeviceWidth(){
     DisplayMetrics metrics = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(metrics);
     return metrics.widthPixels;
 }
 public int getDeviceHeight(){
     DisplayMetrics metrics = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(metrics);
     return metrics.heightPixels;
 }

ViewFlipper Animation-Android

"Android Code Snippet"

Some handy Animation methods when using viewflipper:


protected Animation inFromRightAnimation() {
     Animation inFromRight = new TranslateAnimation(
     Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
     );
     inFromRight.setDuration(500);
     inFromRight.setInterpolator(new AccelerateInterpolator());
     return inFromRight;
}
protected Animation outToLeftAnimation() {
     Animation outtoLeft = new TranslateAnimation(
       Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
       Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
     );
     outtoLeft.setDuration(500);
     outtoLeft.setInterpolator(new AccelerateInterpolator());
     return outtoLeft;
}

protected Animation inFromLeftAnimation() {
     Animation inFromLeft = new TranslateAnimation(
     Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
     );
     inFromLeft.setDuration(500);
     inFromLeft.setInterpolator(new AccelerateInterpolator());
     return inFromLeft;
}
protected Animation outToRightAnimation() {
     Animation outtoRight = new TranslateAnimation(
       Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
       Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
     );
     outtoRight.setDuration(500);
     outtoRight.setInterpolator(new AccelerateInterpolator());
     return outtoRight;
}

Usage:

  ((ViewFlipper)findViewById(R.id.flipFooter)).setInAnimation(inFromRightAnimation());
  ((ViewFlipper)findViewById(R.id.flipFooter)).setOutAnimation(outToLeftAnimation());
  
  ((ViewFlipper)findViewById(R.id.flipFooter)).showNext();

Saturday, March 2, 2013

Fetch Files from sdcard-Android

"Android Code Snippet":
fetch files from sdcard android:


    File file[] = Environment.getExternalStorageDirectory().listFiles();
 recursiveFileFind(file);

    public void recursiveFileFind(File[] file1){
    int i = 0;
    String filePath="";
        if(file1!=null){
        while(i!=file1.length){
            filePath = file1[i].getAbsolutePath();
         if(file1[i].isDirectory()){
          File file[] = file1[i].listFiles();
                recursiveFileFind(file);
         }
            i++;
            Log.d(i+"", filePath);
        }
      }
    }