Inheriting the ParseObject subclass (Android)
Is it possible to subclass a subclass of ParseObject
? I followed the instructions here
@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);
}
...
}
I have a subclass that looks like this
@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 I have this code in onCreate():
ParseObject.registerSubclass(Stove.class);
ParseObject.registerSubclass(ElectricStove.class);
...
Parse.initialize(this, "<lots of letters>", "<more letters>");
ParseInstallation.getCurrentInstallation().saveInBackground();
I ran into 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)
It makes me wonder if I’m handling this the wrong way, or if that’s simply impossible.
Solution
This is not yet possible because it is not supported by the Parse Android SDK. Instead, as a suggestion, use identifiers to specify what type of “stove” a particular cooktop object is. For 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 will be a workaround that allows you to perform operations on the object depending on its type. It’s not perfect, but it might suit your needs. InstrumentType is simply a class for static constants to access id values
Example taken from here