android–Recycler View中的OutOfMemory错误

android–Recycler View中的OutOfMemory错误,第1张

概述我正在创建一个简单的应用程序,它具有交错的布局,交错布局使用Volley库在PHP脚本的帮助下从服务器加载数据当我点击RecyclerView中的项目时,我的应用程序包含以下错误日志.此外,当我查看内存日志时,应用程序在将数据从服务器加载到recyclerView时使用了大量内存记录//在应用程序

我正在创建一个简单的应用程序,它具有交错的布局,交错布局使用Volley库在PHP脚本的帮助下从服务器加载数据当我点击RecyclerVIEw中的项目时,我的应用程序包含以下错误日志.

此外,当我查看内存日志时,应用程序在将数据从服务器加载到recyclerVIEw时使用了大量内存

记录//在应用程序启动时

I/Choreographer: Skipped 189 frames!  The application may be doing too much work on its main thread.I/art: Background partial concurrent mark sweep GC freed 3797(174KB) AllocSpace objects, 1(36KB) LOS objects, 6% free, 56MB/60MB, paused 19.976ms total 90.718ms

错误记录//单击RecyclerVIEw中的项目后

I/art: Alloc sticky concurrent mark sweep GC freed 10628(425KB) AllocSpace objects, 5(562KB) LOS objects, 2% free, 59MB/60MB, paused 476us total 7.071msI/art: Alloc partial concurrent mark sweep GC freed 928(67KB) AllocSpace objects, 1(16KB) LOS objects, 6% free, 58MB/62MB, paused 647us total 37.510msI/art: Alloc concurrent mark sweep GC freed 241(23KB) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 574us total 49.041msI/art: Forcing collection of SoftReferences for 21MB allocationI/art: Alloc concurrent mark sweep GC freed 13(472B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 429us total 16.959msE/art: Throwing OutOfMemoryError "Failed to allocate a 22400012 byte allocation with 4194304 free bytes and 5MB until OOM"I/art: Alloc sticky concurrent mark sweep GC freed 5(608B) AllocSpace objects, 0(0B) LOS objects, 3% free, 58MB/60MB, paused 509us total 8.143msI/art: Alloc partial concurrent mark sweep GC freed 17(480B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 5.517ms total 17.409msI/art: Alloc concurrent mark sweep GC freed 14(448B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 1.077ms total 107.298msI/art: Forcing collection of SoftReferences for 21MB allocationI/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB, paused 620us total 36.488msE/art: Throwing OutOfMemoryError "Failed to allocate a 22400012 byte allocation with 4194304 free bytes and 5MB until OOM"D/skia: --- allocation Failed for scaled bitmapD/AndroIDRuntime: Shutting down VMFATAL EXCEPTION: mainProcess: com.trueblueoperator.swachhapp, PID: 25499  java.lang.OutOfMemoryError: Failed to allocate a 22400012 byte allocation with 4194304 free bytes and 5MB until OOM  at dalvik.system.vmruntime.newNonMovableArray(Native Method)  at androID.graphics.BitmapFactory.nativeDecodeAsset(Native Method)  at androID.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)  at androID.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)  at androID.graphics.drawable.Drawable.createFromresourceStream(Drawable.java:988)  at androID.content.res.Resources.loadDrawableForcookie(Resources.java:2474)  at androID.content.res.Resources.loadDrawable(Resources.java:2381)  at androID.content.res.TypedArray.getDrawable(TypedArray.java:749)  at androID.Widget.ImageVIEw.<init>(ImageVIEw.java:146)  at androID.Widget.ImageVIEw.<init>(ImageVIEw.java:135)  at androID.support.v7.Widget.AppCompatimageVIEw.<init>(AppCompatimageVIEw.java:58)  at androID.support.v7.Widget.AppCompatimageVIEw.<init>(AppCompatimageVIEw.java:54)  at androID.support.v7.app.AppCompatVIEwInflater.createVIEw(AppCompatVIEwInflater.java:95)  at androID.support.v7.app.AppCompatDelegateImplV7.createVIEw(AppCompatDelegateImplV7.java:938)  at androID.support.v7.app.AppCompatDelegateImplV7.onCreateVIEw(AppCompatDelegateImplV7.java:992)  at androID.support.v4.vIEw.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateVIEw(LayoutInflaterCompatHC.java:44)  at androID.vIEw.LayoutInflater.createVIEwFromTag(LayoutInflater.java:725)  at androID.vIEw.LayoutInflater.rInflate(LayoutInflater.java:806)  at androID.vIEw.LayoutInflater.rInflate(LayoutInflater.java:809)  at androID.vIEw.LayoutInflater.rInflate(LayoutInflater.java:809)  at androID.vIEw.LayoutInflater.inflate(LayoutInflater.java:504)  at androID.vIEw.LayoutInflater.inflate(LayoutInflater.java:414)  at androID.vIEw.LayoutInflater.inflate(LayoutInflater.java:365)  at androID.support.v7.app.AppCompatDelegateImplV7.setContentVIEw(AppCompatDelegateImplV7.java:256)  at androID.support.v7.app.AppCompatActivity.setContentVIEw(AppCompatActivity.java:109)  at com.trueblueoperator.swachhapp.StoryDetailFragment.onCreate(StoryDetailFragment.java:45)  at androID.app.Activity.performCreate(Activity.java:5990)  at androID.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)  at androID.app.ActivityThread.performlaunchActivity(ActivityThread.java:2278)  at androID.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  at androID.app.ActivityThread.access0(ActivityThread.java:151)  at androID.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  at androID.os.Handler.dispatchMessage(Handler.java:102)  at androID.os.Looper.loop(Looper.java:135)  at androID.app.ActivityThread.main(ActivityThread.java:5254)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.androID.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  at com.androID.internal.os.ZygoteInit.main(ZygoteInit.java:698)

这是我的Code for Fragment类,其中包含Recycler VIEw

FragmetnAllStory.java文件

public class FragmentAllStory extends Fragment implements SwipeRefreshLayout.OnRefreshListener{// implements RecyclerVIEw.OnScrollchangelistener {//Creating a List of superheroesprivate List<AllStoryData> allStoryDataList;//Volley Request Queueprivate RequestQueue requestQueue;private Progressbar progressbar;//The request counter to send ?page=1, ?page=2  requestsprivate int requestCount = 1;private RecyclerVIEw recyclerVIEw;private SwipeRefreshLayout swipeRefreshLayout;private RecyclerVIEw.Adapter adapter;@OverrIDepublic voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setRetainInstance(true);}@Nullable@OverrIDepublic VIEw onCreateVIEw(LayoutInflater inflater, VIEwGroup container, Bundle savedInstanceState) {    requestCount = 1;    VIEw v = inflater.inflate(R.layout.fragment_all_story, container, false);    progressbar = (Progressbar) v.findVIEwByID(R.ID.progress_bar);    swipeRefreshLayout = (SwipeRefreshLayout) v.findVIEwByID(R.ID.swipeRefreshLayout);    swipeRefreshLayout.setonRefreshListener(this);    recyclerVIEw = (RecyclerVIEw) v.findVIEwByID(R.ID.recycler_vIEw2);//new RecyclerVIEw(getActivity());    if(getResources().getConfiguration().orIEntation == Configuration.ORIENTATION_PORTRAIT) {        recyclerVIEw.setLayoutManager(new StaggeredGrIDLayoutManager(2, 1));    }    else {        recyclerVIEw.setLayoutManager(new StaggeredGrIDLayoutManager(3, 1));    }    allStoryDataList = new ArrayList<>();    requestQueue = Volley.newRequestQueue(getContext());    //getData();    recyclerVIEw.addOnScrollListener(new OnScrollListener() {        @OverrIDe        public voID onScrollStateChanged(RecyclerVIEw recyclerVIEw, int newState) {            super.onScrollStateChanged(recyclerVIEw, newState);        }        @OverrIDe        public voID onScrolled(RecyclerVIEw recyclerVIEw, int dx, int dy) {            super.onScrolled(recyclerVIEw, dx, dy);            if(isLastItemdisplaying(recyclerVIEw))            {                getData();            }        }    });    adapter = new AllStoryAdapter(allStoryDataList, getActivity());    recyclerVIEw.setAdapter(adapter);    return v;}//Request to get Json from server we are passing an integer here//This integer will used to specify the page number for the request ?page = requestcount//This method would return a JsonArrayRequest that will be added to the request queue    private JsonArrayRequest getDataFromServer(int requestCount) {    //displaying Progressbar    progressbar.setVisibility(VIEw.VISIBLE);    //JsonArrayRequest of volley    JsonArrayRequest JsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),            new Response.Listener<JsONArray>() {                @OverrIDe                public voID onResponse(JsONArray response) {                    //Calling method parseData to parse the Json response                    parseData(response);                    //HIDing the progressbar                    progressbar.setVisibility(VIEw.GONE);                }            },            new Response.ErrorListener() {                @OverrIDe                public voID one rrorResponse(VolleyError error) {                    progressbar.setVisibility(VIEw.GONE);                    //If an error occurs that means end of the List has reached                    Toast.makeText(getContext(), "No More Items Available", Toast.LENGTH_SHORT).show();                }            });    //Returning the request    return JsonArrayRequest;}@OverrIDepublic voID onResume() {    super.onResume();    requestCount =1;    allStoryDataList.clear();    getData();}//This method will get data from the web APIprivate voID getData() {    //Adding the method to the queue by calling the method getDataFromServer    requestQueue.add(getDataFromServer(requestCount));    //Incrementing the request counter    requestCount++;    swipeRefreshLayout.setRefreshing(false);}//This method will parse Json dataprivate voID parseData(JsONArray array) {    for (int i = 0; i < array.length(); i++) {        //Creating the superhero object        AllStoryData allStoryData = new AllStoryData();        JsONObject Json = null;        try {            //Getting Json            Json = array.getJsONObject(i);            //Adding data to the superhero object            allStoryData.setimageUrl(Json.getString(Config.TAG_IMAGE_URL));            allStoryData.setname(Json.getString(Config.TAG_name));            allStoryData.setPublisher(Json.getString(Config.TAG_PUBliSHER));        } catch (JsONException e) {            e.printstacktrace();        }        //Adding the superhero object to the List        allStoryDataList.add(allStoryData);        Log.d("ListSuper", "" + allStoryDataList);    }    //Notifying the adapter that data has been added or changed    adapter.notifyDataSetChanged();}//This method would check that the recyclervIEw scroll has reached the bottom or notprivate boolean isLastItemdisplaying(RecyclerVIEw recyclerVIEw) {    int[] info = new int[3];    if (recyclerVIEw.getAdapter().getItemCount() != 0) {        ((StaggeredGrIDLayoutManager) recyclerVIEw.getLayoutManager()).findLastCompletelyVisibleItempositions(info);        Log.d("info", "" + info[0] + " " + info[1]);        if (info[0] == recyclerVIEw.getAdapter().getItemCount() - 1 || info[1] == recyclerVIEw.getAdapter().getItemCount() - 1 || info[2] == recyclerVIEw.getAdapter().getItemCount() - 1)            return true;    }    return false;}@OverrIDepublic voID onRefresh() { requestCount =1;    allStoryDataList.clear();    getData();}}

StoryDe​​tailFragment.java文件

public class StoryDetailFragment extends AppCompatActivity implements VIEw.OnClickListener, AppbarLayout.OnOffsetChangedListener {TextVIEw textVIEw;TextVIEw like;ImageVIEw imageVIEw;String requestString;RequestParams params = new RequestParams();@OverrIDepublic voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.fragment_story_detail); // error line 45    // Intent Message sent from broadcast Receiver    requestString = getIntent().getStringExtra("heading");    Toolbar toolbar = (Toolbar) findVIEwByID(R.ID.toolbar);    setSupportActionbar(toolbar);    Actionbar actionbar = getSupportActionbar();    actionbar.setdisplayHomeAsUpEnabled(true);    imageVIEw = (ImageVIEw) findVIEwByID(R.ID.story_image);    like = (TextVIEw) findVIEwByID(R.ID.likes);    if (requestString != null) {        textVIEw = (TextVIEw) findVIEwByID(R.ID.story_detail_message);        textVIEw.setText(requestString);    }    AppbarLayout appbarLayout = (AppbarLayout) findVIEwByID(R.ID.app_bar);    appbarLayout.addOnOffsetChangedListener(this);    floatingActionbutton fab1 = (floatingActionbutton) findVIEwByID(R.ID.fab1);    floatingActionbutton fab2 = (floatingActionbutton) findVIEwByID(R.ID.fab2);    fab1.setonClickListener(this);    fab2.setonClickListener(this);    getData();}private voID getData() {    params.put("heading", "" + requestString);    // Make RESTful webservice call using AsynchttpClIEnt object    AsynchttpClIEnt clIEnt = new AsynchttpClIEnt();    clIEnt.get(Config.DETAIL_URL, params,            new JsonhttpResponseHandler() {                // When the response returned by REST has http                // response code '200'                @OverrIDe                public voID onSuccess(JsONArray response) {                    Log.d("result",""+response);                    try {                        JsONObject result = response.getJsONObject(0);                        textVIEw.setText((CharSequence) result.get("detailstory"));                        like.setText((CharSequence) result.get("likes"));                        String res = (String) result.get("images");                        //URL url = new URL(res);                        //Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getinputStream());                        new DownloadImagesTask().execute(res);                        Log.d("result",""+res);                    } catch (JsONException e) {                        e.printstacktrace();                    }                    //super.onSuccess(response);                }                // When the response returned by REST has http                // response code other than '200' such as '404',                // '500' or '403' etc                @OverrIDe                public voID onFailure(int statusCode, Throwable error, JsONArray errorResponse) {                    // When http response code is '404'                    if (statusCode == 404) {                        Toast.makeText(StoryDetailFragment.this,                                "Requested resource not found",                                Toast.LENGTH_LONG).show();                    }                    // When http response code is '500'                    else if (statusCode == 500) {                        Toast.makeText(StoryDetailFragment.this,                                "Something went wrong at server end",                                Toast.LENGTH_LONG).show();                    }                    // When http response code other than 404, 500                    else {                        Toast.makeText(                                StoryDetailFragment.this,                                "Unexpected Error occcured! [Most common Error: Device might "                                        + "not be connected to Internet or Remote Server is not up and running], check for other errors as well",                                Toast.LENGTH_LONG).show();                    }                }            });}@OverrIDepublic voID onBackpressed() {    super.onBackpressed();    finish();}@OverrIDepublic boolean onoptionsItemSelected(MenuItem item) {    int ID = item.getItemID();    if (ID == androID.R.ID.home) {        onBackpressed();    }    return super.onoptionsItemSelected(item);}@OverrIDepublic voID onClick(VIEw v) {    switch (v.getID()) {        case R.ID.fab1:            // Code for button like click            break;        case R.ID.fab2:            // Code for saving the articles            break;    }}@OverrIDepublic voID onOffsetChanged(AppbarLayout appbarLayout, int verticalOffset) {    if (Math.abs(verticalOffset) <= appbarLayout.getTotalScrollRange() - 120) {        like.setVisibility(TextVIEw.VISIBLE);    } else {        like.setVisibility(TextVIEw.GONE);    }}public class DownloadImagesTask extends AsyncTask<String, VoID, Bitmap> {    @OverrIDe    protected Bitmap doInBackground(String... params) {        return download_Image(params[0]);    }    @OverrIDe    protected voID onPostExecute(Bitmap result) {        imageVIEw.setimageBitmap(result);    }    private Bitmap download_Image(String url) {        Bitmap bmp = null;        try {            URL ulrn = new URL(url);            httpURLConnection con = (httpURLConnection) ulrn.openConnection();            inputStream is = con.getinputStream();            bmp = BitmapFactory.decodeStream(is);            if (null != bmp)                return bmp;        } catch (Exception e) {        }        return bmp;    }}}

XML文件fragment_story_detail.xml

<androID.support.design.Widget.CoordinatorLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"xmlns:app="http://schemas.androID.com/apk/res-auto"xmlns:tools="http://schemas.androID.com/tools"androID:layout_wIDth="match_parent"androID:layout_height="match_parent"androID:fitsSystemwindows="true"tools:context="com.trueblueoperator.samplescrolling.ScrollingActivity"><androID.support.design.Widget.AppbarLayout    androID:ID="@+ID/app_bar"    androID:layout_wIDth="match_parent"    androID:layout_height="192dp"    androID:fitsSystemwindows="true"    androID:theme="@style/Apptheme.AppbarOverlay">    <androID.support.design.Widget.CollapsingToolbarLayout        androID:ID="@+ID/toolbar_layout"        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"        androID:fitsSystemwindows="true"        app:contentScrim="?attr/colorPrimary"        app:layout_scrollFlags="scroll|exitUntilCollapsed">        <ImageVIEw            androID:ID="@+ID/story_image"            androID:layout_wIDth="match_parent"            androID:layout_height="192dp"            androID:scaleType="centerCrop"            androID:src="@drawable/image"            app:layout_collapseMode="parallax" />        <androID.support.v7.Widget.Toolbar            androID:ID="@+ID/toolbar"            androID:layout_wIDth="match_parent"            androID:layout_height="?attr/actionbarSize"            app:layout_collapseMode="pin"            app:popuptheme="@style/Apptheme.PopupOverlay" />    </androID.support.design.Widget.CollapsingToolbarLayout></androID.support.design.Widget.AppbarLayout><include layout="@layout/content_scrolling"/><TextVIEw    androID:ID="@+ID/likes"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:paddingleft="5dp"    androID:paddingBottom="5dp"    androID:paddingtop="5dp"    androID:paddingRight="70dp"    androID:layout_marginRight="10dp"    androID:textSize="20dp"    androID:background="@drawable/rounded_corner"    androID:text="100"    app:layout_anchor="@ID/app_bar"    app:layout_anchorGravity="right|bottom"    /><androID.support.design.Widget.floatingActionbutton    androID:ID="@+ID/fab1"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:src="@drawable/like"    app:layout_anchor="@ID/app_bar"    app:layout_anchorGravity="right|bottom" /><androID.support.design.Widget.floatingActionbutton    androID:ID="@+ID/fab2"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:src="@drawable/like"    androID:layout_gravity="bottom|right" /></androID.support.design.Widget.CoordinatorLayout>

解决方法:

什么是你的logcat投掷

E/art: Throwing OutOfMemoryError “Failed to allocate a 22400012 byte
allocation with 4194304 free bytes and 5MB until OOM”I/art: Alloc
14(448B) AllocSpace objects, 0(0B) LOS objects, 6% free, 58MB/62MB,
paused 1.077ms total 107.298ms I/art: Forcing collection of
SoftReferences for 21MB allocation I/art: Alloc concurrent mark sweep
GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 6% free,
58MB/62MB, paused 620us total 36.488ms E/art: Throwing
OutOfMemoryError “Failed to allocate a 22400012 byte allocation with
4194304 free bytes and 5MB until OOM” D/skia: — allocation Failed
for scaled bitmap

当应用程序尝试将更多数据添加到堆空间区域时,将触发Java堆空间错误,但没有足够的空间.

请减少Image Sizes&增加VM堆大小(AVD).

每个AndroID驱动的设备都有不同的系统可用RAM,因此为每个应用程序提供不同的堆限制.您可以调用getMemoryClass()来估算应用程序的可用堆(以兆字节为单位).如果您的应用尝试分配的内存超过此处可用内存,则会收到OutOfMemoryError.

忠告

使用androID:largeHeap =“true”不是一个好主意.

请阅读

> Managing Your App’s Memory
> Strange out of memory issue while loading an image to a Bitmap object

总结

以上是内存溢出为你收集整理的android – Recycler View中的OutOfMemory错误全部内容,希望文章能够帮你解决android – Recycler View中的OutOfMemory错误所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1108155.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存