2017-02-02 2 views
0

J'ai besoin d'aide avec mon RecyclerView. J'ai un tableau atring de ma base de données SQL qui ressemble à ceci:Json text to RecyclerView dans Android

{"success":true,"0":{"order_number":"078","typ_first":"E3rft","typ_last":"Split","order_date_time":"2016-10-11 19:20:03"},"1":{"order_number":"166","typ_first":"E483f","typ_last":"Split_test","order_date_time":"2016-10-12 18:39:30"}} 

Dans mon RecyclerView je les champs suivants:

  • order_number
  • typ_all (premier type et dernier)
  • date (seulement une date sans heure)

Ceci est ce que je reçois mon tableau de chaînes:

String plansData = plansPreferenceData.getString("plansPreferenceData", ""); 

Voilà comment je mis les données à mon RecyclerView:

// Set plan data 
Plans plan = new Plans("123", "E3rft Split", "11.10.2016"); 
// Add Object to list 
planList.add(plan); 

// Notify data changes 
pAdapter.notifyDataSetChanged(); 

Ma Plans classe:

public class Plans { 
    private String planTitle, planType, planDate; 

    public Plans(String planTitle, String planType, String planDate) { 
     this.planTitle = planTitle; 
     this.planType = planType; 
     this.planDate = planDate; 
    } 

    public void setPlanTitle(String planTitle) { 
     this.planTitle = planTitle; 
    } 

    public String getPlanTitle() { 
     return planTitle; 
    } 

    public void setPlanType(String planType) { 
     this.planType = planType; 
    } 

    public String getPlanType() { 
     return planType; 
    } 

    public void setPlanDate(String planDate) { 
     this.planDate = planDate; 
    } 

    public String getPlanDate() { 
     return planDate; 
    } 
} 

Mon onCreateView:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    View view = inflater.inflate(R.layout.fragment_training, container, false); 

    preparePlansData(); 

    return view; 
} 

Mon preparePlansData():

private void preparePlansData() { 

    // Set plan data 
    Plans plan = new Plans("123", "fkfjfjeje", "21.04.1977"); 
    // Add Object to list 
    planList.add(plan); 

    plan = new Plans("test", "tttt", "22.01.2017"); 
    planList.add(plan); 

    // Notify data changes 
    pAdapter.notifyDataSetChanged(); 

} 

Ma question est de savoir comment puis-je obtenir les informations sur le tableau de chaînes dans mon adaptateur? J'ai également besoin de formater la date avant d'ajouter. Merci de votre aide!

+0

Ce tutoriel devrait vous aider https://developer.android.com/training/material/lists-cards.html –

+0

Pas vraiment d'aide pour la première vue. Je dois extraire les données de ma matrice et créer les entrées pour mon RecyclerView. –

+0

Pas de réponse? J'ai besoin de cela ... –

Répondre

1

En savoir plus sur Gson ici:

http://guides.codepath.com/android/leveraging-the-gson-library

Après cela, vous serez en mesure d'écrire du code comme ça:

Type type = new TypeToken<Map<Integer, Plans>>(){}.getType(); 
Map<Integer, Plans> myMap = gson.fromJson("your json from db", type); 

et utiliser cette map.values ​​() dans votre adaptateur La classe Plans devrait ressembler à ceci:

class Plans { 
    String order_number; 
    String typ_first; 
    String typ_last; 
    String order_date_time; 
} 

Si vous voulez un autre nom de domaine, vous devez utiliser @SerializedName annotation

Enfin, vous devriez écrire quelque chose comme ça, (je ne sais pas si la syntaxe est de 100% ne pas IDE maintenant ouvert):

private void preparePlansData() { 
    String plansData = plansPreferenceData.getString("plansPreferenceData", ""); 
    Type type = new TypeToken<Map<Integer, Plans>>(){}.getType(); 
    Map<Integer, Plans> myMap = gson.fromJson(plansData, type); 
    planList.addAll(myMap.values()); 

    // Notify data changes 
    pAdapter.notifyDataSetChanged(); 
} 

et modifier votre classe modèle:

public class Plans { 
    @SerializedName("order_number") 
    String planTitle; 
    @SerializedName("typ_last") 
    String planType; 
    @SerializedName("order_date_time") 
    String planDate; 
    .... 

J'espère que cela vous aidera yo u.

+0

Mais comment extraire les différentes informations? Dans ce tableau sont deux objets donc il devrait y avoir deux lignes différentes –

+0

utiliser 'Map' voici la solution: http://stackoverflow.com/a/15943171/2318843 – RadekJ

+0

Vous cherchez bien. Pouvez-vous me donner un exemple pour une valeur de ma chaîne? N'oubliez pas que le résultat n'est pas statique comme dans la solution que vous avez publiée –

0

Vérifiez ce code (vous pouvez supprimer l'annotation @Test):

class Plans { 
    String typ_firstString; 
    String typ_last; 
    String order_date_time; 

    public Plans(String typ_firstString, String typ_last, String order_date_time) { 
     this.typ_firstString = typ_firstString; 
     this.typ_last = typ_last; 
     this.order_date_time = order_date_time; 
    } 
} 

class PlansResponse { 
    boolean status; 
    List<Plans> plans; 
} 

@Test 
public void testPlacesResponseDeserializer() { 
    Gson gson = new GsonBuilder() 
      .registerTypeAdapter(PlansResponse.class, new PlansResponseDeserializer()) 
      .create(); 
    String jsonString = "{\"success\":true,\"0\":{\"order_number\":\"078\",\"typ_first\":\"E3rft\",\"typ_last\":\"Split\",\"order_date_time\":\"2016-10-11 19:20:03\"},\"1\":{\"order_number\":\"166\",\"typ_first\":\"E483f\",\"typ_last\":\"Split_test\",\"order_date_time\":\"2016-10-12 18:39:30\"}}"; 
    PlansResponse plansResponse = gson.fromJson(jsonString, PlansResponse.class); 

    assert plansResponse.status == true; 
    assert plansResponse.plans.size() == 2; 
} 

class PlansResponseDeserializer implements JsonDeserializer<PlansResponse> { 

    private String getElementAsString(JsonObject jsonObject, String key) { 
     JsonElement element = jsonObject.get(key); 
     return element.getAsString(); 
    } 

    @Override 
    public PlansResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
     PlansResponse plansResponse = new PlansResponse(); 

     List<Plans> plansList = new ArrayList<>(); 
     Gson gson = new Gson(); 
     Type type = new TypeToken<Map<String, JsonObject>>(){}.getType(); 
     Map<String, JsonElement> map = gson.fromJson(json, type); 

     for(Map.Entry<String, JsonElement> entry : map.entrySet()) { 
      String key = entry.getKey(); 

      if("success".equals(key)) { 
       JsonPrimitive jsonPrimitive = (JsonPrimitive) entry.getValue(); 
       plansResponse.status = jsonPrimitive.getAsBoolean(); 
       continue; 
      } 

      JsonObject jsonObject = (JsonObject)entry.getValue(); 
      String typ_firstString = getElementAsString(jsonObject, "typ_first"); 
      String typ_last = getElementAsString(jsonObject, "typ_last"); 
      String order_date_time = getElementAsString(jsonObject, "order_date_time"); 
      plansList.add(new Plans(typ_firstString, typ_last, order_date_time)); 
     } 
     plansResponse.plans = plansList; 
     return plansResponse; 
    } 
} 
+0

Comment puis-je formater une date comme ceci '2016-10-11 19: 20: 03' à ce' 11.10.2016' –

+0

lire à propos de 'SimpleDateFormat': h ttps: //www.mkyong.com/java/java-date-and-calendar-examples/ – RadekJ

+0

Et je peux le faire avec ma chaîne json aussi? –