gpt4 book ai didi

android - 单例构造函数使我的应用程序崩溃

转载 作者:行者123 更新时间:2023-12-03 16:30:08 25 4
gpt4 key购买 nike

我正在测试应用程序的模型层,并且想向列表中添加元素。但是,每当我尝试向数据模型中添加一些数据时,应用程序就会崩溃。我找不到原因。

我的数据模型代码。

public class DataModel {


private List<Log> logs;
private static DataModel instance;
private Context ctx;


//Singleton constructor
private DataModel()
{
//This makes it crash
logs.add(new Log("1234","sms", 123545, 1, 0));

//Load logs from database - Not done yet.

}

public static DataModel getInstance()
{
if (instance == null)
{
//Creates the instance
instance = new DataModel();
}
return instance;
}

我的日志代码
public class Log {


private String phonenumber;
private String type;
private long date;
private int incoming;
private int outgoing;
private long id;

//Constructor for incoming sms or call
public Log( String Phonenumber, String Type, long Date, int Incoming, int Outgoing)
{

this.phonenumber = Phonenumber;
this.type = Type;
this.date = Date;
this.incoming = Incoming;
this.outgoing = Outgoing;
}


public long getId()
{
return id;
}

public void setId(long id)
{
this.id = id;
}

public String getPhonenumber()
{
return phonenumber;
}

public void setPhonenumer(String phonenumber)
{
this.phonenumber = phonenumber;
}

public String getType()
{
return type;
}

public void setType(String type)
{
this.type = type;
}

public long getDate()
{
return date;
}

public void setDate(long date)
{
this.date = date;
}

public int getIncoming()
{
return incoming;
}

public void setIncoming(int incoming)
{

this.incoming = incoming;

}

public int getOutgoing()
{
return outgoing;
}

public void setOutgoing (int outgoing)
{

this.outgoing = outgoing;
}

最佳答案

您没有初始化logs。执行以下语句时其null:

logs.add(new Log("1234","sms", 123545, 1, 0));

更改:
private List<Log> logs;

至:
private List<Log> logs = new ArrayList<Log>();

关于android - 单例构造函数使我的应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19062829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com