【问题标题】:getActivityResult() intent parameter gives nullgetActivityResult() 意图参数给出 null
【发布时间】:2015-02-13 06:45:48
【问题描述】:

早上好,先生, 我使用了导航抽屉和片段。 我正在使用 ActionBarActivity 并在其中调用了这个 Fragment。 在我的 Fragment 中,我从相机捕获图像,因此在 getActivityResult() 方法中没有给我 Intent 值。

package com.ssoft.admin.imageprocessingwithnavigation;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class CameraDemo extends Fragment implements View.OnClickListener {
    ImageButton mImgBtnActivityBack,mImgBtnActivityWrong,mImgBtnActivityRight ,mImgBtnActivityEdit ,mImgBtnActivitySearch ,mImgBtnActivityAdd ,mImgBtnActivityNext,mImgBtnActivitySetting;
    LinearLayout mLinearLayout1,mLinearLayout2;
    Button mFragSignatureClear,mBtnBlack,mBtnRed,mSIBtnSubmit,mSIBtnCamera,mSIBtnAdd ;
    PaintView mPaintView;
    int currrID = 0;
    android.support.v4.app.Fragment fragment;
    public int st = 3;
    int sizex, sizeh;
    Paint paint = new Paint() ;
    Uri imageUri=null ;
    final int CAMERA_DATA = 1888, INTENT_DATA = 1 ;
    Bitmap mbkground ;
    public CameraDemo() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        mbkground = null ;
        mLinearLayout2=(LinearLayout) rootView.findViewById(R.id.draw);
        mPaintView = new PaintView(getActivity().getApplicationContext());
        mLinearLayout2.addView(mPaintView);
        mFragSignatureClear=(Button) rootView.findViewById(R.id.fragSignatureClear);
        mFragSignatureClear.setOnClickListener(this);
        mBtnBlack=(Button)rootView.findViewById(R.id.black);
        mBtnBlack.setOnClickListener(this);
        mBtnRed=(Button)rootView.findViewById(R.id.red);
        mBtnRed.setOnClickListener(this);
        mSIBtnSubmit=(Button) rootView.findViewById(R.id.fragSIBtnSubmit);
        mSIBtnSubmit.setOnClickListener(this);
        mSIBtnCamera=(Button) rootView.findViewById(R.id.camera) ;
        mSIBtnCamera.setOnClickListener(this) ;
        mSIBtnAdd = (Button) rootView.findViewById(R.id.add) ;
        mSIBtnAdd . setOnClickListener( this );
        DisplayMetrics m = this.getResources().getDisplayMetrics();
        float density = getResources().getDisplayMetrics().density;

        int w = m.widthPixels;
        int h = m.heightPixels;

        sizex = w;
        sizeh = h;

        Log.i("hi", "" + sizex);
        Log.i("hi", "" + sizeh);
        Log.i("hi", "" + density);
        float fsize = sizex / density;

        return rootView;
    }
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.black){
            currrID=v.getId();
        }else if(v.getId()==R.id.black){
            currrID=v.getId();
        }else if(v.getId()==R.id.fragSIBtnSubmit){
            mPaintView.toJPEGFile();
            mPaintView.SaveFile();
        }else if(v.getId()==R.id.camera){
                captureImage();
        }else if(v.getId()==R.id.add){
            mPaintView.loadFromFile();
        }

        else {
            Toast.makeText(getActivity().getApplicationContext(), "FragSIPhotos Add Button OnClick", Toast.LENGTH_SHORT).show();

        }
    }
    class Point {
        float x, y;

        public String toString() {
            return x + "," + y;
        }
    }
    public class LineData {
        List<Point> points = new ArrayList<Point>();

        LineData(List<Point> p) {
            points.addAll(p);
        }

        public void Draw(Canvas mCanvas, Paint paint) {
            float fData[] = new float[points.size() * 4];
            int Index = 0;
            for (Point point : points) {
                if (Index > 0) {
                    fData[Index++] = point.x;
                    fData[Index++] = point.y;
                }
                fData[Index++] = point.x;
                fData[Index++] = point.y;
                // canvas.drawCircle(point.x, point.y, 5, paint);

            }
            if (Index > 2)
                mCanvas.drawLines(fData, 0, Index - 2, paint);

        }
    }
    public class PaintView extends View implements View.OnTouchListener {
        private static final String TAG = "PaintView" ;
        Paint paint = new Paint() ;
        int t = 0 ;
        List<Point> points = new ArrayList<Point>() ;
        List<LineData> pointsred = new ArrayList<LineData>() ;
        List<LineData> pointsblack = new ArrayList<LineData>() ;
        public PaintView(Context context) {
            super(context) ;
            setFocusable(true) ;
            setFocusableInTouchMode(true) ;
            List<Point> points = new ArrayList<Point>() ;

            setDrawingCacheEnabled(true) ;
            this.setOnTouchListener(this) ;
            mbkground = BitmapFactory.decodeResource(getResources(),
                    R.drawable.plain) ;

            paint.setAntiAlias(true) ;
            paint.setStrokeMiter(10.0f) ;
            paint.setStrokeWidth(st) ;

            currrID = R.id.red ;

        }
        @Override
        public void onDraw(Canvas mCanvas) {
            mCanvas.drawBitmap(mbkground, 0, 0, null);
            // canvas.drawColor(Color.WHITE) ;
            this.setBackgroundColor(Color.BLACK);
            // To Do Paint for text
            //this code for  my image app
            //yesss very good
        /*    Paint mText= new Paint(Color.RED);
            mText.setTextSize(25);
            mCanvas.drawText("Hiren",100,100,mText);
        */    if (currrID == R.id.red)
                paint.setColor(Color.RED) ;
            else if (currrID == R.id.black)
                paint.setColor(Color.BLACK) ;
            else
                paint.setColor(Color.BLACK) ;

            float fdata[] = new float[points.size() * 4] ;
            int Index = 0 ;
            for (Point point : points) {
                if (Index > 0) {
                    fdata[Index++] = point.x ;
                    fdata[Index++] = point.y ;
                }
                fdata[Index++] = point.x ;
                fdata[Index++] = point.y ;
                // canvas.drawCircle(point.x, point.y, 5, paint);

            }
            if (Index > 2)
                mCanvas.drawLines(fdata, 0, Index - 2, paint);

            paint.setColor(Color.RED) ;
            for (LineData lines : pointsred)
                lines.Draw(mCanvas, paint) ;


            paint.setColor(Color.BLACK) ;
            for (LineData lines : pointsblack)
                lines.Draw(mCanvas, paint) ;

            paint.setColor(Color.WHITE) ;

        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
                points.clear() ;
            } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                {
                    LineData data = new LineData(points) ;

                    if (currrID == R.id.red)
                        pointsred.add(data) ;
                    else if (currrID == R.id.black)
                        pointsblack.add(data) ;

                    points.clear() ;
                }
            } else {

                Point point = new Point() ;

                point.x = event.getX() ;

                point.y = event.getY() ;

                points.add(point) ;
            }
            invalidate() ;

            return true;

        }
        public void toJPEGFile() {
            File folder = new File(Environment.getExternalStorageDirectory()
                    + "/Mateco/") ;

            if (!folder.exists())
                folder.mkdirs() ;
            try {

                this.setDrawingCacheEnabled(true) ;

                File f = new File(Environment.getExternalStorageDirectory()
                        + "/Mateco/" + "Mateco" + ".png") ;
                // file mFile = new File(Environment.g)
                FileOutputStream fos = new FileOutputStream(f) ;

                Bitmap bitmap = this.getDrawingCache() ;
                bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos) ;
                // 80 quality bet 0-100 define

                fos.flush() ;
                fos.close() ;
                this.setDrawingCacheEnabled(false) ;

            } catch (FileNotFoundException e) {

                e.printStackTrace() ;
            } catch (IOException e) {

                e.printStackTrace() ;
            }

        }

        public void loadFromFile() {

            FileInputStream in;
            BufferedInputStream buf;

            try {
                in = new FileInputStream(
                        Environment.getExternalStorageDirectory() + "/Mateco/"
                                + "mateco" + ".jpg");
                buf = new BufferedInputStream(in);

                mbkground = BitmapFactory.decodeStream(buf);

                if (in != null) {
                    in.close();
                }
                if (buf != null) {
                    buf.close();
                }
            } catch (Exception e) {
                Log.e("Error reading file", e.toString());
            }
        }

        public void setBitMap(){

           /* mbkground = BitmapFactory.decodeResource(getResources(),
                    R.drawable.background) ;
*/
        }
        public void setBitMap(Bitmap photo){

            mbkground = photo;
        }

        public void SaveFile() {
            Toast.makeText(getActivity().getApplicationContext(),"Save 1",Toast.LENGTH_SHORT).show();
            File folder = new File(Environment.getExternalStorageDirectory()
                    + "/Mateco/");

            if (!folder.exists())
                folder.mkdirs();
            try {
                this.setDrawingCacheEnabled(true);
                t++;
                File f = new File(Environment.getExternalStorageDirectory()
                        + "/Mateco/" + System.currentTimeMillis() + ".jpg");
                FileOutputStream fos = new FileOutputStream(f);
                Bitmap bitmap = this.getDrawingCache();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                // 80 quality bet 0-100 define

                fos.flush();
                fos.close();
                File temp = new File(Environment.getExternalStorageDirectory()
                        + "/Mateco/" + "Mateco" + ".png");
                temp.delete();
                this.setDrawingCacheEnabled(false);

            } catch (FileNotFoundException e) {

                Toast.makeText(getActivity().getApplicationContext(),"FILE_NOT_FOUND_EXCEPTION  "+e.getMessage(),Toast.LENGTH_SHORT).show();

                e.printStackTrace();
            } catch (IOException e) {

                Toast.makeText(getActivity().getApplicationContext(),"IO_EXCEPTION  "+e.getMessage(),Toast.LENGTH_SHORT).show();

                e.printStackTrace();
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Intent mediaScanIntent = new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                File f = new File(
                        "file://"
                                + Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
                Uri contentUri = Uri.fromFile(f);
                mediaScanIntent.setData(contentUri);
                getActivity().getApplicationContext().sendBroadcast(mediaScanIntent);
                Toast.makeText(getActivity().getApplicationContext(),"Save 9",Toast.LENGTH_SHORT).show();

            } else {
                getActivity().getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                        Uri.parse("file://"
                                + Environment.getExternalStorageDirectory())));
                Toast.makeText(getActivity().getApplicationContext(),"Save 11",Toast.LENGTH_SHORT).show();

            }
        }
    }
    public void captureImage(){
        // Define the file-name to save photo taken by Camera activity

        String fileName = "Mateco.jpg";

        // Create parameters for Intent with filename

        ContentValues values = new ContentValues();

        values.put(MediaStore.Images.Media.TITLE, fileName);
        // Log.e("Intrenal Storage "+MediaStore.Images.Media.INTERNAL_CONTENT_URI.toString(),"");

        values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");

        // imageUri is the current activity attribute, define and save it for later usage

        Uri imageUri = getActivity().getApplicationContext().getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
      /*  Uri imageUri=getActivity().getApplicationContext().getContentResolver().insert( MediaStore. Images. Media. INTERNAL_CONTENT_URI,values ) ;
*/
        /**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/


        // Standard Intent action that can be sent to have the camera
        // application capture an image and return it.

        Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );

        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, INTENT_DATA);
        Log.e("captureImage()", "state -1");
        getActivity().startActivityForResult(intent, CAMERA_DATA);
        Log.e("captureIma   ge()", "end");

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("OnActivityResult()", "1");
        try {
            if (requestCode == CAMERA_DATA && resultCode == getActivity().RESULT_OK) {
                // Image captured and saved to fileUri specified in the Intent
                Log.e("OnActivityResult()", "2");

                InputStream stream =getActivity().getApplicationContext(). getContentResolver().openInputStream(
                        data.getData());
                mbkground = BitmapFactory.decodeStream(stream);
                Log.e("OnActivityResult()", "2.1");

                Bitmap photo = (Bitmap) data.getExtras().get("data");
                Log.e("OnActivityResult()", "2.2");

                mPaintView.setBitMap(photo);
                Log.e("OnActivityResult()", "3");
            } else {
                // Image capture failed, advise user
                Log.e("OnActivityResult()", "5");
            }
        }catch (Exception objException){
            Log.e("onActivityResult();",""+objException.getMessage());
        }
    }
}

【问题讨论】:

  • 由于您正在调用getActivity().startActivityForResult(intent, CAMERA_DATA),因此托管活动将收到结果。你试过在没有getActivty() 的情况下调用它吗?这样你的片段应该得到结果。
  • Mr.MH 我会尝试你的建议,但它不起作用它还在 Intent 中给出空值
  • @HirenVaghela:你在哪里使用getActivityResult() ??
  • 托管您片段的活动将获得意图和所需的结果。您应该在该活动中实现“onActivityResult”并将结果保存在公共对象的某个位置,然后在您想要的任何地方访问它。
  • 我在 Fragment 中使用过 onActivityResult()

标签: android android-intent android-fragments android-camera


【解决方案1】:

这一行没有返回你的想法:

            InputStream stream =getActivity().getApplicationContext(). getContentResolver().openInputStream(
                    data.getData());

如果您在这些行中执行您所做的操作,它会返回一个 URI:

            Uri contentUri = Uri.fromFile(f);
            mediaScanIntent.setData(contentUri);

但你没有,所以它不会返回你所期望的。您需要通过获取存储的 URI 来获取 ImageURL,如下所示:

            InputStream stream =getActivity().getApplicationContext(). getContentResolver().openInputStream(
                    data.getStringExtra(MediaStore.EXTRA_OUTPUT));

编辑:

另外,startActivityForResult 用于调用一个新的Activity,当它“完成”时将回调它正在调用Activity 的方法onActivityResult - 所以你的部分代码可能也是造成问题。不过,您现在应该可以对其进行排序了...

【讨论】:

  • openInputStream() 需要 Uri 作为参数。
  • yes - 如果设置了正确的属性,data.getData() 将返回一个 URI。我没有正确说明我的回答。
  • 您好先生,任何人有解决方案请帮助我
猜你喜欢
  • 2019-08-07
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多