Java 如何有效地将此字符串转换为列表(Android)?
我一直在写这个Android程序,首先,你需要写一些名字,电子邮件地址和电话号码,我有这个字符串,我需要把它变成一个列表,以便能够在ListView中显示它。我查了很多东西,结果都不一样,不是我想要的方式 下面是处理字符串的部分(先作为JSONObject,然后作为JSONArray),以便您可以看到它的外观:Java 如何有效地将此字符串转换为列表(Android)?,java,android,Java,Android,我一直在写这个Android程序,首先,你需要写一些名字,电子邮件地址和电话号码,我有这个字符串,我需要把它变成一个列表,以便能够在ListView中显示它。我查了很多东西,结果都不一样,不是我想要的方式 下面是处理字符串的部分(先作为JSONObject,然后作为JSONArray),以便您可以看到它的外观: public static void addFriend(Context c, String name, String number, String email) { try {
public static void addFriend(Context c, String name, String number, String email) {
try {
if (friends == null) {
friends = new JSONObject();
friends.put("array", new JSONArray());
}
JSONArray array = friends.getJSONArray("array");
JSONObject friend = new JSONObject();
friend.put("name", name);
friend.put("phone number", number);
friend.put("email", email);
array.put(friend);
FileOutputStream fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(friends.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
下面是它的内容:
public static void printAllBytes(Context c){
try {
FileInputStream fis = c.openFileInput(FILENAME);
String readedBytes = new String(readAllBytes(fis), "UTF-8");
System.err.println(readedBytes);
} catch (Exception e){
e.printStackTrace();
}
}
“System.err.println(readedBytes)”打印的结果是:
(我输入了一个随机的名字,电子邮件和电话号码来测试它)。
我知道,一个接一个地输入多个项目会将它们添加到数组中,这是问题的一部分,但当涉及到将项目放入列表时,我就被难倒了。我不想使用for循环,这对我来说效率很低
提前感谢:)
-Leon考虑将变量存储到对象中,而不是JSON中
public class Person {
String mName;
String mNumber;
String mEmail;
}
一旦您这样做了,您就可以创建一个ArrayAdapter,它接受您的对象并将其映射到自定义XML
本文提供了有关ListView如何工作的更多详细信息:。为什么不创建一个包含所有变量的Person类,然后将Person实例添加到列表中?
public class Person {
String mName;
String mNumber;
String mEmail;
}