0

ランドスケープ モードで画像をキャプチャし、ポートレート モードでアップロードしようとすると、Android アプリケーションで強制終了エラーが表示されます。のようなエラー..

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data dat=file:///mnt/sdcard/Pictures/CameraSample/testphoto20120717_103942-899201574.jpg typ=image/jpeg (has extras) }} to activity {com.freedom.net/com.example.android.photobyintent.PhotoIntentActivity}: java.lang.NullPointerException

Android.app.ActivityThread.performResumeActivity (ActivityThread.java:2141) で

public class PhotoIntentActivity extends MenuActivitySpecific {

private static final int ACTION_TAKE_PHOTO_B = 1;

private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private Handler imageUploadhandler, databaseHandler;
DBAdapter db;
private Dialog dialog;
private String mCurrentPhotoPath;
private  Uri imageUri1=null;
private static final String JPEG_FILE_PREFIX = "testphoto";
private static final String JPEG_FILE_SUFFIX = ".jpg";
File afile;
private AlbumStorageDirFactory mAlbumStorageDirFactory = null;


/* Photo album for this application */
private String getAlbumName() {
    return getString(R.string.album_name);
}
@Override
public void onWindowFocusChanged(boolean hasFocusFlag) {
    super.onWindowFocusChanged(hasFocusFlag);       
    if (hasFocusFlag) {
        openOptionsMenu();
    }
}

private File getAlbumDir() {
    File storageDir = null;

    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

        storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());

        if (storageDir != null) {
            if (! storageDir.mkdirs()) {
                if (! storageDir.exists()){
                    Log.d("CameraSample", "failed to create directory");
                    return null;
                }
            }
        }

    } else {
        Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
    }

    return storageDir;
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = JPEG_FILE_PREFIX + timeStamp ;
    File albumF = getAlbumDir();
    File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
    return imageF;
}

private File setUpPhotoFile() throws IOException {

    File f = createImageFile();
    mCurrentPhotoPath = f.getAbsolutePath();

    return f;
}

private void setPic() {


    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    /* Figure out which way needs to be reduced less */
    int scaleFactor = 1;
    if ((targetW > 0) || (targetH > 0)) {
        scaleFactor = Math.min(photoW/targetW, photoH/targetH); 
    }

    /* Set bitmap options to scale the image decode target */
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    /* Decode the JPEG file into a Bitmap */
    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);

    Matrix matrix = new Matrix();
    matrix.postRotate(90);
    Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, 
            bitmap.getWidth(), bitmap.getHeight(), 
                                  matrix, true);

    mImageView.setImageBitmap(rotated);

    mImageView.setVisibility(View.VISIBLE);

}

private void galleryAddPic() {
        Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
        afile = new File(mCurrentPhotoPath);
        String abcd=afile.toString();
        Uri contentUri = Uri.fromFile(afile);
        imageUri1 = Uri.parse(abcd);
        Uri uri2 = Uri.parse(new File(abcd).toString());
        Uri uri3 = Uri.fromFile(new File(abcd));
        Log.i("uri1, uri2, uri3 :", imageUri1+","+uri2+","+uri3+"");
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
}

private void dispatchTakePictureIntent(int actionCode) {

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    switch(actionCode) {
    case ACTION_TAKE_PHOTO_B:
        File f = null;

        try {
            f = setUpPhotoFile();
            mCurrentPhotoPath = f.getAbsolutePath();
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        } catch (IOException e) {
            e.printStackTrace();
            f = null;
            mCurrentPhotoPath = null;
        }
        break;

    default:
        break;          
    } // switch

    startActivityForResult(takePictureIntent, actionCode);
}




private void handleBigCameraPhoto() {

    if (mCurrentPhotoPath != null) {
        setPic();
        galleryAddPic();
        mCurrentPhotoPath = null;
    }

}



/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cameracapturedimage);
    db = new DBAdapter(this);
    imageUploadhandler = new Handler();
    mImageView = (ImageView) findViewById(R.id.cameraImage);
    //mVideoView = (VideoView) findViewById(R.id.videoView1);
    mImageBitmap = null;
    //mVideoUri = null;


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
    } else {
        mAlbumStorageDirFactory = new BaseAlbumDirFactory();
    }

    dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menucapturedimage, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.backToHome:
        finish();
        return true;
    case R.id.save:
        upload();
        return true;
    case R.id.retakePicture:
        dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case ACTION_TAKE_PHOTO_B: {
        if (resultCode == RESULT_OK) {
            handleBigCameraPhoto();
        }
        if (resultCode == RESULT_CANCELED) {
            Intent intent = new Intent(PhotoIntentActivity.this, Home.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            finish();
            startActivity(intent);
        }
        break;
    } // ACTION_TAKE_PHOTO_B


    } // switch
}

// Some lifecycle callbacks so that the image can survive orientation change
@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);

    outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );

    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);

    mImageView.setImageBitmap(mImageBitmap);
    mImageView.setVisibility(
            savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? 
                    ImageView.VISIBLE : ImageView.INVISIBLE
    );

}

public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list =
        packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}


public void upload() {
    try {
        boolean check = Utility.isNetworkAvailable(PhotoIntentActivity.this);
        // boolean check1 =isOnline();
        if (check) {



            String newtime = Utility.getdate();
            String accesskey = Utility.MD5_Hash(Constants.email + newtime
                    + "moko");
            Constants.ACCESS_KEY = accesskey;
            Constants.proc_date = newtime;
            imageUploadhandler.postDelayed(runImageUpload, 500);
            dialog = ProgressDialog.show(PhotoIntentActivity.this, "",
                    "しばらくお待ちください", true);
            dialog.setCancelable(true);
        } else {

            databaseHandler.postDelayed(runDatabaseImageSave, 500);
            dialog = ProgressDialog.show(PhotoIntentActivity.this, "",
                    "しばらくお待ちください", true);
            dialog.setCancelable(true);

        }
    } catch (Exception e) {

        dialog.cancel();
        Toast.makeText(this, e + "", Toast.LENGTH_LONG).show();
    }
}

private final Runnable runImageUpload = new Runnable() {

    public void run() {

        Log.i("contentUri1", imageUri1+"");
        ResponseFromServer response = Utility.uploadFileAsImage(afile,
                PhotoIntentActivity.this);

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        if (response != null) {


            if (response.getStatus().equalsIgnoreCase("OK")) {
                    Toast.makeText(getApplicationContext(), "画像を保存しました。",
                        Toast.LENGTH_LONG).show();
                finish();
            }
        } else {
            new AlertDialog.Builder(PhotoIntentActivity.this)
                    .setTitle("エラー")
                    .setMessage("ファイル送信に失敗しました。")
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub
                                }
                            }).show();
            return;

        }

    }
};

private final Runnable runDatabaseImageSave = new Runnable() {

    public void run() {

        try {
            InputStream iStream = getContentResolver().openInputStream(
                    imageUri1);

            byte[] inputData = iStream.toString().getBytes();
            db.open();
            String stringUri = imageUri1.toString();
            String userMail = Constants.email;
            Log.e("Email: ", userMail + "");
            boolean feedback = db.InsertImage(inputData, stringUri,
                    userMail, 1);

            db.close();

            if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (feedback) {
                Toast.makeText(PhotoIntentActivity.this, "画像を保存しました。",
                        Toast.LENGTH_LONG).show();
                finish();
            } else {
                new AlertDialog.Builder(PhotoIntentActivity.this)
                        .setTitle("エラー")
                        .setMessage("ファイル送信に失敗しました。")
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                    }
                                }).show();
                return;

            }
        } catch (Exception e) {
            Log.e("Error to upload Image to database: ", e + "");
        }

    }
};



}
4

2 に答える 2

3

画像クリックから画像アップロードまでの向きの変更を指しているので、構成の変更を処理していないと思います

<activity android:name=".YourActivityName"
          android:configChanges="orientation"/> 

マニフェストファイルに以下を入れて、それが機能するかどうかを確認してください

于 2012-07-17T08:10:10.897 に答える
0

ログメッセージの最後は、問題を示していますjava.lang.NullPointerException。その後にスタックトレースがあるはずです。応答Activityを処理するときに例外をスローしていますIntent。スタックトレースには、エラーが発生したonActivityResult()場所でエラーが表示されると思います。

于 2012-07-17T08:19:12.060 に答える