Android: Reading Files - OutOfMemory Issue

I am creating an application that includes reading data from a file. The file is relatively large (1.8 MB) and read from the asynchronous stream in onCreate. The first time the application is launched, it loads just fine. However, if you click the Back button, and then download it again, it will run out of memory and crashes (OutOfMemory error throw).

How do I get it to use the smallest amount of memory and / or free this memory when it's done?

Code for reading files (executed in the doInBackground()async class method ):

public ArrayList<String> createDataList() {
    dataList = new ArrayList<String>();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(getAssets().open(
                    "text.txt")));
        String data;
        while ((data = br.readLine()) != null) {
            dataList.add(data);
        }                           
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close(); // stop reading
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    return dataList;
}

EDIT * Async Class:

private class loadData extends AsyncTask<Void, Void, ArrayList<String>> {

    @Override
    protected ArrayList<String> doInBackground(Void... arg0) {
        dataList = createDataList();
        return dataList;
    }

    protected void onPostExecute(ArrayList<String> result) {
        super.onPostExecute(result);
        // display first element in ArrayList in TextView as a test

    }

}

, ArrayList, . "" ArrayList, "", ArrayList (/ "", ).

, ?

**

Logcat:

enter image description here

, "", . ( ):

enter image description here

+1
3

-, , . ArrayList, , : ArrayList.clear() .

-, , ArrayList , hprof Eclipse MAT. , .

... , , , byte-to- char. UTF-8 ( , , ASCII), 2x UTF-16, char [] , String, ArrayList. , , 1.8MB.

- byte[], , , , . N, byte[] String . . , ( RandomAccessFile), .

0

android:largeHeap="true" , Android API-8. , , , , .

: android -

0

, .

, StringBuilder? , , .

0

Source: https://habr.com/ru/post/1764092/


All Articles