2017-09-21 1 views
0

Je ne fais que commencer avec Room-Android.Salle Android - Tableau de float, entier, double, .... - Vous pouvez envisager d'ajouter un convertisseur de type pour cela

J'essaie de persister un de mon modèle dont l'un des champs est un tableau:

float[] values; 

J'ai eu cette erreur à la compilation:

Error: Cannot figure out how to save this field into database. 
You can consider adding a type converter for it. 

J'ai créé un convertisseur de type:

public static class ConverterFloatToString { 

    @TypeConverter 
    public String JSONArrayfromFloatArray(Float[] values) { 
     JSONArray jsonArray = new JSONArray(Arrays.asList(values)); 
     return jsonArray.toString(); 
    } 

    @TypeConverter 
    public float[] JSONArrayToFloatArray(String values) { 
     try { 
      JSONArray jsonArray = new JSONArray(values); 
      float[] floatArray = new float[jsonArray.length()]; 
      for (int i = 0; i < jsonArray.length(); i++) { 
       floatArray[i] = Float.parseFloat(jsonArray.getString(i)); 
      } 
      return floatArray; 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

et j'affecté au champ:

@TypeConverters(ConverterFloatToString.class) 
float[] values; 

Mais je reçois toujours la même erreur.

Cannot figure out how to save this field into database. 
You can consider adding a type converter for it. 

Qu'est-ce qui ne va pas?

Répondre

0

Ok, j'ai fait une erreur dans mon convertisseur de type.

JSONArrayfromFloatArray(Float[] values) -> JSONArrayfromFloatArray(float[] values) 

Et j'ai changé mon convertisseur à ceci:

public static class ConverterFloatToString { 

    @TypeConverter 
    public static String JSONArrayfromFloatArray(float[] values) { 
     JSONArray jsonArray = new JSONArray(); 
     for (float value : values) { 
      try { 
       jsonArray.put(value); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
     return jsonArray.toString(); 
    } 

    @TypeConverter 
    public static float[] JSONArrayToFloatArray(String values) { 
     try { 
      JSONArray jsonArray = new JSONArray(values); 
      float[] floatArray = new float[jsonArray.length()]; 
      for (int i = 0; i < jsonArray.length(); i++) { 
       floatArray[i] = Float.parseFloat(jsonArray.getString(i)); 
      } 
      return floatArray; 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

Mais je ne suis pas fan de cette solution, avec ces conversions d'une erreur peut se produire ... Si vous avez une meilleure solution i prendre ;)