Image selected not displaying in mainActivity

2019-03-06 14:33发布

问题:

Why the image selected did not display in Claims.java? Have I missed anything ?

mainfest.xml

  <uses-permission android:name="android.permission.CAMERA" />
        <uses-feature android:name="android.hardware.camera" />
        <uses-feature android:name="android.hardware.camera.autofocus" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-sdk
            android:minSdkVersion="7"
            android:targetSdkVersion="16" />

camera_main.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:fillViewport="false">


<AbsoluteLayout
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="5dp" >

    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select Picture"
        android:id="@+id/btnSelectPhoto"
        android:layout_x="111dp"
        android:layout_y="305dp" />

    <Button
        android:layout_width="121dp"
        android:layout_height="61dp"
        android:text="Submit"
        android:id="@+id/button8"
        android:layout_x="131dp"
        android:layout_y="681dp" />

    <ImageView
        android:layout_width="285dp"
        android:layout_height="285dp"
        android:id="@+id/imageView"
        android:layout_x="43dp"
        android:layout_y="376dp"
        android:contentDescription="i" />

</AbsoluteLayout>

</ScrollView>

Claims.java

public class Claims extends Fragment {

ImageView viewImage;
Button b;

private String selectedImagePath;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View claims = inflater.inflate(R.layout.camera_main, container, false);
    b = (Button) claims.findViewById(R.id.btnSelectPhoto);
    viewImage=(ImageView)claims.findViewById(R.id.imageView);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
    return claims;
}


private void selectImage() {

    final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};

    AlertDialog.Builder builder = new AlertDialog.Builder(Claims.this.getActivity());
    builder.setTitle("Add Photo!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(getActivity().getApplicationContext(), " mounted ", Toast.LENGTH_LONG).show();

                }
                startActivityForResult(intent, 1);
            } else if (options[item].equals("Choose from Gallery")) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);

            } else if (options[item].equals("Cancel")) {
dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            if(f != null){
                Toast.makeText(getActivity().getApplicationContext(), " not null ", Toast.LENGTH_LONG).show();
            }
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);

                viewImage.setImageBitmap(bitmap);

                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {

            Uri selectedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            if(picturePath.startsWith("/")) picturePath = picturePath.substring(1);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            Drawable d = new BitmapDrawable(thumbnail);
            viewImage.setBackground(d);
        }
    }
}

When I select the image, nothing display on imageviewe. But if I capture Image from camera, the image can display...WHy?

10-22 14:28:11.128    7451-7451/com.example.project.project E/ViewRootImpl﹕ sendUserActionEvent() mView == null
10-22 14:28:15.228    7451-7451/com.example.project.project E/BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException: /https:/lh3.googleusercontent.com/-ZiYOXTFTKqQ/URcxPqvEtTI/AAAAAAAAAJw/GN893VrnxGw/I/PANO_20130210_133321.jpg: open failed: ENOENT (No such file or directory)

What does this mean? How can I fix this? And how can I know the sdk version in android studio? Please help me.... Thanks

回答1:

As I can see in your logcat your path is wrong.

There's an extra "/" at the beginning.

You can try:

if(picturePath.startsWith("/")) picturePath = picturePath.substring(1);


回答2:

I faced this before and I just did like this

else if (requestCode == 2) {
                Uri selectedImage = data.getData();
               viewImage.setImageURI(selectedImage);

and it works! Hope it helps you too...Good luck



回答3:

Hi Iam also facing the same problem and I did like this...

String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getActivity().getContentResolver().query(data.getData(),
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

            viewImage.setImageBitmap(BitmapFactory
                    .decodeFile(imgDecodableString));

you just replace the code in else if(requestCode == 2) with the above mentioned code

Hope this will solve your problem