Example usage for android.media ExifInterface saveAttributes

List of usage examples for android.media ExifInterface saveAttributes

Introduction

In this page you can find the example usage for android.media ExifInterface saveAttributes.

Prototype

public void saveAttributes() throws IOException 

Source Link

Document

Save the tag data into the original image file.

Usage

From source file:Main.java

public static void compressFileIfNeeded(String filePath) {
    File f = new File(filePath);

    Bitmap bitmap;/*ww  w. ja  va  2  s.c om*/
    bitmap = BitmapFactory.decodeFile(filePath);
    int MAX_IMAGE_SIZE = 1000 * 1024;
    int streamLength = (int) f.length();
    if (streamLength > MAX_IMAGE_SIZE) {
        int compressQuality = 105;
        ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
        while (streamLength >= MAX_IMAGE_SIZE && compressQuality > 5) {
            try {
                bmpStream.flush();//to avoid out of memory error
                bmpStream.reset();
            } catch (IOException e) {
                e.printStackTrace();
            }
            compressQuality -= 5;
            bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
            byte[] bmpPicByteArray = bmpStream.toByteArray();
            streamLength = bmpPicByteArray.length;
            Log.d("test upload", "Quality: " + compressQuality);
            Log.d("test upload", "Size: " + streamLength);
        }

        FileOutputStream fo;

        try {
            f.delete();
            f = new File(filePath);
            fo = new FileOutputStream(f);
            fo.write(bmpStream.toByteArray());
            fo.flush();
            fo.close();
            ExifInterface exif = new ExifInterface(f.getAbsolutePath());
            exif.setAttribute(ExifInterface.TAG_ORIENTATION, "6");
            exif.saveAttributes();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static boolean copyExifRotation(File sourceFile, File destFile) {
    if (sourceFile == null || destFile == null)
        return false;
    try {//from w  w w  .  j  a  va  2s. co m
        ExifInterface exifSource = new ExifInterface(sourceFile.getAbsolutePath());
        ExifInterface exifDest = new ExifInterface(destFile.getAbsolutePath());
        exifDest.setAttribute(ExifInterface.TAG_ORIENTATION,
                exifSource.getAttribute(ExifInterface.TAG_ORIENTATION));
        exifDest.saveAttributes();
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:Main.java

/**
 * Store the exif attributes in the passed image file using the TAGS stored in the passed bundle
 *
 * @param filepath/* w w w .j a v a2  s . c o  m*/
 * @param bundle
 * @return true if success
 */
public static boolean saveAttributes(final String filepath, Bundle bundle) {
    ExifInterface exif;
    try {
        exif = new ExifInterface(filepath);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    for (String tag : EXIF_TAGS) {
        if (bundle.containsKey(tag)) {
            exif.setAttribute(tag, bundle.getString(tag));
        }
    }
    try {
        exif.saveAttributes();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.nextgis.ngm_clink_monitoring.fragments.ObjectStatusFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    File tempPhotoFile = new File(mTempPhotoPath);

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
        GISApplication app = (GISApplication) getActivity().getApplication();
        ContentResolver contentResolver = app.getContentResolver();
        String photoFileName = getPhotoFileName();

        try {/*from   www  .j a v  a2s .c  o m*/
            BitmapUtil.writeLocationToExif(tempPhotoFile, app.getCurrentLocation(), 0);
        } catch (IOException e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        Uri allAttachesUri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName
                + "/" + mObjectId + "/attach");

        ContentValues values = new ContentValues();
        values.put(VectorLayer.ATTACH_DISPLAY_NAME, photoFileName);
        values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg");
        //values.put(VectorLayer.ATTACH_DESCRIPTION, photoFileName);

        Uri attachUri = null;
        try {
            attachUri = contentResolver.insert(allAttachesUri, values);

        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }

        if (null != attachUri) {

            try {
                int exifOrientation = BitmapUtil.getOrientationFromExif(tempPhotoFile);

                // resize and rotate
                Bitmap sourceBitmap = BitmapFactory.decodeFile(tempPhotoFile.getPath());
                Bitmap resizedBitmap = BitmapUtil.getResizedBitmap(sourceBitmap,
                        FoclConstants.PHOTO_MAX_SIZE_PX, FoclConstants.PHOTO_MAX_SIZE_PX);
                Bitmap rotatedBitmap = BitmapUtil.rotateBitmap(resizedBitmap, exifOrientation);

                // jpeg compress
                File tempAttachFile = File.createTempFile("attach", null, app.getCacheDir());
                OutputStream tempOutStream = new FileOutputStream(tempAttachFile);
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, FoclConstants.PHOTO_JPEG_COMPRESS_QUALITY,
                        tempOutStream);
                tempOutStream.close();

                int newHeight = rotatedBitmap.getHeight();
                int newWidth = rotatedBitmap.getWidth();

                rotatedBitmap.recycle();

                // write EXIF to new file
                BitmapUtil.copyExifData(tempPhotoFile, tempAttachFile);

                ExifInterface attachExif = new ExifInterface(tempAttachFile.getCanonicalPath());

                attachExif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + ExifInterface.ORIENTATION_NORMAL);
                attachExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, "" + newHeight);
                attachExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, "" + newWidth);

                attachExif.saveAttributes();

                // attach data from tempAttachFile
                OutputStream attachOutStream = contentResolver.openOutputStream(attachUri);
                FoclFileUtil.copy(new FileInputStream(tempAttachFile), attachOutStream);
                attachOutStream.close();

                tempAttachFile.delete();

            } catch (IOException e) {
                Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            }

            Log.d(TAG, attachUri.toString());

        } else {
            Log.d(TAG, "insert attach failed");
        }

        try {
            if (app.isOriginalPhotoSaving()) {
                File origPhotoFile = new File(getDailyPhotoFolder(), photoFileName);

                if (!com.nextgis.maplib.util.FileUtil.move(tempPhotoFile, origPhotoFile)) {
                    Toast.makeText(getActivity(), "Save original photo failed", Toast.LENGTH_LONG).show();
                }

            } else {
                tempPhotoFile.delete();
            }

            setPhotoGalleryAdapter();
            setPhotoGalleryVisibility(true);

        } catch (IOException e) {
            Toast.makeText(getActivity(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    }

    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_CANCELED) {
        tempPhotoFile.delete();
    }
}

From source file:org.egov.android.view.activity.CreateComplaintActivity.java

public String compressImage(String fromfilepath, String tofilepath) {

    Bitmap scaledBitmap = null;/*from   w w  w  . j  av a  2  s  . c o m*/

    BitmapFactory.Options options = new BitmapFactory.Options();

    //      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
    //      you try the use the bitmap here, you will get null.
    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(fromfilepath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;

    //      max Height and width values of the compressed image is taken as 816x612

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;

    //      width and height values are set maintaining the aspect ratio of the image

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxWidth / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;

        }
    }

    //      setting inSampleSize value allows to load a scaled down version of the original image

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

    //      inJustDecodeBounds set to false to load the actual bitmap
    options.inJustDecodeBounds = false;

    //      this options allow android to claim the bitmap memory if it runs low on memory
    options.inPurgeable = true;
    options.inInputShareable = true;
    options.inTempStorage = new byte[16 * 1024];

    try {
        //          load the bitmap from its path
        bmp = BitmapFactory.decodeFile(tofilepath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }
    try {
        scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }

    float ratioX = actualWidth / (float) options.outWidth;
    float ratioY = actualHeight / (float) options.outHeight;
    float middleX = actualWidth / 2.0f;
    float middleY = actualHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2,
            new Paint(Paint.FILTER_BITMAP_FLAG));

    String attrLatitute = null;
    String attrLatituteRef = null;
    String attrLONGITUDE = null;
    String attrLONGITUDEREf = null;

    //      check the rotation of the image and display it properly
    ExifInterface exif;
    try {
        exif = new ExifInterface(fromfilepath);

        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
        Log.d("EXIF", "Exif: " + orientation);
        Matrix matrix = new Matrix();
        if (orientation == 6) {
            matrix.postRotate(90);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 3) {
            matrix.postRotate(180);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 8) {
            matrix.postRotate(270);
            Log.d("EXIF", "Exif: " + orientation);
        }

        attrLatitute = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
        attrLatituteRef = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
        attrLONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
        attrLONGITUDEREf = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);

        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
                scaledBitmap.getHeight(), matrix, true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(tofilepath);

        //          write the compressed bitmap at the destination specified by filename.
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

        ExifInterface exif2 = new ExifInterface(tofilepath);

        if (attrLatitute != null) {
            exif2.setAttribute(ExifInterface.TAG_GPS_LATITUDE, attrLatitute);
            exif2.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, attrLONGITUDE);
        }

        if (attrLatituteRef != null) {
            exif2.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, attrLatituteRef);
            exif2.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, attrLONGITUDEREf);
        }
        exif2.saveAttributes();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return tofilepath;
}

From source file:com.nextgis.ngm_clink_monitoring.fragments.CreateObjectFragment.java

protected void writePhotoAttach(File tempPhotoFile) throws IOException {
    GISApplication app = (GISApplication) getActivity().getApplication();

    ContentResolver contentResolver = app.getContentResolver();
    String photoFileName = getPhotoFileName(tempPhotoFile);
    Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), photoFileName: " + photoFileName);

    Uri allAttachesUri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName
            + "/" + mObjectId + "/attach");
    Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), allAttachesUri: " + allAttachesUri);

    ContentValues values = new ContentValues();
    values.put(VectorLayer.ATTACH_DISPLAY_NAME, photoFileName);
    values.put(VectorLayer.ATTACH_MIME_TYPE, "image/jpeg");
    //values.put(VectorLayer.ATTACH_DESCRIPTION, photoFileName);

    Uri attachUri = null;//from  www  .  ja  v  a2s .  c  o m
    String insertAttachError = null;
    try {
        attachUri = contentResolver.insert(allAttachesUri, values);
        Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), insert: " + attachUri.toString());
    } catch (Exception e) {
        Log.d(TAG,
                "CreateObjectFragment, writePhotoAttach(), Insert attach failed: " + e.getLocalizedMessage());
        insertAttachError = "Insert attach failed: " + e.getLocalizedMessage();
    }

    if (null != attachUri) {
        int exifOrientation = BitmapUtil.getOrientationFromExif(tempPhotoFile);

        // resize and rotate
        Bitmap sourceBitmap = BitmapFactory.decodeFile(tempPhotoFile.getPath());
        Bitmap resizedBitmap = BitmapUtil.getResizedBitmap(sourceBitmap, FoclConstants.PHOTO_MAX_SIZE_PX,
                FoclConstants.PHOTO_MAX_SIZE_PX);
        Bitmap rotatedBitmap = BitmapUtil.rotateBitmap(resizedBitmap, exifOrientation);

        // jpeg compress
        File tempAttachFile = File.createTempFile("attach", null, app.getCacheDir());
        OutputStream tempOutStream = new FileOutputStream(tempAttachFile);
        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, FoclConstants.PHOTO_JPEG_COMPRESS_QUALITY,
                tempOutStream);
        tempOutStream.close();

        int newHeight = rotatedBitmap.getHeight();
        int newWidth = rotatedBitmap.getWidth();

        rotatedBitmap.recycle();

        // write EXIF to new file
        BitmapUtil.copyExifData(tempPhotoFile, tempAttachFile);
        BitmapUtil.writeLocationToExif(tempAttachFile, mAccurateLocation, app.getGpsTimeOffset());

        ExifInterface attachExif = new ExifInterface(tempAttachFile.getCanonicalPath());

        attachExif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + ExifInterface.ORIENTATION_NORMAL);
        attachExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, "" + newHeight);
        attachExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, "" + newWidth);

        attachExif.saveAttributes();

        // attach data from tempAttachFile
        OutputStream attachOutStream = contentResolver.openOutputStream(attachUri);
        if (attachOutStream != null) {
            FoclFileUtil.copy(new FileInputStream(tempAttachFile), attachOutStream);
            attachOutStream.close();
        } else {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), attachOutStream == null, attachUri"
                    + attachUri.toString());
        }

        if (!tempAttachFile.delete()) {
            Log.d(TAG,
                    "CreateObjectFragment, writePhotoAttach(), tempAttachFile.delete() failed, tempAttachFile:"
                            + tempAttachFile.getAbsolutePath());
        }
    }

    if (app.isOriginalPhotoSaving()) {
        BitmapUtil.writeLocationToExif(tempPhotoFile, mAccurateLocation, app.getGpsTimeOffset());
        File origPhotoFile = new File(getDailyPhotoFolder(), photoFileName);

        if (!com.nextgis.maplib.util.FileUtil.move(tempPhotoFile, origPhotoFile)) {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), move original failed, tempPhotoFile:"
                    + tempPhotoFile.getAbsolutePath() + ", origPhotoFile: " + origPhotoFile.getAbsolutePath());
            throw new IOException(
                    "Save original photo failed, tempPhotoFile: " + tempPhotoFile.getAbsolutePath());
        }

    } else {
        if (!tempPhotoFile.delete()) {
            Log.d(TAG, "CreateObjectFragment, writePhotoAttach(), tempPhotoFile.delete() failed, tempPhotoFile:"
                    + tempPhotoFile.getAbsolutePath());
        }
    }

    if (null != insertAttachError) {
        throw new IOException(insertAttachError);
    }
}

From source file:com.almalence.opencam.PluginManagerBase.java

public static int saveExifToInput(File file, int displayOrientation, boolean cameraMirrored, boolean saveGeo) {
    try {// w  w w. j  a  v a 2s .  co  m
        ExifInterface ei = new ExifInterface(file.getAbsolutePath());
        int exif_orientation = ExifInterface.ORIENTATION_NORMAL;
        switch (displayOrientation) {
        default:
        case 0:
            exif_orientation = ExifInterface.ORIENTATION_NORMAL;
            break;
        case 90:
            if (cameraMirrored) {
                displayOrientation = 270;
                exif_orientation = ExifInterface.ORIENTATION_ROTATE_270;
            } else {
                exif_orientation = ExifInterface.ORIENTATION_ROTATE_90;
            }
            break;
        case 180:
            exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
            break;
        case 270:
            if (cameraMirrored) {
                displayOrientation = 90;
                exif_orientation = ExifInterface.ORIENTATION_ROTATE_90;
            } else {
                exif_orientation = ExifInterface.ORIENTATION_ROTATE_270;
            }
            break;
        }
        ei.setAttribute(ExifInterface.TAG_ORIENTATION, "" + exif_orientation);

        if (saveGeo) {
            Location l = MLocation.getLocation(ApplicationScreen.getMainContext());

            if (l != null) {
                ei.setAttribute(ExifInterface.TAG_GPS_LATITUDE, GPSTagsConverter.convert(l.getLatitude()));
                ei.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF,
                        GPSTagsConverter.latitudeRef(l.getLatitude()));
                ei.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, GPSTagsConverter.convert(l.getLongitude()));
                ei.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF,
                        GPSTagsConverter.longitudeRef(l.getLongitude()));

            }
        }

        ei.saveAttributes();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return displayOrientation;
}

From source file:com.almalence.opencam.SavingService.java

protected File saveExifTags(File file, long sessionID, int i, int x, int y, int exif_orientation,
        boolean useGeoTaggingPrefExport, boolean enableExifTagOrientation) {
    addTimestamp(file, exif_orientation);

    // Set tag_model using ExifInterface.
    // If we try set tag_model using ExifDriver, then standard
    // gallery of android (Nexus 4) will crash on this file.
    // Can't figure out why, other Exif tools work fine.
    try {/*  ww  w .ja va  2  s.  c  om*/
        ExifInterface ei = new ExifInterface(file.getAbsolutePath());
        String tag_model = getFromSharedMem("exiftag_model" + Long.toString(sessionID));
        String tag_make = getFromSharedMem("exiftag_make" + Long.toString(sessionID));
        if (tag_model == null)
            tag_model = Build.MODEL;
        ei.setAttribute(ExifInterface.TAG_MODEL, tag_model);
        if (tag_make == null)
            tag_make = Build.MANUFACTURER;
        ei.setAttribute(ExifInterface.TAG_MAKE, tag_make);
        ei.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(exif_orientation));
        ei.saveAttributes();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Open ExifDriver.
    ExifDriver exifDriver = ExifDriver.getInstance(file.getAbsolutePath());
    ExifManager exifManager = null;
    if (exifDriver != null) {
        exifManager = new ExifManager(exifDriver, getApplicationContext());
    }

    if (useGeoTaggingPrefExport) {
        Location l = MLocation.getLocation(getApplicationContext());

        if (l != null) {
            double lat = l.getLatitude();
            double lon = l.getLongitude();
            boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);

            if (hasLatLon) {
                exifManager.setGPSLocation(l.getLatitude(), l.getLongitude(), l.getAltitude());
            }

            String GPSDateString = new SimpleDateFormat("yyyy:MM:dd").format(new Date(l.getTime()));
            if (GPSDateString != null) {
                ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
                value.setBytes(GPSDateString.getBytes());
                exifDriver.getIfdGps().put(ExifDriver.TAG_GPS_DATE_STAMP, value);
            }
        }
    }

    String tag_exposure_time = getFromSharedMem("exiftag_exposure_time" + Long.toString(sessionID));
    String tag_aperture = getFromSharedMem("exiftag_aperture" + Long.toString(sessionID));
    String tag_flash = getFromSharedMem("exiftag_flash" + Long.toString(sessionID));
    String tag_focal_length = getFromSharedMem("exiftag_focal_lenght" + Long.toString(sessionID));
    String tag_iso = getFromSharedMem("exiftag_iso" + Long.toString(sessionID));
    String tag_white_balance = getFromSharedMem("exiftag_white_balance" + Long.toString(sessionID));
    String tag_spectral_sensitivity = getFromSharedMem(
            "exiftag_spectral_sensitivity" + Long.toString(sessionID));
    String tag_version = getFromSharedMem("exiftag_version" + Long.toString(sessionID));
    String tag_scene = getFromSharedMem("exiftag_scene_capture_type" + Long.toString(sessionID));
    String tag_metering_mode = getFromSharedMem("exiftag_metering_mode" + Long.toString(sessionID));

    if (exifDriver != null) {
        if (tag_exposure_time != null) {
            int[][] ratValue = ExifManager.stringToRational(tag_exposure_time);
            if (ratValue != null) {
                ValueRationals value = new ValueRationals(ExifDriver.FORMAT_UNSIGNED_RATIONAL);
                value.setRationals(ratValue);
                exifDriver.getIfdExif().put(ExifDriver.TAG_EXPOSURE_TIME, value);
            }
        } else { // hack for expo bracketing
            tag_exposure_time = getFromSharedMem(
                    "exiftag_exposure_time" + Integer.toString(i) + Long.toString(sessionID));
            if (tag_exposure_time != null) {
                int[][] ratValue = ExifManager.stringToRational(tag_exposure_time);
                if (ratValue != null) {
                    ValueRationals value = new ValueRationals(ExifDriver.FORMAT_UNSIGNED_RATIONAL);
                    value.setRationals(ratValue);
                    exifDriver.getIfdExif().put(ExifDriver.TAG_EXPOSURE_TIME, value);
                }
            }
        }
        if (tag_aperture != null) {
            int[][] ratValue = ExifManager.stringToRational(tag_aperture);
            if (ratValue != null) {
                ValueRationals value = new ValueRationals(ExifDriver.FORMAT_UNSIGNED_RATIONAL);
                value.setRationals(ratValue);
                exifDriver.getIfdExif().put(ExifDriver.TAG_APERTURE_VALUE, value);
            }
        }
        if (tag_flash != null) {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, Integer.parseInt(tag_flash));
            exifDriver.getIfdExif().put(ExifDriver.TAG_FLASH, value);
        }
        if (tag_focal_length != null) {
            int[][] ratValue = ExifManager.stringToRational(tag_focal_length);
            if (ratValue != null) {
                ValueRationals value = new ValueRationals(ExifDriver.FORMAT_UNSIGNED_RATIONAL);
                value.setRationals(ratValue);
                exifDriver.getIfdExif().put(ExifDriver.TAG_FOCAL_LENGTH, value);
            }
        }
        try {
            if (tag_iso != null) {
                if (tag_iso.indexOf("ISO") > 0) {
                    tag_iso = tag_iso.substring(0, 2);
                }
                ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT,
                        Integer.parseInt(tag_iso));
                exifDriver.getIfdExif().put(ExifDriver.TAG_ISO_SPEED_RATINGS, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (tag_scene != null) {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, Integer.parseInt(tag_scene));
            exifDriver.getIfdExif().put(ExifDriver.TAG_SCENE_CAPTURE_TYPE, value);
        } else {
            int sceneMode = CameraController.getSceneMode();

            int sceneModeVal = 0;
            if (sceneMode == CameraParameters.SCENE_MODE_LANDSCAPE) {
                sceneModeVal = 1;
            } else if (sceneMode == CameraParameters.SCENE_MODE_PORTRAIT) {
                sceneModeVal = 2;
            } else if (sceneMode == CameraParameters.SCENE_MODE_NIGHT) {
                sceneModeVal = 3;
            }

            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, sceneModeVal);
            exifDriver.getIfdExif().put(ExifDriver.TAG_SCENE_CAPTURE_TYPE, value);
        }
        if (tag_white_balance != null) {
            exifDriver.getIfd0().remove(ExifDriver.TAG_LIGHT_SOURCE);

            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT,
                    Integer.parseInt(tag_white_balance));
            exifDriver.getIfdExif().put(ExifDriver.TAG_WHITE_BALANCE, value);
            exifDriver.getIfdExif().put(ExifDriver.TAG_LIGHT_SOURCE, value);
        } else {
            exifDriver.getIfd0().remove(ExifDriver.TAG_LIGHT_SOURCE);

            int whiteBalance = CameraController.getWBMode();
            int whiteBalanceVal = 0;
            int lightSourceVal = 0;
            if (whiteBalance == CameraParameters.WB_MODE_AUTO) {
                whiteBalanceVal = 0;
                lightSourceVal = 0;
            } else {
                whiteBalanceVal = 1;
                lightSourceVal = 0;
            }

            if (whiteBalance == CameraParameters.WB_MODE_DAYLIGHT) {
                lightSourceVal = 1;
            } else if (whiteBalance == CameraParameters.WB_MODE_FLUORESCENT) {
                lightSourceVal = 2;
            } else if (whiteBalance == CameraParameters.WB_MODE_WARM_FLUORESCENT) {
                lightSourceVal = 2;
            } else if (whiteBalance == CameraParameters.WB_MODE_INCANDESCENT) {
                lightSourceVal = 3;
            } else if (whiteBalance == CameraParameters.WB_MODE_TWILIGHT) {
                lightSourceVal = 3;
            } else if (whiteBalance == CameraParameters.WB_MODE_CLOUDY_DAYLIGHT) {
                lightSourceVal = 10;
            } else if (whiteBalance == CameraParameters.WB_MODE_SHADE) {
                lightSourceVal = 11;
            }

            ValueNumber valueWB = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, whiteBalanceVal);
            exifDriver.getIfdExif().put(ExifDriver.TAG_WHITE_BALANCE, valueWB);

            ValueNumber valueLS = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, lightSourceVal);
            exifDriver.getIfdExif().put(ExifDriver.TAG_LIGHT_SOURCE, valueLS);
        }
        if (tag_spectral_sensitivity != null) {
            ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
            value.setBytes(tag_spectral_sensitivity.getBytes());
            exifDriver.getIfd0().put(ExifDriver.TAG_SPECTRAL_SENSITIVITY, value);
        }
        if (tag_version != null && !tag_version.equals("48 50 50 48")) {
            ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
            value.setBytes(tag_version.getBytes());
            exifDriver.getIfd0().put(ExifDriver.TAG_EXIF_VERSION, value);
        } else {
            ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
            byte[] version = { (byte) 48, (byte) 50, (byte) 50, (byte) 48 };
            value.setBytes(version);
            exifDriver.getIfd0().put(ExifDriver.TAG_EXIF_VERSION, value);
        }
        if (tag_metering_mode != null && !tag_metering_mode.equals("")
                && Integer.parseInt(tag_metering_mode) <= 255) {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT,
                    Integer.parseInt(tag_metering_mode));
            exifDriver.getIfdExif().put(ExifDriver.TAG_METERING_MODE, value);
            exifDriver.getIfd0().put(ExifDriver.TAG_METERING_MODE, value);
        } else {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, 0);
            exifDriver.getIfdExif().put(ExifDriver.TAG_METERING_MODE, value);
            exifDriver.getIfd0().put(ExifDriver.TAG_METERING_MODE, value);
        }

        ValueNumber xValue = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_LONG, x);
        exifDriver.getIfdExif().put(ExifDriver.TAG_IMAGE_WIDTH, xValue);

        ValueNumber yValue = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_LONG, y);
        exifDriver.getIfdExif().put(ExifDriver.TAG_IMAGE_HEIGHT, yValue);

        String dateString = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").format(new Date());
        if (dateString != null) {
            ValueByteArray value = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
            // Date string length is 19 bytes. But exif tag
            // specification length is 20 bytes.
            // That's why we add "empty" byte (0x00) in the end.
            byte[] bytes = dateString.getBytes();
            byte[] res = new byte[20];
            for (int ii = 0; ii < bytes.length; ii++) {
                res[ii] = bytes[ii];
            }
            res[19] = 0x00;
            value.setBytes(res);
            exifDriver.getIfd0().put(ExifDriver.TAG_DATETIME, value);
            exifDriver.getIfdExif().put(ExifDriver.TAG_DATETIME_DIGITIZED, value);
            exifDriver.getIfdExif().put(ExifDriver.TAG_DATETIME_ORIGINAL, value);
        }

        // extract mode name
        String tag_modename = getFromSharedMem("mode_name" + Long.toString(sessionID));
        if (tag_modename == null)
            tag_modename = "";
        String softwareString = getResources().getString(R.string.app_name) + ", " + tag_modename;
        ValueByteArray softwareValue = new ValueByteArray(ExifDriver.FORMAT_ASCII_STRINGS);
        softwareValue.setBytes(softwareString.getBytes());
        exifDriver.getIfd0().put(ExifDriver.TAG_SOFTWARE, softwareValue);

        if (enableExifTagOrientation) {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT, exif_orientation);
            exifDriver.getIfd0().put(ExifDriver.TAG_ORIENTATION, value);
        } else {
            ValueNumber value = new ValueNumber(ExifDriver.FORMAT_UNSIGNED_SHORT,
                    ExifInterface.ORIENTATION_NORMAL);
            exifDriver.getIfd0().put(ExifDriver.TAG_ORIENTATION, value);
        }

        // Save exif info to new file, and replace old file with new
        // one.
        File modifiedFile = new File(file.getAbsolutePath() + ".tmp");
        exifDriver.save(modifiedFile.getAbsolutePath());
        return modifiedFile;
    }
    return null;
}

From source file:Main.java

public static void fixBitmapRotationExif(String filePath, Activity activityForScreenOrientation) {
    try {//from  w w w . j a v  a  2s.c  o  m
        ExifInterface exif = new ExifInterface(filePath);

        int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        if (exifOrientation == ExifInterface.ORIENTATION_UNDEFINED
                && Build.MANUFACTURER.toLowerCase(Locale.ENGLISH).contains("htc"))
            return;

        boolean flippedHorizontally = false, flippedVertically = false;

        int angle = 0;

        if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
            angle += 90;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
            angle += 180;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
            angle += 270;
        } else if (exifOrientation == ExifInterface.ORIENTATION_FLIP_HORIZONTAL) {
            flippedHorizontally = true;
        } else if (exifOrientation == ExifInterface.ORIENTATION_FLIP_VERTICAL) {
            flippedVertically = true;
        } else if (exifOrientation == ExifInterface.ORIENTATION_TRANSPOSE) {
            angle += 90;
            flippedVertically = true;
        } else if (exifOrientation == ExifInterface.ORIENTATION_TRANSVERSE) {
            angle -= 90;
            flippedVertically = true;
        }

        int orientation;

        if (activityForScreenOrientation != null) {
            orientation = getScreenOrientation(activityForScreenOrientation);
            if (orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                angle += 90;
            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
                angle += 180;
            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
                angle += 270;
            }
        }

        orientation = 0;
        angle = angle % 360;

        if (angle == -90 && flippedVertically && !flippedHorizontally) {
            orientation = ExifInterface.ORIENTATION_TRANSVERSE;
        } else if (angle == -270 && flippedVertically && !flippedHorizontally) {
            orientation = ExifInterface.ORIENTATION_TRANSPOSE;
        } else if (angle == -90 && !flippedVertically && flippedHorizontally) {
            orientation = ExifInterface.ORIENTATION_TRANSPOSE;
        } else if (angle == -270 && !flippedVertically && flippedHorizontally) {
            orientation = ExifInterface.ORIENTATION_TRANSVERSE;
        } else {
            while (angle < 0) {
                angle += 360;
            }
            switch (angle) {
            case 0:
                if (flippedHorizontally) {
                    orientation = ExifInterface.ORIENTATION_FLIP_HORIZONTAL;
                } else if (flippedVertically) {
                    orientation = ExifInterface.ORIENTATION_FLIP_VERTICAL;
                }
                break;
            case 90:
                orientation = ExifInterface.ORIENTATION_ROTATE_90;
                break;
            case 180:
                orientation = ExifInterface.ORIENTATION_ROTATE_180;
                break;
            case 270:
                orientation = ExifInterface.ORIENTATION_ROTATE_270;
                break;
            }
        }

        if (orientation != exifOrientation) {
            exif.setAttribute(ExifInterface.TAG_ORIENTATION, ((Integer) orientation).toString());
            exif.saveAttributes();
        }
    } catch (IOException e) {
        Log.w("TAG", "-- Error in setting image");
    }
}

From source file:foam.starwisp.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {

    String type = "";
    Integer tid = 0;//from w ww.j  a  v  a  2 s  .c om
    String token = "";

    try {

        type = arr.getString(0);
        tid = arr.getInt(1);
        token = arr.getString(2);

    } catch (JSONException e) {
        Log.e("starwisp",
                "Error parsing update arguments for " + ctxname + " " + arr.toString() + e.toString());
    }

    final Integer id = tid;

    //Log.i("starwisp", "Update: "+type+" "+id+" "+token);

    try {

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            LinearLayout linearLayout = (LinearLayout) msg.getView();
            View child = linearLayout.getChildAt(0);
            TextView messageTextView = (TextView) child;
            messageTextView.setTextSize(arr.getInt(4));
            msg.show();
            return;
        }

        if (token.equals("play-sound")) {
            String name = arr.getString(3);

            if (name.equals("ping")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.ping);
                mp.start();
            }
            if (name.equals("active")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.active);
                mp.start();
            }
        }

        if (token.equals("soundfile-start-recording")) {
            String filename = arr.getString(3);
            m_SoundManager.StartRecording(filename);
        }
        if (token.equals("soundfile-stop-recording")) {
            m_SoundManager.StopRecording();
        }
        if (token.equals("soundfile-start-playback")) {
            String filename = arr.getString(3);
            m_SoundManager.StartPlaying(filename);
        }
        if (token.equals("soundfile-stop-playback")) {
            m_SoundManager.StopPlaying();
        }

        if (token.equals("vibrate")) {
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(arr.getInt(3));
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(  R.animator.fragment_slide_left_enter,
            //             R.animator.fragment_slide_right_exit);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("view")) {
            //ctx.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse()));

            File f = new File(arr.getString(3));
            Uri fileUri = Uri.fromFile(f);

            Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(arr.getString(3));
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            myIntent.setDataAndType(fileUri, mimetype);
            ctx.startActivity(myIntent);
            return;
        }

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("gps-start")) {
            final String name = arr.getString(3);

            if (m_LocationManager == null) {
                m_LocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
                m_GPS = new DorisLocationListener(m_LocationManager);
            }

            m_GPS.Start((StarwispActivity) ctx, name, this, arr.getInt(5), arr.getInt(6));
            return;
        }

        if (token.equals("sensors-get")) {
            final String name = arr.getString(3);
            if (m_SensorHandler == null) {
                m_SensorHandler = new SensorHandler((StarwispActivity) ctx, this);
            }
            m_SensorHandler.GetSensors((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("sensors-start")) {
            final String name = arr.getString(3);
            final JSONArray requested_json = arr.getJSONArray(5);
            ArrayList<Integer> requested = new ArrayList<Integer>();

            try {
                for (int i = 0; i < requested_json.length(); i++) {
                    requested.add(requested_json.getInt(i));
                }
            } catch (JSONException e) {
                Log.e("starwisp", "Error parsing data in sensors start " + e.toString());
            }

            // start it up...
            if (m_SensorHandler == null) {
                m_SensorHandler = new SensorHandler((StarwispActivity) ctx, this);
            }
            m_SensorHandler.StartSensors((StarwispActivity) ctx, name, this, requested);
            return;
        }

        if (token.equals("sensors-stop")) {
            if (m_SensorHandler != null) {
                m_SensorHandler.StopSensors();
            }
            return;
        }

        if (token.equals("walk-draggable")) {
            final String name = arr.getString(3);
            int iid = arr.getInt(5);
            DialogCallback(ctx, ctxname, name, WalkDraggable(ctx, name, ctxname, iid).replace("\\", ""));
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            final String name = arr.getString(3);
            final String ssid = arr.getString(5);
            m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("http-request")) {
            Log.i("starwisp", "http-request called");
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", "", name);
            }
            return;
        }

        if (token.equals("http-post")) {
            Log.i("starwisp", "http-post called");
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                final String data = arr.getString(6);
                m_NetworkManager.StartRequestThread(url, "post", data, name);
            }
            return;
        }

        if (token.equals("http-upload")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http ul request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "upload", "", filename);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", "", filename);
            }
            return;
        }

        if (token.equals("take-photo")) {
            photo(ctx, arr.getString(3), arr.getInt(4));
        }

        if (token.equals("bluetooth")) {
            final String name = arr.getString(3);
            m_Bluetooth.Start((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("bluetooth-send")) {
            m_Bluetooth.Write(arr.getString(3));
        }

        if (token.equals("process-image-in-place")) {
            BitmapCache.ProcessInPlace(arr.getString(3));
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {
            final String name = arr.getString(3);
            final String msg = arr.getString(5);
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };
            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();
            return;
        }

        if (token.equals("ok-dialog")) {
            final String name = arr.getString(3);
            final String msg = arr.getString(5);
            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };
            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Ok", dialogClickListener).show();
            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

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

        if (id == 0) {
            Log.i("starwisp", "Zero ID, aborting...");
            return;
        }

        // now try and find the widget
        final View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // only tested on spinners
        if (token.equals("disabled")) {
            vv.setAlpha(0.3f);
            //vv.getSelectedView().setEnabled(false);
            vv.setEnabled(false);
            return;
        }

        if (token.equals("enabled")) {
            vv.setAlpha(1.0f);
            //vv.getSelectedView().setEnabled(true);
            vv.setEnabled(true);
            return;
        }

        if (token.equals("animate")) {
            JSONArray trans = arr.getJSONArray(3);

            final TranslateAnimation animation = new TranslateAnimation(getPixelsFromDp(ctx, trans.getInt(0)),
                    getPixelsFromDp(ctx, trans.getInt(1)), getPixelsFromDp(ctx, trans.getInt(2)),
                    getPixelsFromDp(ctx, trans.getInt(3)));
            animation.setDuration(1000);
            animation.setFillAfter(false);
            animation.setInterpolator(new AnticipateOvershootInterpolator(1.0f));
            animation.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationEnd(Animation animation) {
                    vv.clearAnimation();
                    Log.i("starwisp", "animation end");
                    ((ViewManager) vv.getParent()).removeView(vv);

                    //LayoutParams lp = new LayoutParams(imageView.getWidth(), imageView.getHeight());
                    //lp.setMargins(50, 100, 0, 0);
                    //imageView.setLayoutParams(lp);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationStart(Animation animation) {
                    Log.i("starwisp", "animation start");
                }

            });

            vv.startAnimation(animation);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            Log.i("starwisp", "set-enabled called...");
            vv.setEnabled(arr.getInt(3) == 1);
            vv.setClickable(arr.getInt(3) == 1);
            if (vv.getBackground() != null) {
                if (arr.getInt(3) == 0) {
                    //vv.setBackgroundColor(0x00000000);
                    vv.getBackground().setColorFilter(0x20000000, PorterDuff.Mode.MULTIPLY);
                } else {
                    vv.getBackground().setColorFilter(null);
                }
            }
            return;
        }

        if (token.equals("background-colour")) {
            JSONArray col = arr.getJSONArray(3);

            if (type.equals("linear-layout")) {
                vv.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            } else {
                //vv.setBackgroundColor();
                vv.getBackground().setColorFilter(
                        Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)),
                        PorterDuff.Mode.MULTIPLY);
            }
            vv.invalidate();
            return;
        }

        // special cases

        if (type.equals("linear-layout")) {
            //Log.i("starwisp","linear-layout update id: "+id);
            StarwispLinearLayout.Update(this, (LinearLayout) vv, token, ctx, ctxname, arr);
            return;
        }

        if (type.equals("relative-layout")) {
            StarwispRelativeLayout.Update(this, (RelativeLayout) vv, token, ctx, ctxname, arr);
            return;
        }

        if (type.equals("draggable")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }

            if (token.equals("contents-add")) {
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = (LinearLayout) vv;

            if (token.equals("grid-buttons")) {
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final int count = buttons.length();
                int vertcount = 0;
                LinearLayout vert = null;

                for (int i = 0; i < count; i++) {
                    JSONArray button = buttons.getJSONArray(i);

                    if (vertcount == 0) {
                        vert = new LinearLayout(ctx);
                        vert.setId(0);
                        vert.setOrientation(LinearLayout.VERTICAL);
                        horiz.addView(vert);
                    }
                    vertcount = (vertcount + 1) % height;

                    if (buttontype.equals("button")) {
                        Button b = new Button(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("toggle")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                String arg = "#f";
                                if (((ToggleButton) v).isChecked())
                                    arg = "#t";
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("single")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing on click data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                final JSONArray items = arr.getJSONArray(3);
                v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {
                    @Override
                    public int getCount() {
                        return items.length();
                    }

                    @Override
                    public Fragment getItem(int position) {
                        try {
                            String fragname = items.getString(position);
                            return ActivityManager.GetFragment(fragname);
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing pages data " + e.toString());
                        }
                        return null;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                v.setImageBitmap(BitmapCache.Load(arr.getString(3)));
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(Html.fromHtml(arr.getString(3)), BufferType.SPANNABLE);
                //                    v.invalidate();
            }
            if (token.equals("file")) {
                v.setText(LoadData(arr.getString(3)));
            }

            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            if (token.equals("request-focus")) {
                v.requestFocus();
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = (StarwispCanvas) vv;
            if (token.equals("drawlist")) {
                v.SetDrawList(arr.getJSONArray(3));
            }
            return;
        }

        if (type.equals("camera-preview")) {
            final CameraPreview v = (CameraPreview) vv;

            if (token.equals("take-picture")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] input, Camera camera) {
                        Bitmap original = BitmapFactory.decodeByteArray(input, 0, input.length);
                        Bitmap resized = Bitmap.createScaledBitmap(original, PHOTO_WIDTH, PHOTO_HEIGHT, true);
                        ByteArrayOutputStream blob = new ByteArrayOutputStream();
                        resized.compress(Bitmap.CompressFormat.JPEG, 100, blob);

                        String datetime = getDateTime();
                        String filename = path + datetime + ".jpg";
                        SaveData(filename, blob.toByteArray());
                        v.Shutdown();
                        ctx.finish();
                    }
                });
            }

            // don't shut the activity down and use provided path
            if (token.equals("take-picture-cont")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                Log.i("starwisp", "take-picture-cont fired");

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] input, Camera camera) {
                        Log.i("starwisp", "on picture taken...");

                        // the version used by the uav app

                        Bitmap original = BitmapFactory.decodeByteArray(input, 0, input.length);
                        //Bitmap resized = Bitmap.createScaledBitmap(original, PHOTO_WIDTH, PHOTO_HEIGHT, true);
                        ByteArrayOutputStream blob = new ByteArrayOutputStream();
                        original.compress(Bitmap.CompressFormat.JPEG, 95, blob);
                        original.recycle();
                        String filename = path;
                        Log.i("starwisp", path);
                        SaveData(filename, blob.toByteArray());

                        // burn gps into exif data
                        if (m_GPS.currentLocation != null) {
                            double latitude = m_GPS.currentLocation.getLatitude();
                            double longitude = m_GPS.currentLocation.getLongitude();

                            try {
                                ExifInterface exif = new ExifInterface(filename);
                                exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, GPS.convert(latitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF,
                                        GPS.latitudeRef(latitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, GPS.convert(longitude));
                                exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF,
                                        GPS.longitudeRef(longitude));
                                exif.saveAttributes();
                            } catch (IOException e) {
                                Log.i("starwisp",
                                        "Couldn't open " + filename + " to add exif data: ioexception caught.");
                            }

                        }

                        v.TakenPicture();
                    }
                });
            }

            if (token.equals("shutdown")) {
                v.Shutdown();
            }

            return;
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = arr.getJSONArray(3);
                ArrayList<String> spinnerArray = new ArrayList<String>();

                for (int i = 0; i < items.length(); i++) {
                    spinnerArray.add(items.getString(i));
                }

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                        spinnerArray) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View v = super.getView(position, convertView, parent);
                        ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                        return v;
                    }
                };

                spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);
                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                        CallbackArgs(ctx, ctxname, wid, "" + pos);
                    }

                    public void onNothingSelected(AdapterView<?> v) {
                    }
                });

            }
            return;
        }

        if (type.equals("draw-map")) {
            DrawableMap v = m_DMaps.get(id);
            if (v != null) {
                if (token.equals("polygons")) {
                    v.UpdateFromJSON(arr.getJSONArray(3));
                }
                if (token.equals("centre")) {
                    JSONArray tokens = arr.getJSONArray(3);
                    v.Centre(tokens.getDouble(0), tokens.getDouble(1), tokens.getInt(2));
                }
                if (token.equals("layout")) {
                    v.m_parent.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
                }
            } else {
                Log.e("starwisp", "Asked to update a drawmap which doesn't exist");
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing builder data " + e.toString());
        Log.e("starwisp", "type:" + type + " id:" + id + " token:" + token);
    }
}