【问题标题】:Read from text file using array - Android Studio使用数组从文本文件中读取 - Android Studio
【发布时间】:2016-05-05 13:48:12
【问题描述】:

我在尝试从文本文件中读取多个联系人时需要帮助。我看过一些教程,但数据是硬编码的,没有保存在文本文件中。我的文本文件名为“mytextfile.txt”。这是我所有的数据都被保存了。现在我想在列表视图中显示它。到目前为止,这就是我结束的地方。有人可以帮忙吗?我是 Android Studio 的新手。谢谢

public class AllContacts extends Activity implements AdapterView.OnItemClickListener{

ListView l;
String[] contacts={mytextfile.txt};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_contacts);

    l=(ListView) findViewById(R.id.listView);
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);
    l.setAdapter(adapter);
    l.setOnItemClickListener(this);

}

public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
    TextView temp=(TextView) view;
    Toast.makeText(this, temp.getText()+""+i,Toast.LENGTH_SHORT).show();
}

}

【问题讨论】:

    标签: java android arrays list listview


    【解决方案1】:

    您可以使用 File.lines 来使用文件的路径返回文件内容流:

        File fileContact = new File("Indicate you path to the file here");
        String[] contacts = null;
        try {
           contacts = (String[]) Files.lines(fileContact.toPath())
                                      .filter(s -> !s.isEmpty())
                                      .toArray();
        } catch (IOException e) {
        // cant read the file
          e.printStackTrace();
        }
    

    我添加了一个过滤器,用于检查您的文件 contact.txt 中的每一行是否为空

    【讨论】:

      【解决方案2】:

      您做错了,您不能通过将 tge 名称放入数组中来获取文件中的数据,您需要读取文件的内容,因此只需阅读此 official document 以了解如何在 android 中处理不同的数据存储

      【讨论】:

        猜你喜欢
        • 2018-08-17
        • 2015-07-25
        • 1970-01-01
        • 2019-01-11
        • 1970-01-01
        • 2017-08-15
        • 2011-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多