【问题标题】:How do I code the app to read data values from a file to the class object?如何编写应用程序以将数据值从文件读取到类对象?
【发布时间】:2015-02-23 16:54:58
【问题描述】:

我被困住了。我不知道如何从文件中读取数据值到类对象。我必须为 Employee 类的三个引用做这件事。这是我目前所拥有的:

public void displayEmployees(View view)
{
    EditText edt1;
    TextView tv;
    String urlfile; //For variable that stores the user input for url address

    edt1 = (EditText) findViewById(R.id.edit_file);

    tv = (TextView) findViewById(R.id.text_main);

    //Declare references to class Employee
    Employee e1;
    Employee e2;
    Employee e3;

    //Create three objects for class Employee
    e1 = new Employee();
    e2 = new Employee();
    e3 = new Employee();

    //Retrieve what user has input
    urlfile = edt1.getText().toString();



    //Open and read the data values from a file on the web

    try
    {
        //Create URL object
        URL file_url = new URL(urlfile);

        //try to open the file from the web
        Scanner fsc = new Scanner(file_url.openStream());

    }
    catch(IOException e)
    {
        tv.setText("Error: Invalid URL Address or File Does Not Exist");
    }
}

而且,这就是类的样子:

public class Employee {
    private String name;
    private String id;
    private double salary;
    private String office;
    private String extension;
    private int yearsofservice;

public String getName()
{
    return name;
}
public void setName(String n)
{
    name = n;
}
public String getId()
{
    return id;
}
public void setId(String ID)
{
    id = ID;
}
public double getSalary()
{
    return salary;
}
public void setSalary(double Salary)
{
    salary = Salary;
}
public String getOffice()
{
    return office;
}
public void setOffice(String Office)
{
    office = Office;
}
public String getExt()
{
    return extension;
}
public void setExt(String Extension)
{
    extension = Extension;
}
public int getYearsOfServ()
{
    return yearsofservice;
}
public void setYearsOfServ(int YearsOfService)
{
    yearsofservice = YearsOfService;
}

}// end class Employee

最后,我正在读取的文件如下所示,例如:

乔·鲍勃 00001 9000.00 校园大厅 9999 5

【问题讨论】:

    标签: java android class url


    【解决方案1】:

    我宁愿使用 SQlite 来持久化员工信息。

    对于您的问题,您需要编写自己的解析逻辑。

    供阅读check this question

    【讨论】:

      【解决方案2】:

      按照以下步骤操作
      1)连接数据源。
      2)在源端制作一个模型类作为getter和setter。
      3)创建该类的对象并使用设置器插入所有值。
      4)如果您正在使用,则将该对象添加到集合(List,Map,Set)中(制作返回对象
      5)在Android应用程序上得到相同的签名,这是服务器端值设置器的返回类型。

      6)在 android 站点中,您可以执行类似假设您正在获取 ArrayList 的操作

      for(int i=0;i<yourArrayList.size();i++){
      VarType var=yourArrayList.get(i).getFirstSetvalue();
      VarType var2=yourArrayList.get(i).getSecondValue()
      //do what you want
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-09
        • 1970-01-01
        • 1970-01-01
        • 2013-05-24
        • 2021-11-02
        • 2013-06-22
        • 1970-01-01
        相关资源
        最近更新 更多