我在我的一项活动的 onCreate 方法中有此代码
GetNews newsReporter = new GetNews(getApplicationContext());
try{
News[] allNews = newsReporter.getAllNews();
Log.d("News Count", String.valueOf(allNews.length));
String[] timestamps = new String[allNews.length];
String[] texts = new String[allNews.length];
for(int i=0;i<allNews.length;i++)
{
// timestamps[i] = allNews[i].getNewsTime();
texts[i] = allNews[i].getNewsText();
// Log.d("TimeStamp", timestamps[i]);
Log.d("Text", texts[i]);
}
}catch(Exception e){
Log.e("Error News", e.toString());
}
News Count 在 Logcat 中显示 6,这意味着 News[] 不为空。
但是我在 Line texts[i] = allNews[i].getNewsTime(); 上收到 NullPointerException
这是我的新闻课
public class News {
private int id;
private String timestamp;
private String text;
public News(int i,String t, String ti)
{
this.id=i;
this.text = t;
this.timestamp = ti;
}
public String getNewsTime()
{
return this.timestamp;
}
public String getNewsText()
{
return this.text;
}
}
PS News 存储在 SQLitedatabase 中,当我从 DDMS 中提取数据库时,它包含所有 6 行的有效值,其中没有一个为空。
编辑:这是我的 GetAllNews 方法
public News[] getAllNews(){
SQLiteDatabase db = ConMan.OpenDBConnection();
try{
Cursor cursor = db.query(News_Table, Columns, null, null, null, null, null);
if(cursor!=null)
{
cursor.moveToFirst();
}
News[] allNews = new News[cursor.getCount()];
int i =0;
while(cursor.isLast()){
allNews[i] = new News(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2));
cursor.moveToNext();
i++;
}
db.close();
ConMan.close();
return allNews;
}catch(Exception e)
{
Log.e("News DB Errors", e.getMessage());
}
return null;
}