1

this below class in my database model on Relam object

public class ModelMarketBanners extends RealmObject {
    @PrimaryKey
    private String id;
    private String marketId;
    private String imageFileName;
    private String title;
}

as far as i know i can get model fields data by class getter such as getId(), but i want to get filed name instead of class getter methods on loop clause, for example using for to show all class fields such as id or marketId, how can i do that?

i want to get all fileds data and if which one isn't empty attach layout with that data, instead of programing multi line to check and attaching that

for example:

for(int i=0; i> model.field_count; i++){
     if (model.field.lenght() > 0) Log.v("data is: ", model.field);
}

instead of

SampleModel model = realm.where(SampleModel.class).findfirst();
if(model.getId().lenght() > 0)
   Log.v("data is",model.getId());
if(model.getmarketId().lenght() > 0)
   Log.v("data is",model.getmarketId());
if(model.getImageFileName().lenght() > 0)
   Log.v("data is",model.getImageFileName());
mahdi pishguy
  • 994
  • 1
  • 14
  • 43

2 Answers2

3

There is a way, using reflection:

    for (Field field : ModelMarketBanners.class.getDeclaredFields()) {
        for (Method method : ModelMarketBanners.class.getMethods()) {
            if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3))) {
                if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase())) {
                    try {
                        Object value = method.invoke(model);
                        if (!TextUtils.isEmpty(String.valueOf(value)) {
                            Log.v("data is: ", String.valueOf(value));
                        }
                    } catch (IllegalAccessException | InvocationTargetException e) {
                    }

                }
            }
        }
    }
Divers
  • 9,531
  • 7
  • 45
  • 88
0

I saw the other post, take a look at this using reflection...

public class SomeClass {
    private String returnString;
    private String id;
    private String marketId;
    private String imageFileName;
    private String title;

    // test
    public static void main(String[] args) {
    List<String> myFields = new ArrayList<>();
    Field[] allFields = SomeClass.class.getDeclaredFields();
    for (Field field : allFields) {
        myFields.add(field.getName());
    }
    System.out.println(myFields);
    }
}

the output will be the fields of the class

[returnString, id, marketId, imageFileName, title]

EDit:

if you need the data in the string variables please take a look at this question/ my answer....

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97