如何使用Asynctask在imageview上捕获和显示图像?

时间:2017-02-22 10:46:24

标签: android android-asynctask nullpointerexception

我在我的android活动中使用AsyncTask通过内置摄像头捕获图像并在图像视图上显示它。但是发生了错误?我不知道如何解决它。请给出一些解决方案。

这是我的代码:

public class MainActivity extends Activity {
    final static int REQUEST_CODE = 1;
    Uri imageuri = null;
    String ImageID = null;
    MainActivity mainActivity = null;
    public static ImageView imageview = null;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageButton btn = (ImageButton)findViewById(R.id.imageButton);
        imageview = (ImageView)findViewById(R.id.imageView);


        btn.setOnClickListener(new View.OnClickListener() {

            //Camera Intent
            @Override
                public void onClick(View v) {


                String filename = "awais.jpg";

                ContentValues val = new ContentValues();
                val.put(MediaStore.Images.Media.TITLE, filename);

                imageuri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, val);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                startActivityForResult(intent, REQUEST_CODE);

            }
        });



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

        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {

            // Toast.makeText(this,"o0k",Toast.LENGTH_SHORT).show();


            ImageID = Converturi(imageuri, mainActivity);

            new loadphoto().execute("" + ImageID)
                ;

        }

    }

    public static String Converturi(Uri Imageuri, Activity activity) {

        Cursor cursor = null;
        int  imageid = 0;

        try {

            String proj[] = {
                MediaStore.Images.Media._ID,
                MediaStore.Images.Thumbnails._ID
            };

            cursor = activity.managedQuery(Imageuri, proj, null, null, null);

            int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
            int thumb = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);

            //int size=cursor.getCount();
            int thumbid = 0;

            if (cursor.moveToFirst()) {

                imageid = cursor.getInt(index);
                thumbid = cursor.getInt(thumb);
            }

        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return "" + imageid;
    }

    public  class loadphoto extends AsyncTask<String, Void, Void> {
        ProgressDialog dailog = new ProgressDialog(MainActivity.this);
        Bitmap mainbitmap;


        @Override
            protected void onPreExecute() {

            dailog.setMessage("Loading");
            dailog.show();

        }

        @Override
            protected Void doInBackground(String... urls) {

            Bitmap bitmap = null;
            Bitmap newbitmap = null;

            Uri uri = null;

            try {


                uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + urls[0]);
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

                if (bitmap != null) {
                    newbitmap = Bitmap.createScaledBitmap(bitmap, 170, 170, true);
                    bitmap.recycle();

                    if (newbitmap != null) {
                        mainbitmap = newbitmap;
                    }
                }
            }
            catch (IOException e) {
                cancel(true);
            }


            return null;
        }
        @Override
            protected void onPostExecute(Void unused) {

            dailog.dismiss();
            if (mainbitmap != null) {

                imageview.setImageBitmap(mainbitmap);
            }
        }
    }

错误:

E/AndroidRuntime: FATAL EXCEPTION: main
     java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.itinternee.camera/com.example.itinternee.camera.MainActivity}: java.lang.NullPointerException
         at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
         at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
         at android.app.ActivityThread.access$1100(ActivityThread.java:141)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
         at android.os.Handler.dispatchMessage(Handler.java:99)
         at android.os.Looper.loop(Looper.java:137)
         at android.app.ActivityThread.main(ActivityThread.java:5103)
         at java.lang.reflect.Method.invokeNative(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:525)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
         at dalvik.system.NativeStart.main(Native Method)
      Caused by: java.lang.NullPointerException
         at com.example.itinternee.camera.MainActivity.Converturi(MainActivity.java:93)
         at com.example.itinternee.camera.MainActivity.onActivityResult(MainActivity.java:72)
         at android.app.Activity.dispatchActivityResult(Activity.java:5322)
         at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
         at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410) 
         at android.app.ActivityThread.access$1100(ActivityThread.java:141) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304) 
         at android.os.Handler.dispatchMessage(Handler.java:99) 
         at android.os.Looper.loop(Looper.java:137) 
         at android.app.ActivityThread.main(ActivityThread.java:5103) 
         at java.lang.reflect.Method.invokeNative(Native Method) 
         at java.lang.reflect.Method.invoke(Method.java:525) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
         at dalvik.system.NativeStart.main(Native Method) 

1 个答案:

答案 0 :(得分:0)

我认为你不需要你的异步函数来加载imageView中的图片.... 首先使用代码启动相机然后进入

 btn.setOnClickListener(new View.OnClickListener() {
        //Camera Intent
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 0);
        }
    });

OnActivityResult添加了这个。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        Bitmap imageCapture = (Bitmap) data.getExtras().get("data");
        imageview.setImageBitmap(imageCapture);

    } catch (NullPointerException e) {

    }

}