【问题标题】:Loading listview using SharedPreferences throwing OutofMemoryError使用抛出 OutofMemoryError 的 SharedPreferences 加载列表视图
【发布时间】:2015-06-15 09:29:51
【问题描述】:

我在 mainactivity 中使用 edittext 和按钮,单击时我想将文本添加到它正确执行的列表视图中。

我还使用 sharedpreferences 保存它,这样当我返回 mainactivity 或重新启动应用程序时,它会自动加载列表视图,但是在单击按钮时,我在这一行得到 OutOfMemoryerror:

   arrayCars.add(new Car(pred.getString("Value["+i+"]", ""),"green",3455));

列表视图代码:

       ArrayList<Car> arrayCars;
ListView listViewCars;
String venName;
SharedPreferences pred;
SharedPreferences.Editor spEditor;
static int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
    arrayCars=new ArrayList<Car>();

    System.out.println("count is"+count);
    pred = getSharedPreferences("place", Context.MODE_PRIVATE);
       spEditor = pred.edit();
       count = pred.getInt("countd",count);
        if(count > 0){
           for(int i = 0; i < count; i++){

               arrayCars.add(new Car(pred.getString("Value["+i+"]",  ""),"green",3455));


        count++;
           }
          }

      listViewCars = (ListView) findViewById(R.id.list_cars);
    ListCarsAdapter adapter = new ListCarsAdapter(this, arrayCars);
    listViewCars.setAdapter(adapter);
    listViewCars.setOnItemClickListener(this);



    try{
        Bundle bundle = getIntent().getExtras();
         venName = bundle.getString("r"); 
    }catch(Exception e){}

        if(venName!=null){
        spEditor.putString("Value["+count+"]", venName);
        spEditor.apply();
        arrayCars.add(new Car(pred.getString("Value["+count+"]", ""),"red",3444));
        count += 1;
        spEditor.putInt("countd", count);
        adapter.notifyDataSetChanged();
        }  

    }

PS:我正在使用自定义列表视图

【问题讨论】:

    标签: android listview android-listview sharedpreferences


    【解决方案1】:
    count = pred.getInt("countd",count);
        if(count > 0){
           for(int i = 0; i < count; i++){
    
               arrayCars.add(new Car(pred.getString("Value["+i+"]",  ""),"green",3455));
    
    
        count++;
           }
        }
    

    在上面的代码中,您每次将计数增加 1,因此它永远不会结束循环将重复,直到它抛出异常。

    为了避免删除那个计数++;

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      删除count++;你增加count变量同时增加i,所以for循环永远不会停止

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-16
        • 1970-01-01
        • 1970-01-01
        • 2019-01-28
        • 2017-06-25
        • 2014-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多