图库视图中不显示图片

时间:2016-04-05 04:45:26

标签: android image android-activity android-gallery

这是我的两项活动。我试图在其他活动的图像视图中显示图像。对于相机它的工作正常但是对于图库它不在图像视图中显示。即在图像视图中选择图像后,它似乎是空白的。我在SO上看到了很多答案但是它们都不适用于我。

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author aditya
 */
public class UploadFinding extends BaseActivity {


    // LogCat tag
    private static final String TAG = UploadFinding.class.getSimpleName();
    Bitmap b;

    public static final String IMAGE_URL = "imageURL";
    // Camera activity request codes
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 1337;
    String mCurrentPhotoPath;
    String imgDecodableString;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;



    protected static final int RESULT_LOAD_IMAGE = 1;
    Button capture_photo, capture_video;

    private Uri mFileUri;
    TextView textview1,textview2,textview3;

    private final Context mContext = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * Adding our layout to parent class frame layout.
         */
        getLayoutInflater().inflate(R.layout.upload_finding_layout, frameLayout);



        //for Design
        textview1 = (TextView)findViewById(R.id.textView1);
        Typeface face1= Typeface.createFromAsset(getAssets(), "fonts/AlexBrush-Regular.ttf");
        textview1.setTypeface(face1);

        textview2 = (TextView)findViewById(R.id.textView2);
        Typeface face2= Typeface.createFromAsset(getAssets(), "fonts/AlexBrush-Regular.ttf");
        textview2.setTypeface(face2);

        textview3 = (TextView)findViewById(R.id.textView3);
        Typeface face3= Typeface.createFromAsset(getAssets(), "fonts/AlexBrush-Regular.ttf");
        textview3.setTypeface(face3);



        capture_photo = (Button) findViewById(R.id.capture_photo);
        capture_video = (Button) findViewById(R.id.capture_video);


        capture_photo.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(UploadFinding.this);
                alertDialogBuilder.setTitle("Capture");
                alertDialogBuilder.setPositiveButton("From Camera",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent cameraIntent = new Intent(
                                        MediaStore.ACTION_IMAGE_CAPTURE);
                                mFileUri = getOutputMediaFileUri(1);
                                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
                                startActivityForResult(cameraIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
                            }

                        })
                        .setNegativeButton("From Gallery", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent i = new Intent(Intent.ACTION_PICK,
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                mFileUri = getOutputMediaFileUri(1);
                                i.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
                                startActivityForResult(i, RESULT_LOAD_IMAGE);
                            }
                        });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();

            }

        });


//End Btn_Click


        // For Camera

        capture_video.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(UploadFinding.this);
                alertDialogBuilder.setTitle("Capture");
                alertDialogBuilder.setPositiveButton("From Camera",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
//
                                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
                                cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 5);


                                mFileUri = getOutputMediaFileUri(2);

                                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
                                cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
                                startActivityForResult(cameraIntent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
                            }
                        })
                        .setNegativeButton("From Gallery", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent i = new Intent(Intent.ACTION_PICK,
                                        MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                                 i.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
                                startActivityForResult(i, RESULT_LOAD_IMAGE);
                                finish();
                            }
                        });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }

        });

        /**
         * Setting title and itemChecked
         */
        mDrawerList.setItemChecked(position, true);
        setTitle(listArray[position]);

    }


    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putParcelable("file_uri", mFileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        mFileUri = savedInstanceState.getParcelable("file_uri");
    }

//
//
    //multipart

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {


                // successfully captured the image
                // launching upload activity
                launchUploadActivity(true);


            } else if (resultCode == RESULT_CANCELED) {

                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();

            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }

        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // video successfully recorded
                // launching upload activity
                launchUploadActivity1(true);

            } else if (resultCode == RESULT_CANCELED) {

                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();

            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }

        if(requestCode==RESULT_LOAD_IMAGE){
            if (resultCode == RESULT_OK) {

                launchUploadActivity2(true);
            }
        }
//        {
    }


    private void launchUploadActivity(boolean isImage) {
        Intent i = new Intent(UploadFinding.this, Finding_Preview_Image.class);
        i.putExtra("filePath", mFileUri.getPath());
        i.putExtra("isImage", isImage);
        startActivity(i);
    }

    private void launchUploadActivity1(boolean isImage) {
        Intent i = new Intent(UploadFinding.this, Finding_preview_video.class);
        i.putExtra("filePath", mFileUri.getPath());
        i.putExtra("isImage", isImage);
        startActivity(i);
    }

    private void launchUploadActivity2(boolean isImage) {
        Intent i = new Intent(UploadFinding.this, Finding_Preview_Image.class);
        i.putExtra("filePath", mFileUri.getPath());
        i.putExtra("isImage", isImage);
        startActivity(i);
    }

    private Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    // Return image / video
    private static File getOutputMediaFile(int type) {
        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                Config.IMAGE_DIRECTORY_NAME);
//        // Save a file: path for use with ACTION_VIEW intents
//        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
//        return image;
        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "Oops! Failed create "
                        + Config.IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        }

        else {
            return null;
        }

        return mediaFile;

    }
}

下一个活动

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;

public class Finding_Preview_Image extends BaseActivity {

    private Button finding_upload_button;

    // private ImageView photo;
// multipart
// LogCat tag
    private static final String TAG = UploadFinding.class.getSimpleName();

    private ProgressBar progressBar;
    private String filePath = null;
    // private TextView txtPercentage;
    private ImageView photo;
    private EditText fullname;
    private VideoView vidPreview;
    private Button Finding_upload_button;
    long totalSize = 0;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLayoutInflater().inflate(R.layout.finding__preview_image, frameLayout);

        finding_upload_button = (Button) findViewById(R.id.finding_upload_button);
        photo = (ImageView) findViewById(R.id.find_Image);
        fullname = (EditText) findViewById(R.id.editText);
        EditText fullname = (EditText) findViewById(R.id.editText);
        EditText location = (EditText) findViewById(R.id.editText2);
        EditText description = (EditText) findViewById(R.id.editText3);
        ImageView photo = (ImageView) findViewById(R.id.find_Image);
        //multipart
        // txtPercentage = (TextView) findViewById(R.id.txtPercentage);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        // vidPreview = (VideoView) findViewById(R.id.videoPreview);


        // Receiving the data from previous activity
        Intent i = getIntent();

        // image or video path that is captured in previous activity
        filePath = i.getStringExtra("filePath");

        // boolean flag to identify the media type, image or video
        boolean isImage = i.getBooleanExtra("isImage", true);

        if (filePath != null) {
            // Displaying the image or video on the screen
            Log.i("UploadApp", "file path is null");
            previewMedia(isImage);
        } else {
            Toast.makeText(getApplicationContext(),
                    "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
        }

        finding_upload_button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // uploading the file to server
                new UploadFileToServer().execute();
            }
        });


    }
//
    //Displaying captured image/video on the screen

    private void previewMedia(boolean isImage) {


        // Checking whether captured media is image or video
        if (isImage) {
            photo.setVisibility(View.VISIBLE);
            // vidPreview.setVisibility(View.GONE);
            // bimatp factory
            BitmapFactory.Options options = new BitmapFactory.Options();


            // down sizing image as it throws OutOfMemory Exception for larger
            // images
            options.inSampleSize = 88;


            final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
            options.inJustDecodeBounds = true;

            photo.setImageBitmap(bitmap);
        }

        //else {
//            photo.setVisibility(View.GONE);
//            vidPreview.setVisibility(View.VISIBLE);
//            vidPreview.setVideoPath(filePath);
//            // start playing
//            vidPreview.start();
//        }
    }

    /**
     * Uploading the file to server
     * */
    private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
        @Override
        protected void onPreExecute() {
            // setting progress bar to zero
            progressBar.setProgress(0);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            // Making progress bar visible
            progressBar.setVisibility(View.VISIBLE);

            // updating progress bar value
            progressBar.setProgress(progress[0]);

            // updating percentage value
            //   txtPercentage.setText(String.valueOf(progress[0]) + "%");
        }

        @Override
        protected String doInBackground(Void... params) {
            return uploadFile();
        }

        @SuppressWarnings("deprecation")
        private String uploadFile() {
            String responseString = null;

            try {

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);



                Log.i("UploadApp", "upload url: " + Config.FILE_UPLOAD_URL);


                AndroidMultiPartEntity entity;
                entity = new AndroidMultiPartEntity(
                        new AndroidMultiPartEntity.ProgressListener() {

                            @Override
                            public void transferred(long num) {
                                publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });

                File sourceFile;
                sourceFile = new File(filePath);

                Log.i("UploadApp", "file path: " + filePath);

                // Adding file data to http body
                entity.addPart("image", new FileBody(sourceFile));
                entity.addPart("fullname", new StringBody(fullname.getText().toString()));


                totalSize = entity.getContentLength();
                httppost.setEntity(entity);

                // Making server call
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity r_entity = response.getEntity();

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    // Server response
                    responseString = EntityUtils.toString(r_entity);
                } else {
                    responseString = "Error occurred! Http Status Code: "
                            + statusCode;
                }

            } catch (ClientProtocolException e) {
                responseString = e.toString();
                Log.e("UploadApp", "exception: " + responseString);
            } catch (IOException e) {
                responseString = e.toString();
                Log.e("UploadApp", "exception: " + responseString);
            }

            return responseString;

        }

        @Override
        protected void onPostExecute(String result) {
            Log.e(TAG, "Response from server: " + result);

            // showing the server response in an alert dialog
            showAlert(result);

            super.onPostExecute(result);
        }

    }

    /**
     * Method to show alert dialog
     * */
    private void showAlert(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle("Response from Servers")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // do nothing
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }


}

1 个答案:

答案 0 :(得分:0)

将其用于图库中的图片

启动图库意图并选择图像

 Intent galleryIntent = new Intent();
 galleryIntent.setType("image/*");
 galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
 startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);   

然后进入活动结果

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
          if (resultCode == RESULT_OK) {
            if(requestCode==RESULT_LOAD_IMAGE){
                mFileUri=data.getData();
                launchUploadActivity2(true);
            }
        }
}

在launchUploadActivity2(true)

 String realPath=getPath(this, mFileUri) 
 i.putExtra("filePath", realPath);