这是主要活动 我试图将类移动到一个新文件 一旦我这样做,我就无法成功召集课程 以下代码生成空指针,但指针不为null 我不能简单地将savedTrainInfo类更改为static,因为 然后文件例程将无法正常工作。必须有一个简单的解决方案 为清晰起见,我需要将我的课程分开。
import mp.trains.conductor.savedTrainInfo;
public class trains extends Activity
{
private savedTrainInfo msavedTrainInfo;
protected static Context context;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
trains.context=getApplicationContext();
msavedTrainInfo=new savedTrainInfo();
msavedTrainInfo.getTrainAttributes();
}
}
新文件 这里有很多功能;主要是文件I / O. 如果位于主要活动列车中,这些都可以正常工作 你是对的。错误似乎在if(readStartupFile(trainAttributes)== false)
public class savedTrainInfo extends trains
{
public void getTrainAttributes()
{
trainAttributes=new String [10];
if (readStartupFile(trainAttributes)==false)
{
fileLine=0;
}
else
{
try
{
fileLine = Integer.parseInt(trainAttributes[0].toString());
}
catch(NumberFormatException nfe)
{
System.out.println("Could not parse " + nfe);
}
}
}
public boolean readStartupFile(String objects[])
{
try
{
// InputStream fHandle = openFileInput("startupTrains.txt");
InputStream fHandle = trains.context.openFileInput("startupTrains.txt");
if (fHandle != null)
{
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(fHandle);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
line = buffreader.readLine();
if (line == null)
{
fHandle.close();
return false;
}
else
{
String[] item = (line).split(",");
objects[0]=item[0].toString();
fHandle.close();
}
return true;
}
else
{
return false;
}
}
catch (FileNotFoundException e2)
{
return false;
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
}
}