[英]Unable to add strings into arrayList
我可以知道為什么嗎? 我已經將三個字符串傳遞給addTab方法,並且在調試時它存在於變量中,但它說它為null,為什么呢? 我還實例化了arrayList
public class STFile implements Serializable{
private ArrayList<String> qnsTitle;
private ArrayList<String> qnsImagePath;
private ArrayList<String> qnsSoundPath;
private Boolean fileExist;
//Constructor for STFile,gets existing data files if exists and load values from it to data files arraylists, if dont exist
//arraylists for data file will be instantiated.
public STFile()
{
setFileExists(checkIfAllFileExist());
if(getFileExist())
{
try {
setQnsTitle(STFile.readFile(STMain.TITLES_PATH));
setQnsImagePath(STFile.readFile(STMain.IMAGES_PATH));
setQnsSoundPath(STFile.readFile(STMain.SOUNDS_PATH));
}catch(IOException e)
{
System.out.println("in class STFile, IOEXception");
}catch(ClassNotFoundException e)
{
System.out.println("in class STFile, ClassNotFoundException");
}
}else
{
File titleFile = new File(STMain.TITLES_PATH);
File imageFile = new File(STMain.IMAGES_PATH);
File soundFile = new File(STMain.SOUNDS_PATH);
qnsTitle = new ArrayList<String>();
qnsImagePath = new ArrayList<String>();
qnsSoundPath= new ArrayList<String>();
}
}
public void addTab(String title,String imagePath,String soundPath)
{
getQnsTitle().add(title);
getQnsImagePath().add(imagePath);
getQnsSoundPath().add(soundPath);
try {
writeFiles();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("in STFile addtab Exception");
e.printStackTrace();
}
}
public static ArrayList<String> readFile(String filePath) throws ClassNotFoundException, IOException
{
ArrayList<String> arraylist = new ArrayList<String>();
ObjectInputStream obj_in = null;
FileInputStream f_in = null;
try {
f_in = new FileInputStream(filePath);
obj_in = new ObjectInputStream (f_in);
arraylist = (ArrayList<String>)obj_in.readObject();
return arraylist;
}catch(Exception e){
return null;
}finally{
f_in.close();
obj_in.close();
return null;
}
}
主要方法。
STFile file = new STFile();
file.addTab("Title", "image", "sound");
它不斷拋出
Exception in thread "main" java.lang.NullPointerException
at STFile.addTab(STFile.java:53)
at STMain.main(STMain.java:18)
您的readFile
方法將始終返回null,因為您必須return null;
在你的最終塊。
因此,如果文件存在,則qnsTitle
(等)將為null,稍后導致NullPointerException
。
我強烈建議您也不要像在readFile
那樣捕獲Exception。 僅在必須這樣做時才捕獲特定的異常-但是在這種情況下,我不會放在第一位,或者可能只是將其包裝在其他異常中。 簡單地從catch
塊返回null
可以掩蓋出問題的事實,並進一步引入另一個問題。 我建議您只是擴展方法的throws
子句(例如,包含IOException
)並刪除catch塊。
return null;
在readFile
中的finally
塊中可能是問題,請嘗試將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.