在去另一个活动后消失,但显示上传到服务器Glide和凌空

问题描述 投票:1回答:1

我在我的应用中创建了两个用于照片上传的功能。第一个用于捕获图像,第二个用于从图库中选择图像。现在我有一个照片API作为URL。通过使用此API,我必须首先将图像上传到服务器,然后从服务器上传,它将通过应用程序提供。现在我可以在服务器上成功上传图片,在服务器端显示图片。但在app的imageview中没有显示该图像。每当我去另一个活动,然后回到图像活动时,imageview是空的。我使用共享首选项将图像保留在图像视图中,但这不起作用。

这是我的照片活动代码

    public class ViewProfileFragment extends Fragment implements
        View.OnClickListener{
    private static final int CODE_GALLERY_REQUEST =999 ;
    private static final int MY_CAMERA_REQUEST_CODE = 100;

    private ImageView image;

    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private String userChoosenTask;
    Bitmap bm;

    private String UPLOAD_URL = Constants.HTTP.PHOTO_URL;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_view_profile,
                container, false);
        .........
        image=(ImageView)rootView.findViewById(R.id.profile_pic);
        saveData();
        return rootView;
    }
    public void saveData(){
        Log.d( "----ViewProfile-Email", "mEmail" );
        GlobalClass globalClass = new GlobalClass();
        String mEmail = globalClass.getEmail_info();
        Realm profileRealm;
        profileRealm = Realm.getDefaultInstance();
        RealmResults<MyColleagueModel> results =
                profileRealm.where(MyColleagueModel.class).equalTo("mail",
                        mEmail).findAll();
        //fetching the data
        results.load();
        if (results.size() > 0) {
            ......
            SharedPreferences preferences =
                    PreferenceManager.getDefaultSharedPreferences(getActivity());
            String mImageUri = preferences.getString("image", null);
            if (mImageUri != null) {
                image.setImageURI(Uri.parse(mImageUri));
            } else {
                Glide.with( this )
                        .load(Constants.HTTP.PHOTO_URL+mail)
                        .thumbnail(0.5f)
                        .override(200,200)
                        .diskCacheStrategy( DiskCacheStrategy.ALL)
                        .into( image);
            }

        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[]
            permissions, int[] grantResults) {
        if(requestCode==CODE_GALLERY_REQUEST){
            if(grantResults.length>0 && grantResults[0]==
                    PackageManager.PERMISSION_GRANTED){
                galleryIntent();
            }
            else {
                Toast.makeText( getActivity().getApplicationContext(),"You
                        don't have permission to access gallery",Toast.LENGTH_LONG ).show();
            }
            return;
        }
        if(requestCode==MY_CAMERA_REQUEST_CODE){
            if(grantResults.length>0 && grantResults[0]==
                    PackageManager.PERMISSION_GRANTED){
                cameraIntent();
            }
            else {
                Toast.makeText( getActivity().getApplicationContext(),"You
                        don't have permission to access gallery",Toast.LENGTH_LONG ).show();
            }
            return;
        }
        super.onRequestPermissionsResult( requestCode, permissions,grantResults );
    }
    public void showDialog(){
//Create a new builder and get the layout.
        final AlertDialog.Builder builder = new
                AlertDialog.Builder(this.getActivity());
        .....
            }
        });
        alertListView.setOnItemClickListener(new

       AdapterView.OnItemClickListener() {
           @Override
              public void onItemClick(AdapterView<?> parent, View view,
                                                                                 int position, long id) {
// ListViekw Clicked item index
             if (position == 0) {
                 userChoosenTask ="Take Photo";
                 alert.dismiss();

                 if(isPermissionGrantedCamera()) {

                  cameraIntent();
                                                  }
                  }
                else if (position == 1){

                 userChoosenTask ="Choose from Library";

                 alert.dismiss();

                 if(isPermissionGrantedGallery()) {

                  galleryIntent();
                                     }
                  }
              }
         });
    }

      public boolean isPermissionGrantedGallery() {
        if (Build.VERSION.SDK_INT >= 23) {
            if
                 (getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v("TAG","Permission is granted");
                return true;
            } else {
                Log.v("TAG","Permission is revoked");
                ActivityCompat.requestPermissions(this.getActivity(), new
                        String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon
            installation
            Log.v("TAG","Permission is granted");
            return true;
        }
    }
    public boolean isPermissionGrantedCamera() {
        if (Build.VERSION.SDK_INT >= 23) {
            if
                    (getActivity().checkSelfPermission(android.Manifest.permission.CAMERA)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v("TAG","Permission is granted");
                return true;
            } else {
                Log.v("TAG","Permission is revoked");
                ActivityCompat.requestPermissions(this.getActivity(), new
                        String[]{Manifest.permission.CAMERA}, 0);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon
            installation
            Log.v("TAG","Permission is granted");
            return true;
        }
    }
    private void galleryIntent()
    {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "Select
                File"),SELECT_FILE);
    }
    public void cameraIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if
                (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
        {
            File cameraFolder;
            if
                    (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                cameraFolder = new
                        File(Environment.getExternalStorageDirectory(), "image/");
            } else {
                cameraFolder = getActivity().getCacheDir();
            }
            if (!cameraFolder.exists()) {
                cameraFolder.mkdirs();
            }
            String imageFileName = System.currentTimeMillis() + ".jpg";File photoFile = new File(cameraFolder + imageFileName);
            currentPhotoPath = photoFile.getAbsolutePath();
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_CAMERA);
            }
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_FILE && data!=null){
                onSelectFromGalleryResult(data);
            }
            else if (requestCode == REQUEST_CAMERA ) {
                if(!TextUtils.isEmpty(currentPhotoPath)) {
                    try {
                        galleryAddPic();
                        onCaptureImageResult();
                    }
                    catch (Exception e){
                    }
                }
            }
        }
    }
    private void galleryAddPic() {
        Intent mediaScanIntent = new
                Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(currentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.getActivity().sendBroadcast(mediaScanIntent);
    }
    private void onCaptureImageResult() {
        Bitmap bitmap = getBitmapFromPath(currentPhotoPath, 200, 200);
        image.setImageBitmap(bitmap);
        compressBitMap(bitmap);
    }
    private void onSelectFromGalleryResult(Intent data) {
        Uri uri = data.getData();
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContext().getContentResolver().query(uri,
                projection, null, null, null);
        if (cursor != null) {
            int column_index =
                    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            currentPhotoPath = cursor.getString(column_index);
            cursor.close();
        } else {
            currentPhotoPath = uri.getPath();
        }// Saves image URI as string to Default Shared Preferences

    SharedPreferences preferences =
            PreferenceManager.getDefaultSharedPreferences(getActivity());
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("image", String.valueOf(uri));
    editor.commit();

    try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
        image.setImageBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
    bm = BitmapFactory.decodeFile(currentPhotoPath);
    compressBitMap(bm);
    }
    private void compressBitMap(Bitmap bitmap) {
        ImageConversion imageConversion = new ImageConversion();
        byte[] bytesArray;
        int maxSize = 10 * 1024;
        int imageMaxQuality = 50;
        int imageMinQuality = 5;
        bytesArray = imageConversion.convertBitmapToByteArray(bitmap,
                imageMaxQuality, imageMinQuality, maxSize);
        File destination = new
                File(getContext().getApplicationContext().getFilesDir(),
                System.currentTimeMillis() + ".jpg");
        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytesArray);
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        currentPhotoPath = destination.getPath();
        uploadImage(bytesArray);
    }

    private void uploadImage(final byte[] bytesArray){
       .....
    }

}
android image sharedpreferences android-imageview android-glide
1个回答
0
投票

请不要使用

image.setImageURI(uri);
image.invalidate();

请使用以下代码而不是:

try {
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
    image.setImageBitmap(bitmap);
} catch (IOException e) {
    e.printStackTrace();
}
© www.soinside.com 2019 - 2024. All rights reserved.