【问题标题】:how to avoid memory leaks in android如何避免android中的内存泄漏
【发布时间】:2011-07-21 05:38:07
【问题描述】:

我正在动态更新表格布局,如下所示,我在其中为每个 tableRow 添加了一个图像按钮和一个 Textview。每当我启动我的活动时,它只显示 4 行(实际上应该显示 10 行)但是如果我在代码中保留断点并且慢慢调试以找出正确显示所有 10 行的问题。我怀疑这一定是代码中的内存问题,因为我从网上获取图像,我觉得这需要大量内存。我尝试在添加到布局后释放视图内存,但它一直在崩溃。
请让我知道我在哪里做错了。

for (int i = 0; i < parsedExampleDataSet.getAppNameString().size(); i++)  
{  
 TableRow row = new TableRow(this);  
 TextView tv = new TextView(this);  
 tv.setText("AppName: "+ parsedExampleDataSet.getAppNameString().get(i) +"\n"     + "Description: " + parsedExampleDataSet.getDescriptionString().get(i));  
 ImageButton imgBtn = new ImageButton(this);  
 URL aURL = new URL(parsedExampleDataSet.getImageUrlString().get(i));   
 URLConnection conn = aURL.openConnection();   
 conn.connect();   
 InputStream is = conn.getInputStream();   
 BufferedInputStream bis = new BufferedInputStream(is);  
 Bitmap bm = BitmapFactory.decodeStream(bis);   
 imgBtn.setImageBitmap(bm);  
 imgBtn.setBackgroundColor(color.transparent);  
 imgBtn.setTag(parsedExampleDataSet.getMarketLinkString().get(i));  
 bis.close();   
 is.close();                      
 row.addView(imgBtn);  
 row.addView(tv);  
 table.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  //here table is a tablelayout object

}

提前致谢
普拉提玛

【问题讨论】:

  • 什么是堆栈跟踪?
  • 如何获得 parsedExampleDataSet?它不是在单独的线程中解析的吗?您是否尝试仅打印它的大小?
  • @ania ::no 它在同一个线程中解析。我尝试打印 size()。现在会做。谢谢

标签: android memory memory-leaks


【解决方案1】:

如果你想加载多行而不是使用 ListView。

它处理所有内存问题,比 TableLayout 更好。

here 就是一个很好的例子。

【讨论】:

  • 谢谢!我是安卓新手。最初我尝试使用 listview 来实现它,但我无法正确理解这个概念。这就是我选择表格布局的原因
【解决方案2】:

答案似乎位于parsedExampleDataSet.getAppNameString().size()

  • 在运行程序时,for(;;) 循环仅迭代 4 次

  • 当你运行调试器并手动单步执行时,它会迭代 10 次,这符合你的预期

parsedExampleDataSet.getAppNameString() 是如何填充的?它的大小被用作for(;;) 循环的上限,它似乎会随着时间而改变。如果它由异步进程(线程)填充,这将解释问题。

请随时添加更多详细信息并告诉我。我将根据您将带来的新元素进一步编辑/详细说明此答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2015-08-27
    相关资源
    最近更新 更多