1

I have been trying to store an array of strings in Realm database programmatically as given below:

Model Class:

  public class Station extends RealmObject {
  private String name;

  // ... Generated getters and setters ...
  }

Saving Data:

  realm.executeTransactionAsync(new Realm.Transaction() {
  @Override
  public void execute(Realm realm) {
    Station station1 =     realm.createObject(Station.class)
    station1.setName(name1);
   Station station2 = realm.createObject(Station.class)
    station2.setName(name2);
  //goes on till station8000
   }
   }, new Realm.Transaction.OnSuccess() {
  @Override
  public void onSuccess() {
    // ...
 });

Is there an alternate best way for this?

V1 Kr
  • 177
  • 1
  • 3
  • 18

1 Answers1

0

Why yes of course there is

public class Station extends RealmObject {
    private String name;

    // ... Generated getters and setters ...
}

and

// field variable
RealmResults<Station> stations;
// field variable
RealmChangeListener<RealmResults<Station>> changeListener = new RealmChangeListener<RealmResults<Station>>() {
    @Override
    public void onChange(RealmResults<Station> results) {
        // handle onSuccess()
    }
}

and

stations = realm.where(Station.class).findAll();
stations.addChangeListener(changeListener);

realm.executeTransactionAsync(new Realm.Transaction() {
   @Override
   public void execute(Realm realm) {
      Station station = new Station();
      for(String stationName : listOfStationNames) {
          station.setName(stationName);
          realm.insert(station);
      }
   }
});

EDIT: Check out this sexy spinner.

public class DropdownSpinnerAdapter
        extends BaseAdapter
        implements SpinnerAdapter {
    private static final String TAG = "DropdownSpinnerAdapter";

    private boolean isItemSelected;

    RealmResults<Station> content;

    public ResultDropdownSpinnerAdapter(RealmResults<Station> objects) {
        this.content = objects;
    }

    @Override
    public int getCount() {
        if(content == null || !content.isValid()) {
            return 1;
        }
        return content.size() + 1;
    }

    @Override
    public String getItem(int position) {
        if(position <= 0) {
            return "";
        }
        return content.get(position - 1);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public int findPosition(Station selectedItem) {
        for(int i = 0, s = content.size(); i < s; i++) {
            Station item = content.get(i);
            if(item.equals(selectedItem)) {
                return i + 1;
            }
        }
        return 0;
    }


    static class ViewHolder {
        TextView textView;
        ImageView imageView;

        public ViewHolder(View convertView) {
            textView = ButterKnife.findById(convertView, R.id.dropdown_textview);
            imageView = ButterKnife.findById(convertView, R.id.dropdown_arrow);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView != null) {
            if(!(convertView instanceof DropdownHeaderView)) {
                convertView = null;
            }
        }
        if(convertView == null) {
            convertView = LayoutInflater.from(parent.getContext())
                    .inflate((isItemSelected) ? R.layout.dropdown_selected : R.layout.dropdown,
                            parent,
                            false);
            ViewHolder viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }
        ViewHolder viewHolder = (ViewHolder) convertView.getTag();
        viewHolder.textView.setText(getItem(position).getName());
        return convertView;
    }

    public void setItemSelected(boolean selected) {
        this.isItemSelected = selected;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(convertView != null) {
            if(!(convertView instanceof DropdownView)) {
                convertView = null;
            }
        }
        if(convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.dropdown_noarrow, parent, false);
            ViewHolder viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }
        ViewHolder viewHolder = (ViewHolder) convertView.getTag();
        viewHolder.textView.setText(getItem(position).getName());
        return convertView;
    }

    public void updateContent(RealmResults<Station> content) {
        this.content = content;
        notifyDataSetChanged();
    }
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • What is 'listOfStationNames' here? I didn't get it – V1 Kr Aug 20 '16 at 14:52
  • the contents of `name1`, `name2`, ... `name8000` in a list – EpicPandaForce Aug 20 '16 at 14:57
  • Fast response...thankyou..I will have to check this out...I'l comment here once I'm done – V1 Kr Aug 20 '16 at 14:58
  • 1
    But you haven't mentioned "realm.copyToRealm" or "realm.createObject". Shouldn't I use either one of them? Also I haven't seen "realm.insert" in their docs.. – V1 Kr Aug 20 '16 at 15:10
  • It was added in `v1.1.0`, and the latest version is `v1.2.0` (I've been using `1.1.1` lately) – EpicPandaForce Aug 20 '16 at 15:11
  • So can I use it in 1.2? – V1 Kr Aug 20 '16 at 15:16
  • yes of course, and you should! `insert()` faster for this use-case than `copyToRealm()` (and than `createObject()`) – EpicPandaForce Aug 20 '16 at 15:16
  • Hey, it workst..BUT while displaing in a spinner, its like: "Station = [{name;station1}].....Station = [{name;station2}].......etc" instead of "station1...station2...etc". I tried converting ReamResults into ArrayList, but it didn't work – V1 Kr Aug 21 '16 at 15:26
  • That's because your Spinner seems to call `toString()` on them, you have to redefine your `getView()` and `getDropDownView()` methods to set `getItem(position).getName()` instead. This is a bitch to do so I'll edit my solution for that into my post. – EpicPandaForce Aug 21 '16 at 16:49
  • oooooor you can just redefine `toString()` in `Station` to return `return name;` and that'll also fix this issue I think, lol – EpicPandaForce Aug 21 '16 at 17:00
  • No no no...it's: Station = [{name;station1}].....Station = [{name;station2}].......etc instead of station1...station2...etc (no double quotes), Also toString isn't supported inside a realm object right? – V1 Kr Aug 22 '16 at 10:17
  • Ahhh then you're displaying the entire `RealmResults` as one element. I think an `ArrayAdapter` should work **if** you redefine `toString()` in `Station` which has been possible since [0.88.3](https://github.com/realm/realm-java/blob/master/CHANGELOG.md) – EpicPandaForce Aug 22 '16 at 10:29
  • 1
    Mayb i read an old tutorial about toString! Tnx! I am currently doing it as: ArrayAdapter(this, android.R.layout.simple_list_item_1, RealmResults a)..now lemme check with your suggestion of toString.. – V1 Kr Aug 22 '16 at 10:40
  • Glad I could help :) – EpicPandaForce Aug 23 '16 at 05:55
  • hey, can you help with this: http://stackoverflow.com/questions/39096308/realm-android-exception-occured-during-performfiltering – V1 Kr Aug 23 '16 at 08:40