Andrid pick photo from android gallery

0 意見

These codes is reference from this link.

public class ImageGalleryDemoActivity extends Activity {
     
     
    private static int RESULT_LOAD_IMAGE = 1;
     
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View arg0) {
                 
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                 
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }
     
     
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
 
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
             
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
         
        }
     
     
    }
}

Android Matrix to handle bitmap

0 意見

Android Developer Matrix


byte[] data; // from onPictureTaken

FileOutputStream fos = new FileOutputStream(pictureFile);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

Matrix matrix = new Matrix();
matrix.setRotate(-90);  // rotate -90 degree
matrix.preScale(1, -1); // mirror
                
Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
rotateBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

fos.close();

Android camera support size for parameter

0 意見

Camera mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
Camera.Parameters params = mCamera.getParameters();
List supportSizes = params.getSupportedPreviewSizes();
Camera.Size selectedSize = supportSizes.get(3); //choose the suitable size
params.setPreviewSize(selectedSize.width, selectedSize.height);
mCamera.setParameters(params);

Android get screen size

0 意見

From Stack Overflow


Display display = getWindowManager().getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
// displzySize.x
// displaySize.y



WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();



Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

Android ImageView set image view

0 意見


File file = new  File(“/images/image.jpg”);
if(file.exists()){
    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());

    ImageView img = (ImageView) findViewById(R.id.image);
    img.setImageBitmap(bitmap);

    // drawable
    img.setImageResource(R.drawable.icon_delta);
}

Android AlertDialog

0 意見

mAlert =  new AlertDialog.Builder(this);
mAlert.setTitle("Hint");
mAlert.setMessage("Connection Error");
    
DialogInterface.OnClickListener OnClick = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
    }
};
    
mAlert.setNeutralButton("OK", OnClick);
mAlert.show();

Android get gps location by network or gps

0 意見

mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Location gpsLocation = null;
Location networkLocation = null;
mLocationManager.removeUpdates(listener);
        
gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER, R.string.not_support_gps);
networkLocation = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER, R.string.not_support_network);

if (gpsLocation != null && networkLocation != null) {
    updateUILocation(getBetterLocation(gpsLocation, networkLocation)); //not implement get better location function
} else if (gpsLocation != null) {
    updateUILocation(gpsLocation);
} else if (networkLocation != null) {
    updateUILocation(networkLocation);
}

private Location requestUpdatesFromProvider(final String provider, final int errorResId) {
    Location location = null;
    if (mLocationManager.isProviderEnabled(provider)) {
        mLocationManager.requestLocationUpdates(provider, TEN_SECONDS, TEN_METERS, listener);
        location = mLocationManager.getLastKnownLocation(provider);
    } else {
        Toast.makeText(this, errorResId, Toast.LENGTH_LONG).show();
    }
    return location;
}

Android Handler and Message

0 意見

Handler class:
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue.

Message class:
Defines a message containing a description and arbitrary data object that can be sent to a Handler. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.

private static final int LAT = 2;
private static final int LONG= 3;

Handler mHandler;

mHandler = new Handler() {
    public void handleMessage(Message msg) {
      switch (msg.what) {
        case LAT:
          String str = (String)msg.obj;
          break;
        case LONG:
          String str = (String)msg.obj;
          break;
      }
    }
};

// notify
Message.obtain(mHandler, LAT, location.getLatitude()+"").sendToTarget();
Message.obtain(mHandler, LONG,location.getLongitude()+"").sendToTarget();

Android LocationListener

0 意見

private final LocationListener listener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            // A new location update is received.  Do something useful with it.  Update the UI with
            // the location update.
            updateUILocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

Android create a dialog class to open GPS settings

0 意見

this example is created by Android developer example

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) new EnableGpsDialogFragment().show(getFragmentManager(), "enableGpsDialog");

private void enableLocationSettings() {
    Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(settingsIntent);
}

private class EnableGpsDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
            .setTitle(R.string.enable_gps)
            .setMessage(R.string.enable_gps_dialog)
            .setPositiveButton(R.string.enable_gps, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                enableLocationSettings();
            }
        })
        .create();
    }
}

Android listview

0 意見

 private class ItemsAdapter extends BaseAdapter{
 String[] items;
 
 public ItemsAdapter(Context context, int textViewResourceId, String[] items)
 {
     this.items = items;
 }
  
 @Override
 public View getView(final int position, View convertView,ViewGroup parent)
 {
  ImageView image;
  TextView mDescription;
  View view = convertView;
       
  if (view == null)
  {
   LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   view = vi.inflate(R.layout.site_menu_row, null);
  }
       
  image = (ImageView) view.findViewById(R.id.site_menu_image);
  mDescription = (TextView) view.findViewById(R.id.site_menu_value);
       
  image.setImageResource(R.drawable.line_20);
  mDescription.setText(items[position]);
       
  return view;
 }
  
 public int getCount() 
 {
  return items.length;
 }
  
 public Object getItem(int position)
 {
  return null;
 }
  
 public long getItemId(int position)
 {
  return position;
 }
}
// create
ListView listView = new ListView(getActivity());
        
ItemsAdapter itemsAdapter = new ItemsAdapter(getActivity(), R.layout.site_menu_row, menu_desc);
        
listView.setAdapter(itemsAdapter);
// site_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="100dp"
    android:layout_height="fill_parent">
    
 <ImageView android:id="@+id/site_menu_image"
   android:layout_width="50dp"
   android:layout_height="50dp"
   android:padding="10dip"
   android:src="@drawable/line_23"/>
 
 <TextView android:id="@+id/site_menu_value"
     android:layout_width="200dip" 
     android:layout_height="fill_parent"
     style="@style/SiteValue"
     android:text="" />
 
</LinearLayout>

Android listview child number return 0 after setAdapter

0 意見

When setAdapter in listview, it may get the child number is retrun zero. just use the Runnable() to solve it. see the following tutorial.

ListView lister1 = (ListView) findViewById(R.id.site_edit_lv1);
lister1.post(new Runnable(){
    public void run(){
        if (list1.length == lister1.getChildCount()){
	    for(int i=0 ; i<lister1.getChildCount() ; i++)
	    {
	    	View view = lister1.getChildAt(i);
	    	EditText et = (EditText)view.findViewById(R.id.edit_row_value);			
	    	et.setText(Sites.get(selectIndex)[i]);
	    }
	 }
    }
});

Android Edittext set focus

0 意見

EditText et = (EditText)view.findViewById(R.id.edit_text);
et.requestFocus();

Android ProgressDialog

0 意見

ProgressDialog dialog = ProgressDialog.show(this, "Hint", "Connecting, please wait...", false);
dialog.show();
dialog.dismiss();

ProgressDialog | Android Developer

Android get position from ContextItemSelected

0 意見


AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;