Ошибки при получении изображения из памяти Android Studio - PullRequest
0 голосов
/ 10 июня 2018

У меня есть фрагмент, который имеет возможность добавить изображение и дает возможность либо выбрать это фото из памяти, либо сделать снимок, и это изображение будет отображаться на этом фрагменте.Это работает, когда я делаю фотографию, однако, когда я выбираю фотографию из моей памяти, она вылетает.Не могли бы вы помочь

Код фрагмента XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/linearLayoutUpload">

        <ImageView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:id="@+id/imageViewAddPhoto"
            android:scaleType="center"
            android:background="@color/lightGrey"
            android:src="@drawable/ic_add_photo"/>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical"
            android:layout_marginTop="10dp">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:hint="@string/file_name"
                android:id="@+id/editTextFileName"
                android:inputType="text" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:hint="@string/date_of_use"
                android:id="@+id/editTextDate"
                android:inputType="date" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:hint="@string/grade"
                android:id="@+id/editTextGrade"
                android:inputType="number" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/Class"
                android:id="@+id/editTextClass"
                android:inputType="text" />


        </LinearLayout>



    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayoutUpload"
        android:id="@+id/relativeLayoutRating"
        android:layout_marginTop="20dp">


        <RatingBar
            android:layout_width="wrap_content"
            android:id="@+id/ratingBar"
            android:layout_centerHorizontal="true"
            android:layout_height="wrap_content"
            />


    </RelativeLayout>

    <LinearLayout
        android:layout_below="@+id/relativeLayoutRating"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <EditText
            android:id="@+id/reflection"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:hint="@string/reflection"
            android:inputType="textMultiLine"
            android:singleLine="false"
            android:gravity="start"
            android:maxLines="20"/>

        <Button
            android:layout_width="wrap_content"
            android:id="@+id/file"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="10dp"
            android:fontFamily="@font/capriola"
            android:background="@color/colorPrimaryDark"
            android:text="@string/file" />


    </LinearLayout>


    <ProgressBar
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/progressBar"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="120dp"
        android:visibility="invisible"/>


</RelativeLayout>

Код класса фрагмента

    public class FragmentUpload extends android.support.v4.app.Fragment 
    implements SelectPhotoDialog.OnPhotoSelectedListener {

    private static final String TAG = "FragmentUpload";


    @Override
    public void getImagePath(Uri imagePath) {
        Log.d(TAG, "getImagePath: setting the image to imageview");
        UniversalImageLoader.setImage(imagePath.toString(), mUploadImage);
        //assign to global variable
        mSelectedBitmap = null;
        mSelectedUri = imagePath;

    }

    @Override
    public void getImageBitmap(Bitmap bitmap) {
        Log.d(TAG, "getImageBitmap: setting the image to imageview");
        mUploadImage.setImageBitmap(bitmap);
        //assign to global variable
        mSelectedUri = null;
        mSelectedBitmap = bitmap;

    }



    public FragmentUpload(){

    }

    private ImageView mUploadImage;
    private EditText mFileName, mDateOfUse, mGrade, mClass, mReflection;
    private Button File;
    private ProgressBar mProgressBar;

    //vars
    private Bitmap mSelectedBitmap;
    private Uri  mSelectedUri;




    //tabs
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.upload_fragment, container, false);

        mUploadImage = view.findViewById(R.id.imageViewAddPhoto);
        mFileName = view.findViewById(R.id.editTextFileName);
        mDateOfUse = view.findViewById(R.id.editTextDate);
        mGrade = view.findViewById(R.id.editTextGrade);
        mClass = view.findViewById(R.id.editTextClass);
        mReflection = view.findViewById(R.id.reflection);
        File = view.findViewById(R.id.file);
        mProgressBar = view.findViewById(R.id.progressBar);

        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        init();

        return view;
    }

    private void init(){
        mUploadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: opening dialog to choose new photo");
                SelectPhotoDialog dialog = new SelectPhotoDialog();
                dialog.show(getFragmentManager(), getString(R.string.dialog_select_photo));
                dialog.setTargetFragment(FragmentUpload.this, 1);
            }
        });
    }

    private void resetFields(){
        UniversalImageLoader.setImage("", mUploadImage);
        mFileName.setText("");
        mDateOfUse.setText("");
        //check later and maybe change the set text
        mGrade.setText("");
        mClass.setText("");
        mReflection.setText("");

    }

    private void showProgressBar(){

        mProgressBar.setVisibility(View.VISIBLE);
    }

    private void hideProgressBar(){
        if(mProgressBar.getVisibility() == View.VISIBLE){
            mProgressBar.setVisibility(View.INVISIBLE);
        }
    }

    private boolean isEmpty(String string){
        return string.equals("");
    }


}

Код UniversalImageLoader

import android.content.Context;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;


public class UniversalImageLoader {

    private static final int defaultImage = R.drawable.ic_add_photo;
    private Context mContext;

    public UniversalImageLoader(Context context) {
        mContext = context;
    }

    public ImageLoaderConfiguration getConfig(){
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(defaultImage)
                .showImageForEmptyUri(defaultImage)
                .showImageOnFail(defaultImage)
                .considerExifParams(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisk(true).resetViewBeforeLoading(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .displayer(new FadeInBitmapDisplayer(300)).build();

        ImageLoaderConfiguration configuration = new 
        ImageLoaderConfiguration.Builder(mContext)
                .defaultDisplayImageOptions(defaultOptions)
                .memoryCache(new WeakMemoryCache())
                .diskCacheSize(100 * 1024 * 1024).build();

        return configuration;
    }


    public static void setImage(String imgURL, ImageView image){

        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.displayImage(imgURL, image);
    }
}

Это было в моих журналах

06-10 14:00:02.628 9237-9237/com.example.amyst.teacherfiles E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.amyst.teacherfiles, PID: 9237
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=66770, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:2107 flg=0x1 }} to activity {com.example.amyst.teacherfiles/com.example.amyst.teacherfiles.MyCabinetActivity}: java.lang.IllegalStateException: ImageLoader must be init with configuration before using
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4491)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4534)
        at android.app.ActivityThread.-wrap20(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1752)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6940)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
     Caused by: java.lang.IllegalStateException: ImageLoader must be init with configuration before using
        at com.nostra13.universalimageloader.core.ImageLoader.checkConfiguration(ImageLoader.java:613)
        at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:236)
        at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:209)
        at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:316)
        at com.example.amyst.teacherfiles.UniversalImageLoader.setImage(UniversalImageLoader.java:46)
        at com.example.amyst.teacherfiles.FragmentUpload.getImagePath(FragmentUpload.java:27)
        at com.example.amyst.teacherfiles.SelectPhotoDialog.onActivityResult(SelectPhotoDialog.java:71)
        at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:156)
        at android.app.Activity.dispatchActivityResult(Activity.java:7547)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4487)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4534) 
        at android.app.ActivityThread.-wrap20(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1752) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6940) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Я думаю, это проблема, но я не уверен, как это исправить

 Caused by: java.lang.IllegalStateException: ImageLoader must be init with configuration before using

1 Ответ

0 голосов
/ 11 июня 2018

Я понял это.Мне нужно было добавить

 UniversalImageLoader universalImageLoader = new UniversalImageLoader(getActivity());
    ImageLoader.getInstance().init(universalImageLoader.getConfig());

в функцию init ()

...