简体   繁体   English

从图库中选择的图像未在Imageview中设置

[英]Selected image from gallery doesn't set in Imageview

Im trying to upload image from gallery. 我试图从画廊上传图像。

Here is the code I'm using. 这是我正在使用的代码。

image view in the xml file - xml文件中的图片视图-

<ImageView
   android:id="@+id/imgView"
   android:layout_width="20dp"
   android:layout_height="20dp"
   android:layout_marginLeft="260dp"
   android:layout_weight="1"/>

code in the java file - Java文件中的代码-

public class AddLabReport02 extends ActionBarActivity {

private static int RESULT_LOAD_IMAGE = 1;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_lab_report02);


        uploadLabReport = (Button) findViewById(R.id.uploadLabReport);

        uploadLabReport.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });

    }


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

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

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

            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }


    }

}

Here, when I click on uploadLabReport button, I can goto Gallery and select the image. 在这里,当我单击uploadLabReport按钮时,可以转到Gallery并选择图像。 But, after that Image is not set in the imageView. 但是,此后未在imageView中设置Image。

I don't see any wrong in my code. 我在代码中没有看到任何错误。 Can someone look at it? 有人可以看吗?

Thanks in advance :) 提前致谢 :)

edited code - 编辑的代码-

package myayubo.com.healthier;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;

import java.util.ArrayList;
import java.util.List;


public class AddLabReport02 extends ActionBarActivity {

    private Spinner IllnessType;

    private Spinner testReportType;

    private Button uploadLabReport;

    private static int GALLERY_PHOTO = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_lab_report02);

        IllnessType = (Spinner) findViewById(R.id.selectIllnessType);
        testReportType = (Spinner) findViewById(R.id.selectTest);
        uploadLabReport = (Button) findViewById(R.id.uploadLabReport);

        addItemsOnSpinnerIllnessType();
        addTestReportType();

        uploadLabReport.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                pickImage();
            }
        });
    }

    private void pickImage(){
        Intent chooserIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        chooserIntent.setType("image/*");
        startActivityForResult(chooserIntent, GALLERY_PHOTO);
    }

    // add Illness Type into spinner dynamically
    public void addItemsOnSpinnerIllnessType() {
        List<String> list = new ArrayList<String>();
        list.add("Illness Type");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        IllnessType.setAdapter(dataAdapter);
    }

    // add Test Report Type into spinner dynamically
    public void addTestReportType() {
        List<String> list = new ArrayList<String>();
        list.add("Test Report Type");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        testReportType.setAdapter(dataAdapter);


    }

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

        if (resultCode == GALLERY_PHOTO && data.getData() != null) {
            String filePath = GetFilePathFromDevice.getPath(AddLabReport02.this, data.getData());
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
        }


    }

    @SuppressLint("NewApi")
    public static final class GetFilePathFromDevice {

        /**
         * Get file path from URI
         *
         * @param context context of Activity
         * @param uri     uri of file
         * @return path of given URI
         */
        public static String getPath(final Context context, final Uri uri) {
            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {
                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{split[1]};
                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {
                // Return the remote address
                if (isGooglePhotosUri(uri))
                    return uri.getLastPathSegment();
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
            return null;
        }

        public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
            Cursor cursor = null;
            final String column = "_data";
            final String[] projection = {column};
            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int index = cursor.getColumnIndexOrThrow(column);
                    return cursor.getString(index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
            return null;
        }

        public static boolean isExternalStorageDocument(Uri uri) {
            return "com.android.externalstorage.documents".equals(uri.getAuthority());
        }

        public static boolean isDownloadsDocument(Uri uri) {
            return "com.android.providers.downloads.documents".equals(uri.getAuthority());
        }

        public static boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }

        public static boolean isGooglePhotosUri(Uri uri) {
            return "com.google.android.apps.photos.content".equals(uri.getAuthority());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_add_lab_report02, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        startActivity(new Intent(AddLabReport02.this, AddLabReport01.class));
        finish();

    }
}

Call below method in your Button click event. 在Button单击事件中调用以下方法。

uploadLabReport.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
       pickImage();
    }
});

Here is code i have used. 这是我使用的代码。 use it according to your need 根据您的需要使用

private static final int GALLERY_PHOTO = 111;
private void pickImage(){
     Intent chooserIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
     chooserIntent.setType("image/*");
     startActivityForResult(chooserIntent, GALLERY_PHOTO);
}

in your onActivityResult() you should use like this. 在您的onActivityResult()您应该这样使用。

 if (resultCode == GALLERY_PHOTO && data.getData() != null) {
        String filePath = GetFilePathFromDevice.getPath(AddLabReport02.this, data.getData());
       ImageView imageView = (ImageView) findViewById(R.id.imgView);
       imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
  }

Here is class used for getting file path from URI . 这是用于从URI获取文件路径的类。

public final class GetFilePathFromDevice {

    /**
     * Get file path from URI
     *
     * @param context context of Activity
     * @param uri     uri of file
     * @return path of given URI
     */
    public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

This code works fine. 此代码可以正常工作。 Figured out it myself. 我自己想通了。 :) :)

public class AddPrescription02 extends ActionBarActivity implements View.OnClickListener {

    private ImageView imageView;

    private Spinner illnessType;

    private Button uploadPrescription;

    private static int RESULT_LOAD_IMAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_prescription02);

        illnessType = (Spinner) findViewById(R.id.selectIllnessType);
        uploadPrescription = (Button) findViewById(R.id.uploadPrescription);

        imageView = (ImageView) findViewById(R.id.imgView);

        addItemsOnSpinnerIllnessType();

        uploadPrescription.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data!=null)
        {
            Uri selectedImage = data.getData();
            imageView.setImageURI(selectedImage);
        }
    }
}

1- fire Intent As: 1-射击意图为:

startActivityForResult(new Intent(Intent.ACTION_PICK,
                                       MediaStore.Images.Media.INTERNAL_CONTENT_URI),
                               GALLERY_PIC_REQUEST);

2- in onActivityResulr write this code: 2-在onActivityResulr中编写以下代码:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == GALLERY_PIC_REQUEST) {

                Uri selectedImage = data.getData();
                if (selectedImage != null) {
                    Cursor cursor = mContext.getContentResolver().query(selectedImage, new String[]
                                    {MediaStore.Images.ImageColumns.DATA},
                            null, null, null);
                    cursor.moveToFirst();
                    String path = cursor.getString(0);
                    Log.e("","$$$$$$$$$$ path of gallery " + path);
                    cursor.close();
                    setImageUser(path,true);
                }

            } 
}
}

Hope This will help you. 希望这会帮助你。

Use this way it will help 使用这种方式将有所帮助

private void uploadImage(){
    class UploadImage extends AsyncTask<Bitmap,Void,String>{

        ProgressDialog loading;
        RequestHandler rh = new RequestHandler();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(MainActivity.this, "Uploading Image", "Please wait...",true,true);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(Bitmap... params) {
            Bitmap bitmap = params[0];
            String uploadImage = getStringImage(bitmap);

            HashMap<String,String> data = new HashMap<>();
            data.put(UPLOAD_KEY, uploadImage);

            String result = rh.sendPostRequest(UPLOAD_URL,data);

            return result;
        }
    }

for more see here 更多信息请看这里

I used below code to show image on ImageView 我用下面的代码在ImageView上显示图像

Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, CHOOSE_FROM_GALLERY);

Inside onActivityResult: 在onActivityResult内部:

  if (requestCode == CHOOSE_FROM_GALLERY){

                 Uri selectedImage = data.getData();
                    String[] filePath = { MediaStore.Images.Media.DATA };
                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    picturePath = c.getString(columnIndex);
                    c.close();
                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));

                    img_profile.setImageBitmap(thumbnail);
            } else {
                img_profile.setBackgroundResource(R.drawable.defaultImage);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM