使用相机android捕获图像后失败的Binder事务

时间:2013-12-12 08:57:43

标签: java android android-camera

我正在构建使用相机作为主要功能的Android应用程序。我正在使用意图打开原生相机,但在我捕获并按下保存按钮后,应用程序返回主要活动。我想在下一个活动中显示捕获的图像,因为我想裁剪捕获的图像。 这是我的代码

package com.example.cobaandroid;
public class MainActivity extends Activity implements OnClickListener {

final int PICTURE_GALLERY = 0;
final int CAMERA_CAPTURE = 1;
final int PIC_CROP = 2;
public static final int MEDIA_IMAGE = 3;
private Uri picUri;
Uri imgFileUri ;
File cameraFile;
String imageFilepath = "";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tampilkanUserManual();
    //getApplicationContext().deleteDatabase("score.db");
    Button ambilGambar = (Button)findViewById(R.id.ambil_gambar);
    Button gallery = (Button) findViewById(R.id.ambilGallery);
    ambilGambar.setOnClickListener(this);
    gallery.setOnClickListener(this);
    if(!supportCamera())
    {
        Toast.makeText(getApplicationContext(), "Maaf device anda tidak mendukung penggunaan kamera", Toast.LENGTH_LONG).show();
        finish();
    }
    Button exit = (Button)findViewById(R.id.exit);
    exit.setOnClickListener(this);
}

// Button onClick 
public void onClick(View v)
{
    if(v.getId()==R.id.ambil_gambar)
    {
        try
        {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String fileName = "IMG_" + dateFormat.format(new Date()) + ".jpg";
            File myDirectory = new File(Environment.getExternalStorageDirectory()+ "/DCIM/Camera");
            cameraFile = new File(myDirectory,fileName);
            picUri = Uri.fromFile(cameraFile);
            Intent intentAmbil = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentAmbil.putExtra(MediaStore.EXTRA_OUTPUT, picUri);

            startActivityForResult(intentAmbil,CAMERA_CAPTURE);
        }
        catch(ActivityNotFoundException activity)
        {
            String errorMessage = "ga support kamera";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    else if(v.getId()==R.id.ambilGallery)
    {
        try
        {
            //intent pick from gallery
            Intent ambilGallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            ambilGallery.setType("image/*");
            startActivityForResult(ambilGallery, PICTURE_GALLERY);
        }
        catch(ActivityNotFoundException activity)
        {
            String errorMessage = "Tidak dapat mengambil gambar dari galeri";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    else if(v.getId()==R.id.exit)
    {
        try
        {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        }
        catch(ActivityNotFoundException ac)
        {
            Toast.makeText(getApplicationContext(), "Tidak dapat menutup aplikasi", Toast.LENGTH_LONG).show();
        }
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if(resultCode==RESULT_OK)
    {
        if(requestCode==CAMERA_CAPTURE)
        {   
            BitmapFactory.Options option = new BitmapFactory.Options();
            option.inJustDecodeBounds = false;
            Bitmap hasilPoto = BitmapFactory.decodeFile(cameraFile.toString(),option);
            Intent cropIntent= new Intent (this, Crop.class);
            cropIntent.putExtra("data", picUri.toString());
            cropIntent.putExtra("gambar", hasilPoto);
            cropIntent.putExtra("kode","kamera");
            startActivity(cropIntent);
        }
        else if(requestCode==PICTURE_GALLERY)
        {
            // Resize picture
            Uri galeriUri = data.getData();
            Bitmap hasilPoto = null;
            try {
                hasilPoto = decodeUri(galeriUri);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Intent cropIntents = new Intent(this,Crop.class);
            cropIntents.putExtra("data", galeriUri.toString());
            cropIntents.putExtra("kode","galeri");
            cropIntents.putExtra("gambar",hasilPoto);
            startActivity(cropIntents);
        }
    }
}


private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(
            getContentResolver().openInputStream(selectedImage), null, o);
    final int REQUIRED_SIZE = 100;
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
            break;
        }
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    return BitmapFactory.decodeStream(
            getContentResolver().openInputStream(selectedImage), null, o2);
}

}

这里是Crop.java

package com.example.cobaandroid;
public class Crop extends Activity  {
final int PIC_CROP = 2;
final int levelBWd = 6;
public static final int MEDIA_IMAGE = 3;
private static final String IMAGE_DIRECTORY_NAME = "Dataset";
private Uri fileUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crop);
    ImageView img = (ImageView) findViewById(R.id.gambarPoto);
    String uriPassed = getIntent().getStringExtra("data");
    fileUri = Uri.parse(uriPassed);
    String intentKode = getIntent().getStringExtra("kode");
    if(intentKode.equals("kamera"))
    {
        Bitmap bmp = getIntent().getParcelableExtra("gambar");
        img.setImageBitmap(bmp);
        System.out.println("Image captured using camera");
    }
    else if(intentKode.equals("galeri"))
    {
        Bitmap bmp = getIntent().getParcelableExtra("gambar");
        img.setImageBitmap(bmp);
        System.out.println("pick from gallery");
    }
    Button cropButton = (Button) findViewById(R.id.cropButton);
    cropButton.setOnClickListener(new View.OnClickListener() {
    int hasCroped = 0;
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
            int jumlahFile = cekDirektoriDataSet(dir);
            if(jumlahFile==0)
            {
                Toast.makeText(getApplicationContext(), "Anda belum melakukan Crop", Toast.LENGTH_LONG).show();
            }
            if(jumlahFile < levelBWd)
            {
                try
                {
                    hasCroped = jumlahFile;
                    if(jumlahFile !=0)Toast.makeText(getApplicationContext(), "Anda sudah melakukan Crop sebanyak "+hasCroped, Toast.LENGTH_LONG).show();
                    hasCroped++;
                    Intent intentCrop = new Intent("com.android.camera.action.CROP");
                    intentCrop.setDataAndType(fileUri, "image/*");
                    Uri tempUri = fileUri;
                    tempUri = getOutputMediaFileUri(MEDIA_IMAGE);
                    intentCrop.putExtra("scale","true");
                    intentCrop.putExtra("AspectX", 1);
                    intentCrop.putExtra("AspectY", 1);
                    intentCrop.putExtra("outputX", 150);
                    intentCrop.putExtra("outputY", 150);
                    intentCrop.putExtra("return-data",false);       
                    intentCrop.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                    startActivityForResult(intentCrop, PIC_CROP);
                }
                catch(ActivityNotFoundException activity)
                {
                    activity.setStackTrace(null);
                }
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Tidak dapat melakukan crop melebihi jumlah level warna BWD", Toast.LENGTH_LONG).show();
            }
        }       
    });

    // DataSet ListView dan Hitung RGB
    Button view = (Button)findViewById(R.id.list);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {   
            File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
            int jumlahFile = cekDirektoriDataSet(dir);
            if(jumlahFile > 0)
            {
                Intent listIntent = new Intent(Crop.this,DataSet.class);
                listIntent.putExtra("uri", fileUri.toString());
                Crop.this.startActivity(listIntent);
                finish();
            }
            else
            {
                Toast toast = Toast.makeText(getApplicationContext(),"Tidak ada citra di direktroi Dataset", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    });

}
@Override
public void onBackPressed()
{
    HapusIsiDir hapusDir = new HapusIsiDir();
    hapusDir.hapusDirektori(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Dataset"));
    hapusDir.hapusDirektori(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Datatest"));
    finish();
}
// store gambar (file URI)
public Uri getOutputMediaFileUri (int type)
{
    return Uri.fromFile(getOutputMediaFile(type));
}

private File getOutputMediaFile (int type)
{
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
    //buat media file name
    int indexGambar = cekDirektoriDataSet(mediaStorageDir);
    File mediaFile;
    if (type == MEDIA_IMAGE)
    {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + (indexGambar+1)+".jpg");                  
    }
    else return null;
    return mediaFile;   
}

//cek jumlah atau isi direktori
private int cekDirektoriDataSet(File dir)
{
    if(!dir.exists())
    {
        if(!dir.mkdir())
        {
            Log.d(IMAGE_DIRECTORY_NAME, "Gagal membuat direktori" + IMAGE_DIRECTORY_NAME + "direktori");
        }
    }
    File[] listDir = dir.listFiles();
    return listDir.length;
}

}

我需要你的帮助,非常感谢你的关注......

这是logcat

12 15:36:10.994: E/AndroidRuntime(30866): FATAL EXCEPTION: main
12-12 15:36:10.994: E/AndroidRuntime(30866): Process: com.example.cobaandroid, PID: 30866
12-12 15:36:10.994: E/AndroidRuntime(30866): java.lang.RuntimeException: Failure delivering result  ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.cobaandroid/com.example.cobaandroid.MainActivity}: java.lang.NullPointerException: Attempt to invoke  virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
12-12 15:36:10.994: E/AndroidRuntime(30866):    at and roid.app.ActivityThread.deliverResults(ActivityThread.java:3368)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3411)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at android.app.ActivityThread.access$1300(ActivityThread.java:138)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at android.os.Handler.dispatchMessage(Handler.java:102)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at android.os.Looper.loop(Looper.java:136)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at android.app.ActivityThread.main(ActivityThread.java:5050)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at java.lang.reflect.Method.invoke(Native Method)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-12 15:36:10.994: E/AndroidRuntime(30866): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
12-12 15:36:10.994: E/AndroidRuntime(30866):    at com.example.cobaandroid.MainActivity.onActivityResult(MainActivity.java:222)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at android.app.Activity.dispatchActivityResult(Activity.java:5433)
12-12 15:36:10.994: E/AndroidRuntime(30866):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3364)
 12-12 15:36:10.994: E/AndroidRuntime(30866):   ... 9 more
 12-12 15:36:14.147: I/Process(30866): Sending signal. PID: 30866 SIG: 9
 12-12 15:46:38.153: I/Adreno-EGL(31795): <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM build:  (CL3776187)
 12-12 15:46:38.153: I/Adreno-EGL(31795): OpenGL ES Shader Compiler Version: 
 12-12 15:46:38.153: I/Adreno-EGL(31795): Build Date: 10/15/13 Tue
 12-12 15:46:38.153: I/Adreno-EGL(31795): Local Branch: 
 12-12 15:46:38.153: I/Adreno-EGL(31795): Remote Branch: partner/upstream
 12-12 15:46:38.153: I/Adreno-EGL(31795): Local Patches: 
 12-12 15:46:38.153: I/Adreno-EGL(31795): Reconstruct Branch: 
 12-12 15:46:38.183: D/OpenGLRenderer(31795): Enabling debug mode 0
 12-12 15:46:45.811: E/JavaBinder(31795): !!! FAILED BINDER TRANSACTION !!!

0 个答案:

没有答案