Android : Missing file through getAssets

on Thursday, October 9, 2014


I have a problem connected with reading a file in Java Application. Please help me as I'm trying to do it for four days and my CS teacher is not into Android Apps. Also any of the tutorials read does not help me.


I have a following function readFile and init() [I show only a part]:



Question[] readFile(String fileName) throws IOException {
String line, content,a,b,c,d,correct;
int id, x = 0;
StringTokenizer st = null;
BufferedReader br = null;

//opens the file to read
try {
br = new BufferedReader(new FileReader(fileName));
}
catch(FileNotFoundException fnfe) {
//JOptionPane.showMessageDialog(null,"There is NOT such a file!");
}
try {
if((line=br.readLine())==null){ // checks if the file is empty
// JOptionPane.showMessageDialog(null,"Data File is empty!");

}
else { // reads the file if not empty
//int size = Integer.parseInt(line);
//array = new Person[size];
}

while((line=br.readLine())!=null) {

st= new StringTokenizer(line, ",");
id = Integer.parseInt(st.nextToken());
content = st.nextToken();
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
d = st.nextToken();
correct = st.nextToken();

questions[x++] = new Question(id, content, a, b, c, d, correct);
}
}
catch(NullPointerException npe){}
br.close();
return questions;
}
// http://stackoverflow.com/questions/5771366/reading-a-simple-text-file
public void init()
{
//questions = new String[]{"What is the capital of Egypt?","What class are you in right now?"};
//answers = new String[]{"Cairo","IST380"};
//currentQuestion = -1;
// TextView ecie = (TextView)findViewById(R.id.QuestionTextView);
answerButton = (Button)findViewById(R.id.AnswerButton);
questionButton = (Button)findViewById(R.id.QuestionButton);
questionView = (TextView)findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
buttonA = (Button)findViewById(R.id.buttonA);
buttonB = (Button)findViewById(R.id.buttonB);
buttonC = (Button)findViewById(R.id.buttonC);
buttonD = (Button)findViewById(R.id.buttonD);

AssetManager assetManager = getAssets();
String [] files=null;
try {
files = assetManager.list("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
questions = readFile(files[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


It is taken from Java application I was writing previously (that is why so many comments). How I can access the fileName in Android App? I was trying InputStream, get Assets, etc. but It does not work or I am doing it improperly. Currently it is throwing NullPointerException.


0 comments:

Post a Comment