如何有效地将此字符串转换为列表(Android)?

时间:2015-09-30 16:39:28

标签: java android

我一直在写这个Android程序,首先,你需要写几个名字,电子邮件地址和电话号码,我有这个字符串,我需要变成一个列表,以便能够显示它列表显示。我查了很多东西,结果却不同,而不是我想要的方式。

这是接受字符串的部分(作为JSONObject,然后是JSONArray),以便您可以看到它的样子:

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)”打印的结果是:

{"array":[{"name":"le on","phone number":"1337","email":"leon"}]}

(我输入一个随机名称,电子邮件和电话号码来测试它)。 我知道在一个接一个地输入多个东西会将它们添加到数组中,这是关键点的一部分,但是当把它们放入列表中时,我只是难倒了。我不想用for循环来做这件事,这对我来说似乎效率低下。

提前致谢:) -Léon

1 个答案:

答案 0 :(得分:0)

考虑将变量存储到对象而不是JSON中。

public class Person {
    String mName;
    String mNumber;
    String mEmail;
}

一旦你这样做,你就可以创建一个ArrayAdapter,它接收你的对象并将它映射到一个自定义的XML。

本文提供了有关ListView如何工作的更多详细信息:http://www.vogella.com/tutorials/AndroidListView/article.html

相关问题