Showing posts with label android tips. Show all posts
Showing posts with label android tips. Show all posts

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();
  }
 }

}

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"
    >


Sunday, 2 June 2013

android soft keyboard move up

android soft keyboard move up: when soft keyboard show, it move up the layout


Use
 
         android:windowSoftInputMode="adjustPan"

android onresume restart activity

android onresume restart activity: This code I get from stackoverflow.

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>
 

Monday, 27 May 2013

android rest client applications

android rest client applications from Google I/O 2010.


 REST Method Implementation Patterns
• Introducing three design patterns to handle REST methods
– Use a Service API
– Use the ContentProvider API
– Use the ContentProvider API and a SyncAdapter

1)  Use a Service API

Use Service API


 2) Use the ContentProvider API



3)  Use the ContentProvider API and a SyncAdapter




PDF FILE: http://dl.google.com/googleio/2010/android-developing-RESTful-android-apps.pdf

Sunday, 26 May 2013

getactionbar in fragment

I  call getactionbar in fragment but the function is not recognized. I search on Google and the solution is very simple.



ActionBar actionBar = getActivity().getActionBar();
   actionBar.setDisplayHomeAsUpEnabled(true);
 
 
 
NOTE 
You can control the behaviors and visibility of the action bar with the ActionBar APIs, which were added in Android 3.0 (API level 11). Remember!

Thursday, 23 May 2013