Subclassing a ParseObject Subclass (Android)

时间:2015-07-28 16:48:30

标签: java android parse-platform

Is it possible to subclass subclasses of ParseObjects? I am following the directions here. My class looks like this:

@ParseClassName("Stove")
public class Stove extends ParseObject{

  private String URL = "url";
  private String BRAND_NAME = "brand name";

  public Stove() {
    //Needed for Parse
  }

  public Stove(String url, String brandName) {
    put(URL, url);
    put(BRAND_NAME, brandName);
  }

  public String getUrl() {
    return getString(URL);
  }

  public String getBrandName() {
    return getString(BRAND_NAME);
  }
  ...
}

and I have a subclass of this that looks like

@ParseClassName("ElectricStove")
public class ElectricStove extends Stove{
  public ElectricStove() {
  }

  public ElectricStove(String url, String brandName) {
    super(url, brandName);
  }
  ...
}

My Application subclass is registered in AndroidManifest.xml and has this code in onCreate():

ParseObject.registerSubclass(Stove.class);
ParseObject.registerSubclass(ElectricStove.class);
...
Parse.initialize(this, "<lots of letters>", "<more letters>");
ParseInstallation.getCurrentInstallation().saveInBackground();

I'm getting this exception

Caused by: java.lang.IllegalArgumentException: You must register this ParseObject subclass before instantiating it.
at com.parse.ParseObject.<init>(ParseObject.java:363)
at com.parse.ParseObject.<init>(ParseObject.java:324)
at <package>.Stove.<init>(Stove.java:16)
at <package>.ElectricStove.<init>(ElectricStove.java:7)

which makes me wonder if I'm going about this in the wrong way or if it's perhaps simply not possible.

1 个答案:

答案 0 :(得分:3)

It's just not possible at this point, as Parse Android SDK does not support this. Rather, as a suggestion, use an identifier to specify what type of "Stove" a particular stove object is. Take this example:

@ParseClassName("Instrument")
public class Instrument extends ParseObject {
    public Instrument() {
    // A default constructor is required.
    }

    public InstrumentType getType() {
        return InstrumentType.parse(getString("type"));
    }
    public void setType(InstrumentType type) {
        put("type", type.toString());
    }

then use:

final Instrument ocarina = new Instrument();

// Since our Instruments are strongly-typed, we can provide mutators that only take
// specific types, such as Strings, ParseUsers, or enum types.
ocarina.setType(InstrumentType.WOODWIND);

This would be a work-around of sorts to allow you to perform actions on an object based on it's type. It's not perfect, but it may suit your needs. The InstrumentType is just a class used for static constants in order to access id values

Example taken from here