我需要有关 RecyclerView 的帮助。我的 SQL 数据库中有一个 atring 数组,如下所示:
{"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"}}
在我的 RecyclerView 中,我有以下字段:
订单号
typ_all
(输入第一个和最后一个)日期
(只有日期,没有时间)
这就是我获取字符串数组的方式:
String plansData = plansPreferenceData.getString("plansPreferenceData", "");
这就是我将数据设置到 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();
我的计划
类(class):
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;
}
}
我的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;
}
我的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();
}
我的问题是如何将字符串数组中的信息获取到我的适配器中?我还需要在添加之前格式化日期。感谢您的帮助!
最佳答案
在这里了解Gson:
http://guides.codepath.com/android/leveraging-the-gson-library
之后您将能够编写这样的代码:
Type type = new TypeToken<Map<Integer, Plans>>(){}.getType();
Map<Integer, Plans> myMap = gson.fromJson("your json from db", type);
并在你的适配器中使用这个map.values()
您的Plans
类应如下所示:
class Plans {
String order_number;
String typ_first;
String typ_last;
String order_date_time;
}
如果您想要其他字段名称,则必须使用@SerializedName
注释
最后,你应该写这样的东西,(我不知道语法是否100%现在没有打开IDE):
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();
}
并修改您的模型类:
public class Plans {
@SerializedName("order_number")
String planTitle;
@SerializedName("typ_last")
String planType;
@SerializedName("order_date_time")
String planDate;
....
希望对你有帮助。
关于java - Android 中的 Json 文本到 RecyclerView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42010427/