onActivityResult数据始终在片段内返回null

时间:2015-05-15 08:00:41

标签: android android-intent android-fragments

gallery.class

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

public class gallery extends Fragment {
    private static final int PICK_FROM_GALLERY = 1;
    RelativeLayout gallerylayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.mainfragment, container, false);
        gallerylayout = (RelativeLayout) v.findViewById(R.id.gallery_layout);
        gallerylayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fireGallery();
            }
        });
        return v;
    }

    private void fireGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PICK_FROM_GALLERY:
                String[] all_path = data.getStringArrayExtra("all_path");
                System.out.println("all_path " + all_path); //Returns null
                System.out.println("Data " + data.getExtras()); //Returns null
                break;
        }
    }

}

onActivityResult中的数据始终为空,如果我的代码有任何问题,请纠正我。如前所述,onActivityResult内的两个日志都返回null。注意我正在扩展Fragment而不是活动。

3 个答案:

答案 0 :(得分:0)

试试这个,您可以从中获取数据:

@Override
    protected void onActivityResult (int requestCode,int resultCode,Intent data){
        super.onActivityResult (requestCode,resultCode,data);


        try{

            // When an Image is picked
             if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK
                    && null != data){

                // Get the Image from data
                Uri selectedImage = data.getData ();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                // Get the cursor
                Cursor cursor = getContentResolver ().query (selectedImage,
                        filePathColumn,null,null,null);

                // Move to first row
                cursor.moveToFirst ();

                int columnIndex = cursor.getColumnIndex (filePathColumn[0]);
            String imgDecodableString = cursor.getString (columnIndex);
                cursor.close ();

                Log.e ("Image Path",imgDecodableString);

                Toast.makeText (this,"You have picked Image" ,
                        Toast.LENGTH_LONG).show ();


            }
            else{

                Toast.makeText (this,"You haven't picked Image",
                        Toast.LENGTH_LONG).show ();
            }
        }
        catch (Exception e){

            Toast.makeText (this,"Something went wrong",Toast.LENGTH_LONG)
                    .show ();
            Log.e ("Exception",e.toString ());
        }
    }

答案 1 :(得分:0)

您可以阅读http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en?fb_action_ids=780839882030502&fb_action_types=og.comments

创建ActivityResultEvent.java

import android.content.Intent;

/**
 * Created by nuuneoi on 3/12/2015.
 */
public class ActivityResultEvent {

    private int requestCode;
    private int resultCode;
    private Intent data;

    public ActivityResultEvent(int requestCode, int resultCode, Intent data) {
        this.requestCode = requestCode;
        this.resultCode = resultCode;
        this.data = data;
    }

    public int getRequestCode() {
        return requestCode;
    }

    public void setRequestCode(int requestCode) {
        this.requestCode = requestCode;
    }

    public int getResultCode() {
        return resultCode;
    }

    public void setResultCode(int resultCode) {
        this.resultCode = resultCode;
    }

    public Intent getData() {
        return data;
    }

    public void setData(Intent data) {
        this.data = data;
    }
}

创建ActivityResultBus.java

import android.os.Handler;
import android.os.Looper;

import com.squareup.otto.Bus;

/**
 * Created by nuuneoi on 3/12/2015.
 */
public class ActivityResultBus extends Bus {

    private static ActivityResultBus instance;

    public static ActivityResultBus getInstance() {
        if (instance == null)
            instance = new ActivityResultBus();
        return instance;
    }

    private Handler mHandler = new Handler(Looper.getMainLooper());

    public void postQueue(final Object obj) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                ActivityResultBus.getInstance().post(obj);
            }
        });
    }

}

//>>>>>>>>>>>>>>>> 覆盖活动上的onActivityResult

public class MainActivity extends ActionBarActivity {

    ...

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ActivityResultBus.getInstance().postQueue(
                    new ActivityResultEvent(requestCode, resultCode, data));
    }

    ...

}

片段:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Don't forget to check requestCode before continuing your job
        if (requestCode == 12345) {
            // Do your job
            tvResult.setText("Result Code = " + resultCode);
        }
    }
 @Override
    public void onStart() {
        super.onStart();
        ActivityResultBus.getInstance().register(mActivityResultSubscriber);
    }

    @Override
    public void onStop() {
        super.onStop();
        ActivityResultBus.getInstance().unregister(mActivityResultSubscriber);
    }

    private Object mActivityResultSubscriber = new Object() {
        @Subscribe
        public void onActivityResultReceived(ActivityResultEvent event) {
            int requestCode = event.getRequestCode();
            int resultCode = event.getResultCode();
            Intent data = event.getData();
            onActivityResult(requestCode, resultCode, data);
        }
    };

答案 2 :(得分:0)

if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK && null!=data)
 {
                Bitmap photo;
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = getActivity().getContentResolver().query(
                        selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                if (picturePath != null) {
                    Log.v("", picturePath);
                    cursor.close();
                    photo = BitmapFactory.decodeFile(picturePath);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    photo = Bitmap.createScaledBitmap(photo, 1200, 1200, true);
                    this.data = baos.toByteArray();
                    chooseImage.setImageBitmap(photo);
                } 
else {
                    Utilities.showToast(getActivity(),
                            "This image is not on your device");
        }

}

如果您想从图库中获取图片,那么您应该使用此功能