Armin.J
Armin.J

Reputation: 1

android app uses too much ram in database reading

I use this block of code to get messages from database. the for may loop more than 15000 times! and this causes app to crash in some phones. I'm sure that its because of using database methods too much. and because of low ram.
Is there any solution to manage this problem?
tnx :)

 if (c.moveToFirst()) {
        for (int i = 0; i < c.getCount(); i++) {
            long dateInMilli = Long.parseLong(c.getString(c.getColumnIndexOrThrow("date")).toString());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(dateInMilli);
            body = c.getString(c.getColumnIndexOrThrow("body")).toString();
            date = sdf.format(calendar.getTime());
            address=c.getString(c.getColumnIndexOrThrow("address")).toString();
            writeFile(address + "\n" + body + "\n" + date + "\n\n");
            c.moveToNext();
        }
        stopManagingCursor(c);
        c.close();
    }

Upvotes: 0

Views: 89

Answers (3)

Colt McAnlis
Colt McAnlis

Reputation: 3886

You have a two fold issue here. The first is Memory Churn. The video Memory Churn and Performance talks about this problem more. Effectively, you're doing allocations in the inner part of a very long loop. As such, you're creating a flood of allocations and putting a lot of pressure on the Garbage Collector. I would estimate that if you profiled your memory (see Memory Profilling 101) that you'd see lots of garbage collection events occurring.

Specifically, your new SimpleDateFormat variables should be allocated OUTSIDE your loop, and re-used multiple times inside of it. The same goes for your Calander.getInstance() call. There's also some sketchy calls you're making with string allocations (calling c.getString().toString() etc) which won't make this any easier.

The second problem you have is most likely blocking the UI thread. You can learn more about this in Rendering Performance 101. Basically, the system is trying to render the screen every 16ms, and if you're doing a 20 minute task, the system will stall, and try to throw an "Application Not Responsive" dialog (which you can detect using Strict Mode). Using AsyncTask or some other primitive will help you move this work OFF of the UI thread, so that it doesn't block the rendering of your application.

Upvotes: 1

Shyamnath Prem
Shyamnath Prem

Reputation: 1

Using AsyncTask will solve your problem. AsyncTask helps you to perform background operations and show its result on the UI thread.

Upvotes: 0

Malwinder Singh
Malwinder Singh

Reputation: 7070

Use Async Task or an Intent Service. Both run in Background and will not interrupt the normal functioning of app. I prefer Async Task because it allows you to update UI thread. Use Intent Service only for running long tasks.

Upvotes: 0

Related Questions