我已经解析了JSON文件,因此我想要的文本在HashMap中。如何在选项卡中显示此文本?还是有一种方法可以将JSON文件中的字符串作为strings.xml文件中的字符串变量?
编辑:这是我解析数据和onCreate方法的主要类的大部分代码
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Dining Hall Menu";
private List<String> days = Arrays.asList("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
private LinkedHashMap<String, String> menu = new LinkedHashMap<>();
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
private int[] tabIcons = {
R.drawable.ic_action_name,
R.drawable.ic_action_tomorrow,
R.drawable.ic_action_week
};
public void readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
readMessagesArray(reader);
} finally {
reader.close();
}
}
public void readMessagesArray(JsonReader reader) throws IOException {
int count = 0;
reader.beginArray();
while (reader.hasNext()) {
readMessage(reader, count);
count++;
}
reader.endArray();
}
public void readMessage(JsonReader reader, int count) throws IOException {
String day,food;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("Monday") || name.equals("Tuesday") || name.equals("Wednesday")
|| name.equals("Thursday") || name.equals("Friday")
|| name.equals("Saturday") || name.equals("Sunday")) {
day = name;
food = reader.nextString();
if (count == 0) {
menu.put(day, food);
} else if (count == 1) {
menu.put(day, menu.get(day) + food);
} else {
menu.put(day, menu.get(day) + food);
}
} else {
reader.skipValue();
}
}
reader.endObject();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
InputStream in = getAssets().open("Week11.json");
readJsonStream(in);
}
catch(IOException e) {
e.printStackTrace();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting");
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
setupTabIcons(tabLayout);
}
答案 0 :(得分:0)
例如:-
@SerializedName("variableName")
String variableName;
void getVariableName() {
return variableName;
}
然后使用构造函数在Fragments中传递Serializable对象,并通过上述创建的getter方法使用Fragments中的值。