无法在android目录中写入新文件

时间:2013-12-05 15:19:44

标签: android image android-intent

我最近有很好的精神来开发Android应用程序并且已经多次询问过android编程,所以如果我再问一遍就不要打扰:D(Intermezzo) 其实我遇到了一些问题。我已经完成了一个应用程序的开发,它在我的设备三星Note 10.1中工作得非常好。但是,当我将应用程序安装到其他设备时,我遇到了一些错误和问题 第一个,我的应用程序在使用相机捕获图像并按下按钮保存后崩溃。我正在使用意图打开相机。 第二个,在我进行裁剪活动后,裁剪后的图像无法在我自己的目录中写入,但目录存在。这是我的代码,如果你借给我我的帮助真的很高兴:)

MainActivity.java

package com.example.cobaandroid;
import java.io.InputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

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;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tampilkanUserManual();
    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);
}

//Cek apakah device memiliki kamera
private Boolean supportCamera()
{
    if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
    {
        return true;
    }
    else return false;
}

// Button onClick 
public void onClick(View v)
{
    if(v.getId()==R.id.ambil_gambar)
    {
        try
        {
            //Intent untuk menggunakan kamera
            Intent intentAmbil = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            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 untuk ngambil gambar di galeri
            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);
        }
        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.inSampleSize = 8;
            option.inJustDecodeBounds = true;
            Bitmap hasilPoto = (Bitmap) data.getExtras().get("data");
            if(hasilPoto==null)
            {
                Toast.makeText(getApplicationContext(), "bitmap null", Toast.LENGTH_LONG).show();
            }
            picUri = data.getData();
            Toast.makeText(getApplicationContext(), picUri.getPath(), Toast.LENGTH_LONG).show();
            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 gambar dari galeri
            Uri galeriUri = data.getData();
            String[] path = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(galeriUri,path,null,null,null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(path[0]);
            String gambarPath = cursor.getString(columnIndex);
            cursor.close();
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inJustDecodeBounds = true;
            opt.inSampleSize = calculateInSampleSize(opt, 50, 100);

            Bitmap hasilPoto = BitmapFactory.decodeFile(gambarPath);
            //Bitmap hasilPoto = BitmapFactory.decodeFile(gambarPath, opt);
            hasilPoto = scaleDown(hasilPoto, 100, getApplicationContext());
            Intent cropIntents = new Intent(this,Crop.class);
            cropIntents.putExtra("data", galeriUri.toString());
            cropIntents.putExtra("kode","galeri");
            cropIntents.putExtra("gambar",hasilPoto);
            cropIntents.putExtra("path", gambarPath);
            startActivity(cropIntents);
        }
    }
}
//fungsi untuk scaling gambar
private Bitmap scaleDown(Bitmap photo, int newHeight,Context contex)
{
    final float densityMultiplier = contex.getResources().getDisplayMetrics().density;
    int h = (int) (newHeight*densityMultiplier);
    int w = (int) (h*photo.getWidth()/(double)photo.getHeight());
    photo = Bitmap.createScaledBitmap(photo, w, h, true);
    return photo;
}

//tampilkan userManual
private void tampilkanUserManual()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    View view = inflater.inflate(R.layout.activity_usermanual, null);
    builder.setView(view);
    builder.setPositiveButton("Ok", null);
    AlertDialog dialog = builder.create();
    dialog.show();
}

}

在MainActivity.java中的

我正在使用相机和图库,用户可以从图库中选择图像或使用相机捕获图像。 这是xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/daun2"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/showTextHome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="@string/showText"
    android:textSize="40sp" />
<Button
    android:id="@+id/exit"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Keluar" />

<Button
    android:id="@+id/ambil_gambar"
    android:layout_width="276dp"
    android:layout_height="wrap_content"
    android:layout_above="@+id/ambilGallery"
    android:layout_alignRight="@+id/showTextHome"
    android:text="@string/ambil" />

<Button
    android:id="@+id/ambilGallery"
    android:layout_width="276dp"
    android:layout_height="wrap_content"
    android:layout_above="@+id/exit"
    android:layout_alignLeft="@+id/ambil_gambar"
    android:layout_marginBottom="26dp"
    android:text="@string/ambilGall" />

用户选择或捕获图像后,意图调用下一个活动Crop.java。在这个类中,用户可以裁剪图像并自动将其保存到名为“数据集”的目录

package com.example.cobaandroid;
import java.io.File;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class Crop extends Activity  {
public static int[] rataRed ;
public static  int[] rataGreen ;
public static  int[] rataBlue ;
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("Gambar diambil dari kamera");
    }
    else if(intentKode.equals("galeri"))
    {
        String path = getIntent().getParcelableExtra("path");
        Bitmap bmp = getIntent().getParcelableExtra("gambar");
        img.setImageBitmap(bmp);
        System.out.println("Gambar diambil dari galeri");
    }
    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
                {
                    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("crop","true");
                    intentCrop.putExtra("AspectX", 0);
                    intentCrop.putExtra("AspectY", 0);
                    intentCrop.putExtra("outputX", 256);
                    intentCrop.putExtra("outputY", 256);
                    intentCrop.putExtra("return-data",true);    
                    intentCrop.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                    startActivityForResult(intentCrop, PIC_CROP);
                }
                catch(ActivityNotFoundException activity)
                {

                }
            }
            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);
            Toast.makeText(getApplicationContext(), dir.getAbsolutePath(), Toast.LENGTH_LONG).show();
            int jumlahFile = cekDirektoriDataSet(dir);
            if(jumlahFile > 0)
            {
                Intent listIntent = new Intent(Crop.this,DataSet.class);
                listIntent.putExtra("uri", fileUri.toString());
                Crop.this.startActivity(listIntent);
            }
            else
            {
                Toast toast = Toast.makeText(getApplicationContext(),"Tidak ada citra di direktroi Dataset", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    });

}
// 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");
        Toast.makeText(getApplicationContext(), mediaFile.getPath(), Toast.LENGTH_LONG).show();

    }
    else return null;
    return mediaFile;   
}


public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,int reqHeight)
{
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if(height > reqHeight || width > reqWidth)
    {
        final int halfHeight = height/2;
        final int halfWidth = width/2;
        while((halfHeight/inSampleSize)>reqHeight && (halfWidth/inSampleSize)>reqWidth)
        {
            inSampleSize*=2;
        }
        long totalPixels = width*height/inSampleSize;
        final long totalReqPixelsCap = reqWidth*reqHeight*2;
        while(totalPixels > totalReqPixelsCap)
        {
            inSampleSize*=2;
            totalPixels/=2;
        }
    }
    return inSampleSize;
}


private Bitmap scaleDown(Bitmap photo, int newHeight,Context contex)
{
    final float densityMultiplier = contex.getResources().getDisplayMetrics().density;
    int h = (int) (newHeight*densityMultiplier);
    int w = (int) (h*photo.getWidth()/(double)photo.getHeight());
    photo = Bitmap.createScaledBitmap(photo, w, h, true);
    return photo;
}
//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;
}

}

这是作物的xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@drawable/daun2"
android:orientation="horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<ImageView
    android:id="@+id/gambarPoto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/list"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="86dp"
    android:contentDescription="@string/gambar"
    android:src="@drawable/ic_launcher" />

<Button
    android:id="@+id/cropButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/gambarPoto"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="28dp"
    android:layout_marginLeft="14dp"
    android:text="@string/crop" />

<TextView
    android:id="@+id/showCrop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="@string/showTextCrop"
    android:textAlignment="textStart"
    android:textSize="18sp"
    android:textStyle="italic|bold" />

<Button
    android:id="@+id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/cropButton"
    android:layout_alignBottom="@+id/cropButton"
    android:layout_alignRight="@+id/gambarPoto"
    android:text="@string/Dataset" />

我真的需要你的帮助 非常感谢...

0 个答案:

没有答案