startActivityForResult()用于选择图像,为什么我没有得到RESULT_OK?

时间:2013-12-12 17:13:48

标签: android

在我的简单活动中,我启动了一个图像的选择。

在我想要显示图像的选择结果上。

但调试我发现resultCode == RESULT_OK不是true

我在这里做错了什么???

public class PictureActivity extends Activity {
private static final int SELECT_PICTURE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivityForResult(intent, SELECT_PICTURE);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {

            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setType("image/*");
            intent.setData(data.getData());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }
}
}

2 个答案:

答案 0 :(得分:5)

这是因为:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

来自文档:http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NEW_TASK

“当调用者从正在启动的活动请求结果时,不能使用此标志。”

答案 1 :(得分:0)

使用我的代码: -

  Uri selectedImageUri; // Global Variable
  String  selectedPath; // Global Variable
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView preview = findViewById(R.id.preview);
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), 10);
    } 


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



        if (resultCode == RESULT_OK) {
         if(data.getData() != null){
           selectedImageUri = data.getData();
         }else{
          Log.d("selectedPath1 : ","Came here its null !");
          Toast.makeText(getApplicationContext(), "failed to get Image!", 500).show();
         }

            if (requestCode == 10)

            {

               selectedPath = getPath(selectedImageUri);
               preview.setImageURI(selectedImageUri);
               Log.d("selectedPath1 : " ,selectedPath);

            }

        }

    }