[英]Android OutOfMemoryError with HashMap and ArrayList
我正在解析一个csv文件,更具体地说是一个POI文件,使用opencsv并将信息读入ArrayList。 我需要将信息缓存在内存中,这样当用户点击按钮时,我会检查每个POI并查看它是否在mapview的当前范围内。 一些POI文件可以有10K - 60K行。 在app力关闭之前,我可以阅读大约50K行,所以我设置了30K的限制为其他东西留下内存。 我的问题是当我去加载另一个文件时我清除()Arraylists我trimToSize()并尝试将ArrayLists声明为新的ArrayLists但GC从不从内存中释放旧数据。 我可以清除()它们并将新文件读入它们但有些东西不允许GC释放内存。 我没有接受过编程,IT或CS方面的培训。 这是我用Java / Android编写过的第一个应用程序。 我已经工作,阅读和学习了大约6天,现在试图弄清楚为什么我有这个内存泄漏。 任何帮助将不胜感激,任何关于如何优化我的代码的建议也将受到赞赏,因为我是一个完整的菜鸟。 此外,下面的代码仅显示了将文件读入内存的方法。 您可以谷歌opencsv查看文档如何工作,如果你需要看到任何其他让我知道,我会发布它。
提前致谢!
public class MainActivity extends MapActivity implements LocationListener {
private static MapView mapView;
int counter = 0;
private ArrayList<String> arrLat = new ArrayList<String>();
private ArrayList<String> arrLong = new ArrayList<String>();
private ArrayList<String> arrName = new ArrayList<String>();
private ArrayList<String> arrInfo = new ArrayList<String>();
private ArrayList<Boolean> arrCheck = new ArrayList<Boolean>();
private ProgressDialog progressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// main.xml contains a MapView
setContentView(R.layout.main);
//Gets file name from ListOfFiles Activity Class
Bundle extras = getIntent().getExtras();
if (extras != null) {
boolean callreadPOIFile = extras.getBoolean("callreadPOIFile");
if(callreadPOIFile) {
String filePath = extras.getString("filePath");
readPOIFileInThread(filePath);
}else{
// Show user alert box
}
}
}
public void readPOIFileInThread(String filePath) {
progressDialog = ProgressDialog.show(this, "", "LOADING:\n" + filePath + "\nPLEASE WAIT...");
final String finalFilePath = filePath;
new Thread(new Runnable(){
public void run(){
try{
readPOIFile(finalFilePath);
}catch(Exception e){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Exception, readPOIFileInThread", Toast.LENGTH_SHORT).show();
//progressDialog.dismiss();
}
});
}
progressDialog.dismiss();
}
}).start();
}
//Parse and load POI CSV File
public void readPOIFile(String filePath){
arrLat.clear();
arrLong.clear();
arrName.clear();
arrInfo.clear();
arrCheck.clear();
arrLat.trimToSize();
arrLong.trimToSize();
arrName.trimToSize();
arrInfo.trimToSize();
arrCheck.trimToSize();
//arrLat = null;
//arrLong = null;
//arrName = null;
//arrInfo = null;
//arrCheck = null;
//arrLat = new ArrayList<String>();
//arrLong = new ArrayList<String>();
//arrName = new ArrayList<String>();
//arrInfo = new ArrayList<String>();
//arrCheck = new ArrayList<Boolean>();
System.out.println(arrLat.isEmpty());
String lat = null;
String lng = null;
Double dLat;
Double dLng;
int lati;
int lngi;
String name = null;
String info = null;
CSVReader reader = null;
//System.out.println(filePath);
try {
reader = new CSVReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// set the message to display
alertbox.setMessage("There was an error reading file: " + filePath
+ "\n Please check the file format and try again.");
// add a neutral button to the alert box and assign a click listener
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
// the button was clicked
//Toast.makeText(getApplicationContext(), "OK button clicked", Toast.LENGTH_SHORT).show();
}
});
// show it
alertbox.show();
e.printStackTrace();
}
String [] nextLine = null;
int count = 0;
try {
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
//System.out.println(nextLine[0]+ "\n" + nextLine[1]+ "\n" + nextLine[2]+ "\n" + nextLine[3] + "\n");
try {
lng = nextLine[0];
} catch (Exception e) {
lng = Integer.toString(1);
}
try {
lat = nextLine[1];
} catch (Exception e) {
lat = Integer.toString(1);
}
try {
name = nextLine[2];
} catch (Exception e) {
name = "No Name...";
}
try {
info = nextLine[3];
} catch (Exception e) {
info = "No Info...";
}
//convert lat and long to double
try{
dLat = Double.parseDouble(lat);
dLng = Double.parseDouble(lng);
}catch(Exception e){
System.out.println("error converting lat long to Double at row: " + count);
break;
}
//convert lat lng to int
lati = (int)(dLat * 1E6);
lngi = (int)(dLng * 1E6);
//add line to ArrayLists
try{
arrLat.add(Integer.toString(lati));
arrLong.add(Integer.toString(lngi));
arrName.add(name);
arrInfo.add(info);
arrCheck.add(false);
}catch (Exception e){
runOnUiThread(new Runnable() {
public void run() {
//Toast.makeText(getApplicationContext(), "Error reading. Please check the file. ", Toast.LENGTH_SHORT).show();
System.out.println("Error reading file.");
}
});
}
count++;
if(count == 10000 || count == 20000){
final int showcount = count;
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), showcount + " POI's loaded",
Toast.LENGTH_LONG).show();
}
});
}
if(count == 30000)
break;
System.out.println(count);
}
final String toastFilePath = filePath;
final int toastcount = count;
runOnUiThread(new Runnable() {
public void run() {
if(toastcount > 0){
Toast.makeText(getApplicationContext(), "File: " + toastFilePath + " read... \n"
+ toastcount + " point(s) were loaded...",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "INVALIDE FILE!\nFile: " + toastFilePath + " read... \n"
+ toastcount + " points.",
Toast.LENGTH_LONG).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
固定:
我最终找到了我的问题! 在研究了活动生命周期后,我发现每次进入列表活动选择文件并缓存它时都会创建一个新实例我正在创建一个新的MainActivity实例。 我在清单中将MainActivity设置为singleTop模式,并将一些代码移动到onNewIntent()方法,一切都很好。 我的应用程序现在很棒!
一些建议:
没有对View对象(或drawable,或任何引用上下文的东西) 的静态引用 。 这是一个非常糟糕的实践,很容易让你内存泄漏.reason:即使在离开活动之后,还有一个静态引用视图,它引用了你已经离开的活动,包括它的所有字段(你的大集合) , 例如)。 在这里阅读更多信息。
你真的必须读取整个文件,并将其全部内容存储到内存中吗? 当然它对你来说很容易,而且比其他任何东西都快,但它很容易占用大量内存,特别是如果你这样使用它。 尽量只读你需要的东西 , 只储存你需要的东西 。
观看谷歌的视频,了解如何查找和处理内存泄漏
你真的必须将数据存储在字符串中吗? 如何只需要检查的值(坐标,也许是?)或Pois的集合 ,每个都有自己的字段(id,name,coordinates,...)? java中的字符串是一个字符数组,每个字符占用2个字节(因为它是unicode),因此它可能占用内存中的大量空间。例如,60000行乘以80个字符乘以每个字符2个字节是9,600,000个字节,这几乎是10MB 。 你需要更紧凑的内存使用。 请记住,它是一个移动平台,其内存效率是其最重要的优先事项之一(用于更好的任务切换)。
使用Pois集合不仅在设计方面更好(更容易阅读,理解,维护......)。 它也将占用更少的空间 - 使用原语而不是包装(例如int而不是Integer)。
几个想法:
Integer.toString(1)
可以替换为"1"
,这将利用字符串池。 String
? lat
和lng
听起来像是在尝试存储纬度和经度。 也许你想用Double
来做到这一点。 ArrayList
。 我对CSVReader的实现知之甚少,但它在readPOIFile中永远不会被关闭。 如果它挂在东西上它可能会导致内存问题。
我检查了静态引用我的Mapview并删除静态改变了什么,除了它打破了我的getter和setter。 我最终找到了我的问题! 在研究了活动生命周期后,我发现每次进入列表活动选择文件并缓存它时都会创建一个新实例我正在创建一个新的MainActivity实例。 我在清单中将MainActivity设置为singleTop模式,并将一些代码移动到onNewIntent()方法,一切都很好。 我的应用程序现在很棒!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.