2017-09-20 2 views
1

내 앱에서 사진을 업로드하는 두 가지 기능을 만들었습니다. 첫 번째는 캡처 이미지 용이고 두 번째 이미지는 갤러리에서 선택한 이미지 용입니다. 이제 URL로 사진 API가 있습니다. 이 API를 사용하여 서버에 이미지를 업로드하고 서버에서 이미지를 사용할 수있게됩니다. 이제 성공적으로 서버에 그림을 업로드 할 수 있으며 서버 쪽에서 그림이 표시됩니다. 그러나 앱의 이미지 뷰에는 이미지가 표시되지 않습니다. 다른 활동으로 가서 이미지 활동으로 돌아올 때마다 이미지 뷰는 비어 있습니다. 공유보기를 사용하여 이미지를 이미지보기로 유지했지만 작동하지 않습니다. 여기 다른 활동으로 이동했지만 서버에 업로드가 표시되면 이미지가 사라집니다. 활과 발리

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){ 
     ..... 
    } 

} 

답변

0

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

가의 아래 대신에이 코드를 사용하시기 바랍니다 사용하지 마십시오 사진 활동에 대한 내 코드입니다 : 난 그냥 함께 노력

try { 
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri); 
    image.setImageBitmap(bitmap); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

당신의 코드,하지만 여전히 동일한 결과, 다른 활동에 갈 때마다 이미지 dissaperas – tamrezh21

+0

나는 여전히 내 코드를 편집했습니다. 나 – tamrezh21

+0

당신은 올바른 이미지 URL을 얻고 있습니까? 브라우저에서 해당 이미지를 클릭하십시오. –

관련 문제