Wednesday, 12 June 2013

android select image from gallery intent

android select image from gallery intent

Tuesday, 11 June 2013

getX and getY different screen android

package com.example.animateframe;

import com.example.animateframe.model.girl;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

public class MainActivity extends Activity {

 /** Called when the activity is first created. */
 ImageView img;
 Button btnStart, btnStop;
 AnimationDrawable animation;
 MediaPlayer mMediaPlayerHEAD;
 SeekBar seekbarS, seekbar;
 static int heart = 0;
 static int level = 1;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // Remove title bar
  // this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
  // Remove notification bar
  // this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  // WindowManager.LayoutParams.FLAG_FULLSCREEN); 
  setContentView(R.layout.main_frame);
  // startService(new Intent(getBaseContext(), MusicService.class));
  mMediaPlayerHEAD = MediaPlayer
    .create(getApplicationContext(), R.raw.s1);
  img = (ImageView) findViewById(R.id.imageView1);
  
  seekbarS = (SeekBar) findViewById(R.id.seekbarS);
  seekbar  = (SeekBar) findViewById(R.id.seekbar);
  // img.setBackgroundDrawable(animation);
  // img.setBackgroundResource(resid)
  // img.setImageBitmap(null);

  /*
   * btnStart = (Button)findViewById(R.id.btnStart); //btnStop =
   * (Button)findViewById(R.id.btnStop);
   * 
   * btnStart.setOnClickListener(new View.OnClickListener() {
   * 
   * @Override public void onClick(View v) { // TODO Auto-generated method
   * stub img.setImageBitmap(null); animation.start(); } });
   * 
   * btnStop.setOnClickListener(new View.OnClickListener() {
   * 
   * @Override public void onClick(View v) { // TODO Auto-generated method
   * stub animation.stop(); } });
   */
  img.setOnTouchListener(new OnTouchListener() {

   @Override
   public boolean onTouch(View v, MotionEvent event) {
   // if (level == 2) return false;
     
    int defaultScreenWidth = 480;
    int defaultScreenHeight = 800;
     
    //int defaultScreenWidth = 240;
    //int defaultScreenHeight = 320;
    
    
    // TODO Auto-generated method stub
    int[] viewCoords = new int[2];
    img.getLocationOnScreen(viewCoords);
    int touchX = (int) event.getX();
    int touchY = (int) event.getY();
    
    int imageX = touchX - viewCoords[0]; // viewCoords[0] is the X coordinate
    int imageY = touchY - viewCoords[1]; // viewCoords[1] is the y coordinate
    
    //Toast.makeText(getBaseContext(),"left = " + img.getLeft() + " top = " + img.getTop() + "bottom = " + img.getBottom() + " right = " + img.getRight() + touchX + " " + touchY + " imageX =" + imageX, Toast.LENGTH_SHORT).show();
    double scaleX = (img.getRight() / defaultScreenWidth) ;
    double scaleY = (img.getBottom() / defaultScreenHeight);
    if (img.getRight() >= defaultScreenWidth )
    {
     // man hinh lon hon
     scaleX = (img.getRight() / defaultScreenWidth) ;
     scaleY = (img.getBottom() / defaultScreenHeight);
    // touchX = (int) (scaleX * touchX);
    // touchY = (int) (scaleY * touchY);
     
    }else
    {
     // man hinh nho hon
     scaleX = (defaultScreenWidth / img.getRight()) ;
     scaleY = (defaultScreenHeight / img.getBottom() );
    // touchX = (int) (scaleX * touchX);
    // touchY = (int) (scaleY * touchY);
    }
    
    
    scaleX = ( (double) img.getRight() / (double) defaultScreenWidth) ;
    //Toast.makeText(getBaseContext(), ""+  img.getRight() + "/" + defaultScreenWidth + "=" +  scaleX + "* x=" + touchX + " Y =" + touchY , Toast.LENGTH_SHORT).show();
    
    scaleY = ( (double)img.getBottom() / (double)defaultScreenHeight);
    
    
    
    int touchX2 = (800  / defaultScreenWidth   ) * touchX;
    int touchY2 = (1280 / defaultScreenHeight  ) * touchY;
    
    //Toast.makeText(getBaseContext(), ""+  (135 * scaleX) + "*" +  scaleX + "* x=" + touchX + " Y =" + touchY , Toast.LENGTH_SHORT).show();
    
    
   // Toast.makeText(getBaseContext()," x=" + touchX + " Y =" + touchY , Toast.LENGTH_SHORT).show();
    
    if ((touchX >=(135 * scaleX)) && (touchX < (320* scaleX)) &&  (touchY >=150* scaleY) && (touchY < 280* scaleY)) // 480 x 800
    
    
   // if ((touchX >= ( 100 * scaleX )) && (touchX < 200 * scaleX) &&  (touchY >=80 * scaleY) && (touchY < 280 * scaleY))
    {
     if (animation.isRunning()) {
      animation.stop();
     }
     if (level == 1)
     {
      img.setBackgroundResource(R.drawable.head);
     }else
     {
      img.setBackgroundResource(R.drawable.gc_next);
     }
     
     
     animation = (AnimationDrawable) img.getBackground();
     animation.start();
     
     
      if (level == 1){
       
     if (SoundOn())  mMediaPlayerHEAD.start();
       checkIfAnimationDone(animation,girl.STANDING);
      }
      else
      {
       if (SoundOn()){
       MediaPlayer mMediaPlayerBUST = MediaPlayer
         .create(getApplicationContext(), R.raw.s8);     
       mMediaPlayerBUST.start();
       }
       checkIfAnimationDone(animation,girl.GA_NEXT);
      }
     
    }
    
    
    
    // bust
    if ((touchX >=150 * scaleX) && (touchX < 370 * scaleX) &&  (touchY >=390 * scaleY) && (touchY < 500 * scaleY))
    {
     if (animation.isRunning()) {
      animation.stop();
     }
     if (level == 1)
      img.setBackgroundResource(R.drawable.bustup);
     else
      img.setBackgroundResource(R.drawable.ge_next);
     
     animation = (AnimationDrawable) img.getBackground();
     animation.start();
     if (SoundOn())
     {
      if (level == 1)
      {
       MediaPlayer mMediaPlayerBUST = MediaPlayer
         .create(getApplicationContext(), R.raw.s4);     
       mMediaPlayerBUST.start();
      }else
      {
       MediaPlayer mMediaPlayerBUST = MediaPlayer
         .create(getApplicationContext(), R.raw.s6);     
       mMediaPlayerBUST.start();
      }
     }
     
     heart += 10;
     seekbar.setProgress(heart);
    // Toast.makeText(getBaseContext()," heart= " + heart + " level " + level, Toast.LENGTH_SHORT).show();
    // checkIfAnimationDone(animation,girl.GA_NEXT);
    // level++;
     if (heart <= 100)
     {
      checkIfAnimationDone(animation,girl.STANDING);
     }
     else
     {
     // Toast.makeText(getBaseContext()," heart=" + heart, Toast.LENGTH_SHORT).show();
      
      if (level != 2 ) level = 2;
      
      checkIfAnimationDone(animation,girl.GA_NEXT);
      seekbar.setProgress(0);
     }
     
    }
    return false;

   }
  });

 }

 @Override
 public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  img.setImageBitmap(null);
  animation = standing();
  animation.start();

 }

 @Override
 public void onPause() {
  super.onPause(); // Always call the superclass method first
  if (SoundOn())
  stopService(new Intent(getBaseContext(), MusicService.class));
  // mMediaPlayerHEAD.stop();
 }

 @Override
 public void onResume() {
  super.onPause(); // Always call the superclass method first
  if (SoundOn())
   startService(new Intent(getBaseContext(), MusicService.class));

 }

 private void checkIfAnimationDone(AnimationDrawable anim, final int doing) {
  final AnimationDrawable a = anim;
  int timeBetweenChecks = 300;
  Handler h = new Handler();
  h.postDelayed(new Runnable() {
   public void run() {
    if (a.getCurrent() != a.getFrame(a.getNumberOfFrames() - 1)) {
     checkIfAnimationDone(a, doing);
    
    } else {
     // Toast.makeText(getApplicationContext(),
     // "ANIMATION DONE!", Toast.LENGTH_SHORT).show();
     animation.stop();
     
     if (doing == girl.STANDING)
      animation = standing();
     
     if (doing == girl.GA_NEXT)
      animation = ga_next();
     
     animation.start();
    }
   }
  }, timeBetweenChecks);
 };
 protected AnimationDrawable ga_next() {

  img.setBackgroundResource(R.drawable.ga_next);
  // Get the background, which has been compiled to an AnimationDrawable
  // object.
  AnimationDrawable frameAnimation = (AnimationDrawable) img
    .getBackground();
  return frameAnimation;
 }
 protected AnimationDrawable nguc() {

  img.setBackgroundResource(R.drawable.bustup);
  // Get the background, which has been compiled to an AnimationDrawable
  // object.
  AnimationDrawable frameAnimation = (AnimationDrawable) img
    .getBackground();
  return frameAnimation;
 }

 protected AnimationDrawable head() {
  img.setBackgroundResource(R.drawable.head);
  // Get the background, which has been compiled to an AnimationDrawable
  // object.
  AnimationDrawable frameAnimation = (AnimationDrawable) img
    .getBackground();
  return frameAnimation;
 }

 protected AnimationDrawable standing() {

  img.setBackgroundResource(R.drawable.standing);
  // Get the background, which has been compiled to an AnimationDrawable
  // object.
  AnimationDrawable frameAnimation = (AnimationDrawable) img
    .getBackground();
  return frameAnimation;
  // Start the animation (looped playback by default).
  // frameAnimation.start();
  /*
   * 
   * int duration = 150; BitmapDrawable frame1 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a001);
   * BitmapDrawable frame2 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a002);
   * BitmapDrawable frame3 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a003);
   * BitmapDrawable frame4 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a004);
   * BitmapDrawable frame5 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a005);
   * BitmapDrawable frame6 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a006);
   * BitmapDrawable frame7 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a007);
   * BitmapDrawable frame8 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a008);
   * BitmapDrawable frame9 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a009);
   * BitmapDrawable frame10 =
   * (BitmapDrawable)getResources().getDrawable(R.drawable.a010);
   * 
   * AnimationDrawable animation2 = new AnimationDrawable();
   * 
   * animation2.addFrame(frame1, duration); animation2.addFrame(frame2,
   * duration); animation2.addFrame(frame3, duration);
   * animation2.addFrame(frame4, duration); animation2.addFrame(frame5,
   * duration); animation2.addFrame(frame6, duration);
   * animation2.addFrame(frame7, duration); animation2.addFrame(frame8,
   * duration); animation2.addFrame(frame9, duration);
   * animation2.addFrame(frame10, duration);
   * 
   * animation2.setOneShot(false); return animation2;
   */
 }
 private boolean SoundOn()
 {
  return false;
 }
}

    

Monday, 10 June 2013

upload and crop from camera android

package com.example.imagegalleryupload;

import java.io.ByteArrayOutputStream;

import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
 final static int REQUEST_CODE = 0;
 //keep track of camera capture intent
 final int CAMERA_CAPTURE = 3;
 
 
 private String selectedImagePath;
 String mUploadMessage = "";
 ImageView img ;
 private Uri imageUri;
 Uri selectedImageUri;
 
 //keep track of cropping intent
 final int PIC_CROP = 2;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  img = (ImageView) findViewById(R.id.imageView1);
  
 }

 

 public void btn_Upload_onClick(View view) {
  // Intent chon hinh tu gallery.
  Intent imageGalleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
  imageGalleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
  imageGalleryIntent.setType("image/*");
  // Intent chup hinh tu camera
  final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);       
     Intent chooserIntent = Intent.createChooser(imageGalleryIntent, "Image Chooser");
  chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });
/*
  Intent intent = new Intent();
  intent.setType("image/*");
  intent.setAction(Intent.ACTION_GET_CONTENT);
  startActivityForResult(Intent.createChooser(intent, "Select Picture"),
    REQUEST_CODE);
 */
  startActivityForResult(chooserIntent, REQUEST_CODE);
 }
 public String getRealPath(Uri uri) {
  String[] projection = { MediaStore.Images.Media.DATA };
  Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
  int column_index = cursor
    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  cursor.moveToFirst();
  return cursor.getString(column_index);
 }
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
  
  super.onActivityResult(requestCode, resultCode, data);
  /*
   if (requestCode == REQUEST_CODE) {
     if (null == this.mUploadMessage) {
              return;
          }
          Uri result;
          if (resultCode != RESULT_OK) {
              result = null;
          } else {
              result = data == null ? this.imageUri : data.getData(); // retrieve from the private variable if the intent is null
          }
          this.mUploadMessage = result.getPath();
       img.setImageURI(result);
          this.mUploadMessage = null;
       Toast.makeText(this, mUploadMessage, Toast.LENGTH_LONG)
    .show();
     
      }
  */
   Toast toast = Toast.makeText(this, "" + requestCode + " * " + resultCode, Toast.LENGTH_LONG);
   toast.show();    
  try {
   
   switch (requestCode) {

   case REQUEST_CODE:
    selectedImageUri = data.getData();
    
// from camera
if ( data.getAction() != null)
    { 
 final ContentResolver cr = getContentResolver(); 
     final String[] p1 = new String[] {
                     MediaStore.Images.ImageColumns._ID,
                     MediaStore.Images.ImageColumns.DATE_TAKEN
             };
      
      Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");     
            if ( c1.moveToFirst() ) {
               String uristringpic = "content://media/external/images/media/" + c1.getInt(0);
               Uri newuri = Uri.parse(uristringpic);
               selectedImageUri = newuri;
            }
     performCrop();
     return;
    }
    
    if (resultCode == Activity.RESULT_OK) { 
     selectedImageUri = data.getData();
     // data gives you the image uri. Try to convert that to
     // bitmap
     //selectedImageUri = data.getData();
     selectedImagePath = getRealPath(selectedImageUri);     
     img.setImageURI(selectedImageUri);
    break;
   } else if (resultCode == Activity.RESULT_CANCELED) {
    // Log.e(TAG, "Selecting picture cancelled");
   }
    
 /*
    if (android.os.Build.VERSION.SDK_INT < 13 )
     {     
      // case: android 2.3 va chup hinh tu camera
      // ghi chu: trong android 2.3 , chup hinh tu camera thi data.getData() == null,
      // test tren Samsung galaxy Y s5360
      if (selectedImageUri == null)
      {     
       final ContentResolver cr = getContentResolver(); 
       final String[] p1 = new String[] {
                       MediaStore.Images.ImageColumns._ID,
                       MediaStore.Images.ImageColumns.DATE_TAKEN
               };
        
        Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");     
              if ( c1.moveToFirst() ) {
                 String uristringpic = "content://media/external/images/media/" + c1.getInt(0);
                 Uri newuri = Uri.parse(uristringpic);
                 selectedImageUri = newuri;
           //      Log.i("TAG", "newuri   "+newuri);
                 img.setImageURI(newuri);
                 performCrop(); 
                 return;
              }
      } 
     }
    
    
    
    
    
    if (resultCode == Activity.RESULT_OK) { 
      selectedImageUri = data.getData();
      // data gives you the image uri. Try to convert that to
      // bitmap
      //selectedImageUri = data.getData();
      selectedImagePath = getRealPath(selectedImageUri);     
      img.setImageURI(selectedImageUri);
     break;
    } else if (resultCode == Activity.RESULT_CANCELED) {
     // Log.e(TAG, "Selecting picture cancelled");
    }
    */   
    break;
    
    
   case PIC_CROP:
    if (resultCode == Activity.RESULT_OK) { 
    //get the returned data
    Bundle extras = data.getExtras();
    //get the cropped bitmap
    Bitmap thePic = extras.getParcelable("data");
    
    
    //display the returned cropped image
    Uri cropImage = getImageUri(getBaseContext(), thePic);
    selectedImagePath = getRealPath(cropImage); 
    Toast.makeText(this, "" + selectedImagePath + " * " + resultCode, Toast.LENGTH_LONG).show();
     
     
     
    img.setImageBitmap(thePic);
    } else if (resultCode == Activity.RESULT_CANCELED) {
     // Log.e(TAG, "Selecting picture cancelled");
    }
    break;
   
    
   }
  } catch (Exception e) {
    Log.e("error 1", "Exception in onActivityResult : " + e.getMessage());
  }
   
 }
 public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
  }
 private void performCrop(){
  
  try {
   //call the standard crop action intent (the user device may not support it)
   Intent cropIntent = new Intent("com.android.camera.action.CROP");
       //indicate image type and Uri
   cropIntent.setDataAndType(selectedImageUri, "image/*");
       //set crop properties
   cropIntent.putExtra("crop", "true");
       //indicate aspect of desired crop
   cropIntent.putExtra("aspectX", 1);
   cropIntent.putExtra("aspectY", 1);
       //indicate output X and Y
   cropIntent.putExtra("outputX", 256);
   cropIntent.putExtra("outputY", 256);
       //retrieve data on return
   cropIntent.putExtra("return-data", true);
       //start the activity - we handle returning in onActivityResult
   startActivityForResult(cropIntent, PIC_CROP);
  }
  catch(ActivityNotFoundException anfe){
      //display an error message
      String errorMessage = "Whoops - your device doesn't support the crop action!";
      Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
      toast.show();
  }
 }

}

Sunday, 9 June 2013

upload image from camera + gallery android

package com.example.imagegalleryupload;

import java.io.ByteArrayOutputStream;

import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
 final static int REQUEST_CODE = 0;
 //keep track of camera capture intent
 final int CAMERA_CAPTURE = 3;
 
 
 private String selectedImagePath;
 String mUploadMessage = "";
 ImageView img ;
 private Uri imageUri;
 Uri selectedImageUri;
 
 //keep track of cropping intent
 final int PIC_CROP = 2;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  img = (ImageView) findViewById(R.id.imageView1);
  
 }

 

 public void btn_Upload_onClick(View view) {
  // Intent chon hinh tu gallery.
  Intent imageGalleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
  imageGalleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
  imageGalleryIntent.setType("image/*");
  // Intent chup hinh tu camera
  final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);       
     Intent chooserIntent = Intent.createChooser(imageGalleryIntent, "Image Chooser");
  chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });
/*
  Intent intent = new Intent();
  intent.setType("image/*");
  intent.setAction(Intent.ACTION_GET_CONTENT);
  startActivityForResult(Intent.createChooser(intent, "Select Picture"),
    REQUEST_CODE);
 */
  startActivityForResult(chooserIntent, REQUEST_CODE);
 }
 public String getRealPath(Uri uri) {
  String[] projection = { MediaStore.Images.Media.DATA };
  Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
  int column_index = cursor
    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  cursor.moveToFirst();
  return cursor.getString(column_index);
 }
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
  
  super.onActivityResult(requestCode, resultCode, data);
  /*
   if (requestCode == REQUEST_CODE) {
     if (null == this.mUploadMessage) {
              return;
          }
          Uri result;
          if (resultCode != RESULT_OK) {
              result = null;
          } else {
              result = data == null ? this.imageUri : data.getData(); // retrieve from the private variable if the intent is null
          }
          this.mUploadMessage = result.getPath();
       img.setImageURI(result);
          this.mUploadMessage = null;
       Toast.makeText(this, mUploadMessage, Toast.LENGTH_LONG)
    .show();
     
      }
  */
   Toast toast = Toast.makeText(this, "" + requestCode + " * " + resultCode, Toast.LENGTH_LONG);
   toast.show();
   
   
    
  try {
   
   switch (requestCode) {

   case REQUEST_CODE:
    if (android.os.Build.VERSION.SDK_INT < 13 )
     {
      selectedImageUri = data.getData();
      // case: android 2.3 va chup hinh tu camera
      if (selectedImageUri == null)
      {     
       final ContentResolver cr = getContentResolver(); 
       final String[] p1 = new String[] {
                      MediaStore.Images.ImageColumns._ID,
                      MediaStore.Images.ImageColumns.DATE_TAKEN
              };      
       Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");     
             if ( c1.moveToFirst() ) {
                String uristringpic = "content://media/external/images/media/" +c1.getInt(0);
                Uri newuri = Uri.parse(uristringpic);
                selectedImageUri = newuri;
                Log.i("TAG", "newuri   "+newuri);
                img.setImageURI(newuri);
                performCrop(); 
                
                return;
             }
      } 
     }
    
    if (resultCode == Activity.RESULT_OK) {     
     //user is returning from capturing an image using the camera
     if(requestCode == CAMERA_CAPTURE){
      //get the Uri for the captured image
      selectedImageUri = data.getData();
      //carry out the crop operation
      performCrop();        
     }
     //user is returning from cropping the image
     else if(requestCode == PIC_CROP){       
       //get the returned data
       Bundle extras = data.getExtras();
       //get the cropped bitmap
       Bitmap thePic = extras.getParcelable("data");
       //display the returned cropped image
       img.setImageBitmap(thePic);
       return;
      }     
      // data gives you the image uri. Try to convert that to
      // bitmap
      //selectedImageUri = data.getData();
      selectedImagePath = getRealPath(selectedImageUri);     
      img.setImageURI(selectedImageUri);
     break;
    } else if (resultCode == Activity.RESULT_CANCELED) {
     // Log.e(TAG, "Selecting picture cancelled");
    }
    break;
   case PIC_CROP:
    if (resultCode == Activity.RESULT_OK) { 
    //get the returned data
    Bundle extras = data.getExtras();
    //get the cropped bitmap
    Bitmap thePic = extras.getParcelable("data");
    
    
    //display the returned cropped image
    Uri cropImage = getImageUri(getBaseContext(), thePic);
    selectedImagePath = getRealPath(cropImage); 
    Toast.makeText(this, "" + selectedImagePath + " * " + resultCode, Toast.LENGTH_LONG).show();
     
     
     
    img.setImageBitmap(thePic);
    } else if (resultCode == Activity.RESULT_CANCELED) {
     // Log.e(TAG, "Selecting picture cancelled");
    }
    break;
   
    
   }
  } catch (Exception e) {
    Log.e("error 1", "Exception in onActivityResult : " + e.getMessage());
  }
   
 }
 public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
  }
 private void performCrop(){
  
  try {
   //call the standard crop action intent (the user device may not support it)
   Intent cropIntent = new Intent("com.android.camera.action.CROP");
       //indicate image type and Uri
   cropIntent.setDataAndType(selectedImageUri, "image/*");
       //set crop properties
   cropIntent.putExtra("crop", "true");
       //indicate aspect of desired crop
   cropIntent.putExtra("aspectX", 1);
   cropIntent.putExtra("aspectY", 1);
       //indicate output X and Y
   cropIntent.putExtra("outputX", 256);
   cropIntent.putExtra("outputY", 256);
       //retrieve data on return
   cropIntent.putExtra("return-data", true);
       //start the activity - we handle returning in onActivityResult
   startActivityForResult(cropIntent, PIC_CROP);
  }
  catch(ActivityNotFoundException anfe){
      //display an error message
      String errorMessage = "Whoops - your device doesn't support the crop action!";
      Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
      toast.show();
  }
 }

}

Thursday, 6 June 2013

android AnimationDrawable stop

android AnimationDrawable stop
private void checkIfAnimationDone(AnimationDrawable anim){
            final AnimationDrawable a = anim;
            int timeBetweenChecks = 300;
            Handler h = new Handler();
            h.postDelayed(new Runnable(){
                public void run(){
                    if (a.getCurrent() != a.getFrame(a.getNumberOfFrames() - 1)){
                        checkIfAnimationDone(a);
                    } else{
                        Toast.makeText(getApplicationContext(), "ANIMATION DONE!", Toast.LENGTH_SHORT).show();
            
                    }
                }
            }, timeBetweenChecks);
    };

remove action bar android

//remove action bar android


        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
       
        setContentView(R.layout.main_frame);
     

android animation fragment transition

 android animation fragment transition

http://adblogcat.com/fragment-transition-animations-while-hiding-the-previous-fragment/

Wednesday, 5 June 2013

animate picture in android with frame


http://www.c-sharpcorner.com/UploadFile/88b6e5/frame-by-frame-animation/
http://digitaldumptruck.jotabout.com/?p=813

INSTALL_FAILED_INSUFFICIENT_STORAGE

 INSTALL_FAILED_INSUFFICIENT_STORAGE and one more attribute of <manifest> tag
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.musicbackground"
    android:versionCode="1"
    android:versionName="1.0"
    android:installLocation="preferExternal"
    >


Monday, 3 June 2013

android version on market

android version on market. Data collected during a 14-day period ending on May 1, 2013.
Any versions with less than 0.1% distribution are not shown.


Wednesday, 29 May 2013

choose image from gallery android


choose image from gallery android in my app, the user need to upload their profile from gallery pop up. I write simple project to demonstrate how to code. ^^





clear notification android onclick

clear notification android onclick

When you create notification , you need to set flag property:
Notification noti = mBuilder.build();
noti.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;


Tuesday, 28 May 2013

multi language android

 multi language android is easy to config. Once you’ve decided on the languages you will support, create the resource subdirectories and string resource files.
Create additional values directories inside res/ that include a hyphen and the ISO country code at the end of the directory name. See ISO country code
 
For example:
 
MyProject/
    res/
       values/
           strings.xml
       values-es/
           strings.xml
       values-fr/
           strings.xml
 
 
 

For example, the following are some different string resource files for different languages.


English (default locale), /values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   
<string name="title">My Application</string>
   
<string name="hello_world">Hello World!</string>
</resources> Spanish, /values-es/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   
<string name="title">Mi Aplicación</string>
   
<string name="hello_world">Hola Mundo!</string>
</resources>
 

ISO country code

ISO-639 Language Codes

Table 20-2 ISO-639 Language Codes
Language
ISO-639 Language Code
Abkhazian
ab
Afar
aa
Afrikaans
af
Albanian
sq
Amharic
am
Arabic
ar
Armenian
hy
Assamese
as
Aymara
ay
Azerbaijani
az
Bashkir
ba
Basque
eu
Bengali (Bangla)
bn
Bhutani
dz
Bihari
bh
Bislama
bi
Breton
br
Bulgarian
bg
Burmese
my
Byelorussian (Belarusian)
be
Cambodian
km
Catalan
ca
Chinese (Simplified)
zh
Chinese (Traditional)
zh
Corsican
co
Croatian
hr
Czech
cs
Danish
da
Dutch
nl
English
en
Esperanto
eo
Estonian
et
Faeroese
fo
Farsi
fa
Fiji
fj
Finnish
fi
French
fr
Frisian
fy
Galician
gl
Gaelic (Scottish)
gd
Gaelic (Manx)
gv
Georgian
ka
German
de
Greek
el
Greenlandic
kl
Guarani
gn
Gujarati
gu
Hausa
ha
Hebrew
he
Hindi
hi
Hungarian
hu
Icelandic
is
Indonesian
id
Interlingua
ia
Interlingue
ie
Inuktitut
iu
Inupiak
ik
Irish
ga
Italian
it
Japanese
ja
Javanese
ja
Kannada
kn
Kashmiri
ks
Kazakh
kk
Kinyarwanda (Ruanda)
rw
Kirghiz
ky
Kirundi (Rundi)
rn
Korean
ko
Kurdish
ku
Laothian
lo
Latin
la
Latvian (Lettish)
lv
Limburgish ( Limburger)
li
Lingala
ln
Lithuanian
lt
Macedonian
mk
Malagasy
mg
Malay
ms
Malayalam
ml
Maltese
mt
Maori
mi
Marathi
mr
Moldavian
mo
Mongolian
mn
Nauru
na
Nepali
ne
Norwegian
no
Occitan
oc
Oriya
or
Oromo (Afan, Galla)
om
Pashto (Pushto)
ps
Polish
pl
Portuguese
pt
Punjabi
pa
Quechua
qu
Rhaeto-Romance
rm
Romanian
ro
Russian
ru
Samoan
sm
Sangro
sg
Sanskrit
sa
Serbian
sr
Serbo-Croatian
sh
Sesotho
st
Setswana
tn
Shona
sn
Sindhi
sd
Sinhalese
si
Siswati
ss
Slovak
sk
Slovenian
sl
Somali
so
Spanish
es
Sundanese
su
Swahili (Kiswahili)
sw
Swedish
sv
Tagalog
tl
Tajik
tg
Tamil
ta
Tatar
tt
Telugu
te
Thai
th
Tibetan
bo
Tigrinya
ti
Tonga
to
Tsonga
ts
Turkish
tr
Turkmen
tk
Twi
tw
Uighur
ug
Ukrainian
uk
Urdu
ur
Uzbek
uz
Vietnamese
vi
Volapük
vo
Welsh
cy
Wolof
wo
Xhosa
xh
Yiddish
yi
Yoruba
yo
Zulu
zu
Code Country Name
AF AFGHANISTAN
AX ÅLAND ISLANDS
AL ALBANIA
DZ ALGERIA
AS AMERICAN SAMOA
AD ANDORRA
AO ANGOLA
AI ANGUILLA
AQ ANTARCTICA
AG ANTIGUA AND BARBUDA
AR ARGENTINA
AM ARMENIA
AW ARUBA
AU AUSTRALIA
AT AUSTRIA
AZ AZERBAIJAN
BS BAHAMAS
BH BAHRAIN
BD BANGLADESH
BB BARBADOS
BY BELARUS
BE BELGIUM
BZ BELIZE
BJ BENIN
BM BERMUDA
BT BHUTAN
BO BOLIVIA, PLURINATIONAL STATE OF
BQ BONAIRE, SINT EUSTATIUS AND SABA
BA BOSNIA AND HERZEGOVINA
BW BOTSWANA
BV BOUVET ISLAND
BR BRAZIL
IO BRITISH INDIAN OCEAN TERRITORY
BN BRUNEI DARUSSALAM
BG BULGARIA
BF BURKINA FASO
BI BURUNDI
KH CAMBODIA
CM CAMEROON
CA CANADA
CV CAPE VERDE
KY CAYMAN ISLANDS
CF CENTRAL AFRICAN REPUBLIC
TD CHAD
CL CHILE
CN CHINA
CX CHRISTMAS ISLAND
CC COCOS (KEELING) ISLANDS
CO COLOMBIA
KM COMOROS
CG CONGO
CD CONGO, THE DEMOCRATIC REPUBLIC OF THE
CK COOK ISLANDS
CR COSTA RICA
CI CÔTE D'IVOIRE
HR CROATIA
CU CUBA
CW CURAÇAO
CY CYPRUS
CZ CZECH REPUBLIC
DK DENMARK
DJ DJIBOUTI
DM DOMINICA
DO DOMINICAN REPUBLIC
EC ECUADOR
EG EGYPT
SV EL SALVADOR
GQ EQUATORIAL GUINEA
ER ERITREA
EE ESTONIA
ET ETHIOPIA
FK FALKLAND ISLANDS (MALVINAS)
FO FAROE ISLANDS
FJ FIJI
FI FINLAND
FR FRANCE
GF FRENCH GUIANA
PF FRENCH POLYNESIA
TF FRENCH SOUTHERN TERRITORIES
GA GABON
GM GAMBIA
GE GEORGIA
DE GERMANY
GH GHANA
GI GIBRALTAR
GR GREECE
GL GREENLAND
GD GRENADA
GP GUADELOUPE
GU GUAM
GT GUATEMALA
GG GUERNSEY
GN GUINEA
GW GUINEA-BISSAU
GY GUYANA
HT HAITI
HM HEARD ISLAND AND MCDONALD ISLANDS
VA HOLY SEE (VATICAN CITY STATE)
HN HONDURAS
HK HONG KONG
HU HUNGARY
IS ICELAND
IN INDIA
ID INDONESIA
IR IRAN, ISLAMIC REPUBLIC OF
IQ IRAQ
IE IRELAND
IM ISLE OF MAN
IL ISRAEL
IT ITALY
JM JAMAICA
JP JAPAN
JE JERSEY
JO JORDAN
KZ KAZAKHSTAN
KE KENYA
KI KIRIBATI
KP KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF
KR KOREA, REPUBLIC OF
KW KUWAIT
KG KYRGYZSTAN
LA LAO PEOPLE'S DEMOCRATIC REPUBLIC
LV LATVIA
LB LEBANON
LS LESOTHO
LR LIBERIA
LY LIBYA
LI LIECHTENSTEIN
LT LITHUANIA
LU LUXEMBOURG
MO MACAO
MK MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF
MG MADAGASCAR
MW MALAWI
MY MALAYSIA
MV MALDIVES
ML MALI
MT MALTA
MH MARSHALL ISLANDS
MQ MARTINIQUE
MR MAURITANIA
MU MAURITIUS
YT MAYOTTE
MX MEXICO
FM MICRONESIA, FEDERATED STATES OF
MD MOLDOVA, REPUBLIC OF
MC MONACO
MN MONGOLIA
ME MONTENEGRO
MS MONTSERRAT
MA MOROCCO
MZ MOZAMBIQUE
MM MYANMAR
NA NAMIBIA
NR NAURU
NP NEPAL
NL NETHERLANDS
NC NEW CALEDONIA
NZ NEW ZEALAND
NI NICARAGUA
NE NIGER
NG NIGERIA
NU NIUE
NF NORFOLK ISLAND
MP NORTHERN MARIANA ISLANDS
NO NORWAY
OM OMAN
PK PAKISTAN
PW PALAU
PS PALESTINE, STATE OF
PA PANAMA
PG PAPUA NEW GUINEA
PY PARAGUAY
PE PERU
PH PHILIPPINES
PN PITCAIRN
PL POLAND
PT PORTUGAL
PR PUERTO RICO
QA QATAR
RE RÉUNION
RO ROMANIA
RU RUSSIAN FEDERATION
RW RWANDA
BL SAINT BARTHÉLEMY
SH SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA
KN SAINT KITTS AND NEVIS
LC SAINT LUCIA
MF SAINT MARTIN (FRENCH PART)
PM SAINT PIERRE AND MIQUELON
VC SAINT VINCENT AND THE GRENADINES
WS SAMOA
SM SAN MARINO
ST SAO TOME AND PRINCIPE
SA SAUDI ARABIA
SN SENEGAL
RS SERBIA
SC SEYCHELLES
SL SIERRA LEONE
SG SINGAPORE
SX SINT MAARTEN (DUTCH PART)
SK SLOVAKIA
SI SLOVENIA
SB SOLOMON ISLANDS
SO SOMALIA
ZA SOUTH AFRICA
GS SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS
SS SOUTH SUDAN
ES SPAIN
LK SRI LANKA
SD SUDAN
SR SURINAME
SJ SVALBARD AND JAN MAYEN
SZ SWAZILAND
SE SWEDEN
CH SWITZERLAND
SY SYRIAN ARAB REPUBLIC
TW TAIWAN, PROVINCE OF CHINA
TJ TAJIKISTAN
TZ TANZANIA, UNITED REPUBLIC OF
TH THAILAND
TL TIMOR-LESTE
TG TOGO
TK TOKELAU
TO TONGA
TT TRINIDAD AND TOBAGO
TN TUNISIA
TR TURKEY
TM TURKMENISTAN
TC TURKS AND CAICOS ISLANDS
TV TUVALU
UG UGANDA
UA UKRAINE
AE UNITED ARAB EMIRATES
GB UNITED KINGDOM
US UNITED STATES
UM UNITED STATES MINOR OUTLYING ISLANDS
UY URUGUAY
UZ UZBEKISTAN
VU VANUATU
VE VENEZUELA, BOLIVARIAN REPUBLIC OF
VN VIET NAM
VG VIRGIN ISLANDS, BRITISH
VI VIRGIN ISLANDS, U.S.
WF WALLIS AND FUTUNA
EH WESTERN SAHARA
YE YEMEN
ZM ZAMBIA
ZW ZIMBABWE