【问题标题】:Store a custom Array List in Shared Preference在共享首选项中存储自定义数组列表
【发布时间】:2016-01-06 05:56:44
【问题描述】:

我想在 Shared Preference 中存储一个自定义数组列表,以便下次打开我的应用程序时可以读取该列表。 我看了很多教程和答案,但我无法真正理解。

list_addr.java

public class list_addr {

public String title;
public String detail;


public list_addr( String title, String detail) {
    super();

    this.title = title;
    this.detail=detail;

}

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getDetail() {
    return detail;
}
public void setDetail(String detail) {
    this.detail = detail;
}


@Override
public String toString() {
    return title + "\n" ;
}

}

list_adapter.java

enterpublic class list_addr_adapter extends ArrayAdapter<list_addr> {

Context context;
int layoutResourceId;



public list_addr_adapter(Context context, int layoutResourceId, List<list_addr> items) {
    super(context, layoutResourceId, items);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    //  this.listener=callback;
}

/*private view holder class*/
private class ViewHolder {

    TextView txtTitle;
    TextView txtDetail;
    ImageView imageview;
    CheckBox checkbox;

}
ViewHolder holder = null;

public View getView(final int position, View convertView, ViewGroup parent) {
    final list_addr lists = getItem(position);
    final int pos=position;


    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.items_sav_addr2, null);
        holder = new ViewHolder();
        holder.txtTitle = (TextView) convertView.findViewById(R.id.textTitle);
        holder.txtDetail = (TextView) convertView.findViewById(R.id.detail);
        holder.imageview = (ImageView) convertView.findViewById(R.id.imageview);
        holder.checkbox=(CheckBox)convertView.findViewById(R.id.chkitem);


        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();






    holder.txtTitle.setText(lists.getTitle());
    holder.txtDetail.setText(lists.getDetail());

        return convertView;
    }

}

这就是我膨胀列表视图的方式 -

 listView1 = (ListView) findViewById(R.id.listView);
    list_adapter_invoice adapter = new list_adapter_invoice(this,
            R.layout.items_row, MyAdaptertwo.rowitems);

    listView1.setAdapter(adapter);

【问题讨论】:

  • 您是否尝试过将其保存在共享首选项中,因为您的代码没有显示一行保存代码
  • @VivekMishra 不,我没有,因为我看不懂方法。
  • 然后 google 将 arraylist 存储在共享首选项中
  • @VivekMishra 这就是我要说的,我用谷歌搜索却无法理解。
  • 使list_addr 实现Serializable,并使用ObjectOutputStreamByteArrayOutputStream 将该arraylist 序列化为字节数组,然后存储您的字节数组,并在使用时将其反序列化回列表。如果您感到困惑,我可以添加一个代码示例。

标签: android arraylist sharedpreferences android-arrayadapter custom-lists


【解决方案1】:

您只能将原始类型保存在共享首选项中。如果您需要保存 ArrayList ,则可以将其保存为以逗号分隔的 String 。在获取这个的时候使用 split(",") 在这个 String 上你会得到一个 String [] 。

如果你想保存一个对象列表,那么我建议使用单例类。这是 Singelton 类的示例。你想试试这个。

public class ReferenceWrapper {
private Context context;
private static ReferenceWrapper wrapper;
private ArrayList<Object> list;

private ReferenceWrapper(Context context) {
    this.context = context;
}

public static ReferenceWrapper getInstance(Activity activity) {
    if (wrapper == null) {
        wrapper = new ReferenceWrapper(activity);
    }
    return wrapper;
}


public ArrayList<Object> getList() {
    return list;
}

public void setList(ArrayList<Object> list) {
    this.list = list;
}

} 并像这样使用它

ReferenceWrapper wrapper=ReferenceWrapper.getInstance(MainActivity.this);
    wrapper.setList(yourArrarlist);

并在任何活动中获取它

ReferenceWrapper wrapper=ReferenceWrapper.getInstance(MainActivity.this);
ArrarList<Object> list= wrapper.getList(yourArrarlist);

它将返回您最近保存的相同 ArrayList 列表。因为它只有一个对象被创建 .让我知道它是否有帮助

【讨论】:

  • 这个类到底怎么用?
【解决方案2】:

答案是在File而不是SharedPreference中写入对象。希望这可能会有所帮助

    try {
        ArrayList<List_addr> addrList = new ArrayList<>();
        addrList.add(new List_addr("Bangalore", "Its a City"));
        addrList.add(new List_addr("Delhi", "Its also a City"));

        //write object into a file
        FileOutputStream fos = openFileOutput("addrList", Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(addrList);
        oos.close();

        //read object from the file
        FileInputStream fis = openFileInput("addrList");
        ObjectInputStream ois = new ObjectInputStream(fis);
        ArrayList<List_addr> readAddrList = (ArrayList<List_addr>) ois.readObject();
        ois.close();

        for (List_addr address : readAddrList) {
            Log.i("TAG", "Name " + address.getTitle() + " City " + address.getDetail());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

重要提示:请注意@MeetTitan 回答 cmets。

【讨论】:

    【解决方案3】:
             Step 1:
    
               Put string array set into the shared preference.
               pref.putStringSet(String key, Set<String> values);
    
             Step 2:
    
               Convert array list of pojo into set.
               Set<String> set = new HashSet<String>(list);
    
             Set 3:
    
               Retrive using the getStringSet.
    

    【讨论】:

      【解决方案4】:

      要将arraylist保存在共享首选项中,请执行以下操作

       // Create List of address that you want to save
          ArrayList addressList = new ArrayList();
          addressList.add(new list_addr());
         addressList.add(new list_addr());
          SharedPreferences prefs = getSharedPreferences("address", Context.MODE_PRIVATE);
          //save the user list to preference
          Editor editor = prefs.edit();
          try {
          editor.putString("addressList", ObjectSerializer.serialize(addressList));
          } catch (IOException e) {
          e.printStackTrace();
          }
          editor.commit();
      

      然后用这个来检索arraylist

      ArrayList addressList = new ArrayList();
      // Load address List from preferences
      SharedPreferences prefs = getSharedPreferences("address", Context.MODE_PRIVATE);
      try {
      addressList = (ArrayList) ObjectSerializer.deserialize(prefs.getString("addressList", ObjectSerializer.serialize(new ArrayList())));
      } catch (IOException e) {
      e.printStackTrace();
      }
      

      这是 objectSerializer 类的链接 Object Serializer

      【讨论】:

        猜你喜欢
        • 2021-12-30
        • 2017-08-19
        • 1970-01-01
        • 1970-01-01
        • 2014-01-16
        • 2011-10-05
        • 2018-08-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多