2012-03-05 12 views
1

これはギャラリーから画像を取得するためのコードです。これは、nullポインタの例外とクラッシュを与えています。私はデバイス自体のコードをテストしていて、ギャラリーでイメージを選択するとクラッシュします。私が間違っているアイデアは?ギャラリーから画像を読み込む際にヌルポインタ例外が発生しました。

     AlertDialog.Builder builder = new AlertDialog.Builder(CreatePod.this); 
         builder.setMessage("Select") .setCancelable(false).setPositiveButton("Gallery", new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int id) { 
            Intent gallIntent=new Intent(Intent.ACTION_GET_CONTENT); 
            gallIntent.setType("image/*"); 
            startActivityForResult(gallIntent, 10); 
           } 
         }) 




protected void onActivityResult(int requestCode, int resultCode, Intent data){ 


    super.onActivityResult(requestCode, resultCode, data); 






     switch (requestCode) { 
     case 10: 
      if (resultCode == Activity.RESULT_OK) { 
       Bundle extras = data.getExtras(); 
        Bitmap b = (Bitmap) extras.get("data"); 
        imgView.setImageBitmap(b); 

       String timestamp = Long.toString(System.currentTimeMillis()); 
        MediaStore.Images.Media.insertImage(getContentResolver(), b, timestamp, timestamp); 
       HttpResponse httpResponse; 
       ByteArrayOutputStream bao = new ByteArrayOutputStream(); 

      b.compress(Bitmap.CompressFormat.JPEG, 100, bao); 

      byte [] ba = bao.toByteArray(); 
      int f = 0; 
      String ba1=Base64.encodeToString(ba, f); 
+0

1.例外のスタックトレースを貼り付けます。デバッグモードでアプリを起動します。 stacktraceを見てください。 – Ivan

+0

しました。 Bundle extras = data.getExtras();を取得します。エキストラをヌルとして。 – Hick

答えて

5

代わりの

Bitmap b = (Bitmap) extras.get("data"); 
imgView.setImageBitmap(b); 

次のコード行を使用して使用して:

Uri imageUri = data.getData(); 
Bitmap b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); 
imgView.setImageBitmap(b); 

を私はそれが私のために働いている、あなたのコードを変更して走りました!

+0

これが私にヌルポインタ例外を与える場合はどうなりますか? – NarendraJi

0

あなたの間違いは、写真が追加で返品されないことです。そのUriはgetData()にあります。

は、代わりにこのコードを試してみてください。

 switch (requestCode) { 
     case 10: 
      if (resultCode == Activity.RESULT_OK) { 
       Uri bitmapUri = data.getData(); 

       try { 

        Bitmap b = Media.getBitmap(getContentResolver(), bitmapUri); 
        mImgView.setImageBitmap(b); 

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

       // ... etc ... 
       break; 
      } 
    } 

はまた、私はあなたがあまりにも多くのAlertDialogBu​​ilder周りにやっていると思います。私はちょうどこれをした:

public void myClickHandler(View clickTarget) { 
    Intent gallIntent = new Intent(Intent.ACTION_GET_CONTENT); 
    gallIntent.setType("image/*"); 
    gallIntent.addCategory(Intent.CATEGORY_OPENABLE); 
    startActivityForResult(gallIntent, 10); 
} 
関連する問題