【问题标题】:When I use WeakReference, cannot resolve symbol message on android当我使用 Wea​​kReference 时,无法解析 android 上的符号消息
【发布时间】:2017-10-26 01:58:28
【问题描述】:

我的应用相机预览记录应用。 我在录制相机预览期间使用ArrayList

ArrayList 声明在全局变量上

private ArrayList<OutputInputPair> pairs = new ArrayList<OutputInput>();

当我记录停止按钮点击时,执行stop()方法

@Override
public void stop() {
   pairs.clear();
   pairs = null;
   stopped = true;
}

所以,如果我继续录制而不单击录制停止按钮。 发生大量内存泄漏。

所以,我想使用WeakReference 我试试这个

//private ArrayList<OutputInputPair> pairs = new ArrayList<OutputInputPair();
  private ArrayList<WeakReference<OutputInputPair>> pairs = new ArrayList<WeakReference<OutputInputPair>>();  //global variable

 @Override
 public void add(OutputInputPair pair) {
    //pairs.add(pair);
    pairs.add(new WeakReference<OutputInputPair>(pair));
 }

 @Override
 public void stop() {
    pairs.clear();
    pairs = null;
    stopped = true;
 }

 @Override
 public void process() {  //record method
    //for (OutputInputPair pair : pairs) {
    for (WeakReference<OutputInputPair> pair = pairs) {
        pair.output.fillCommandQueues(); //output is cannot resolve symbol message 
        pair.input.fillCommandQueues(); //input is cannot resolve symbol message
    }

    while (!stopped) { //when user click stop button, stopped = true.
        //for (OutputInputPair pair : pairs) {
         for (WeakReference<OutputInputPair> pair : pairs) {
             recording(pair); //start recording 
         }
     }
   }

public interface IOutputRaw  {   //IInputRaw class same code.
    void fillCommandQueues(); 
}

我觉得How to Avoid memory rick,使用WeakReference是对的?

如何解决无法解析符号消息使用弱引用?

谢谢。

public class OutputInputPair {
    public IOutputRaw output;
    public IInputRaw input;

     public OutputInputPair(IOutputRaw output, IInputRaw input) {
         this.output = output;
         this.input = input;
     }
 }

【问题讨论】:

    标签: java android arraylist weak-references


    【解决方案1】:

    我不太了解WeakReference。但是您应该使用get() 方法来获取实际参考。

    用途:

    if(pair == null) continue;
    OutputInputPair actualPair = pair.get();
    if(actualPair == null) continue;
    actualPair.output.fillCommandQueues();
    actualPair.input.fillCommandQueues();
    

    代替:

    pair.output.fillCommandQueues();
    pair.input.fillCommandQueues();
    

    【讨论】:

    • null使用前请检查。
    • 不,不是对,pair.get() 可以在弱引用对象被清除的情况下返回 null。
    • @Oleg 哎呀,再次编辑,正如我提到的,我对WeakReference 了解不多。没关系。
    • @Oleg pair == null ?检查?
    • 很高兴我能帮上忙。 :)
    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多