Accessing wrong raw resource in Android
I have the following code. My idea is in OnCreate, I'll populate some categories from a text file in /res/raw to my database.
First a tokenize the read file by lines (myCatToken), then each of these I split again to get the id and name.
For some reason, instead of reading rat.txt I'm getting a totally different file and I have no idea why. The file that is actually read does exist in the /res/raw folder, however its named different.
It seems that it has something to do with the resource it sends to readTxtFromRaw, however I don't see whats wrong with it.
Thanks
StringTokenizer myCatToken = new StringTokenizer(new String(readTxtFromRaw(R.raw.rat)));
while(myCatToken.hasMoreTokens())
{
StringTokenizer myCatDataToken = new StringTokenizer(myCatToken.nextToken(), ",");
String insertString = new String("insert into " + DATABASE_TABLE_CATEGORIES +
" (" + KEY_CATEGORIES_CATID + ", " + KEY_CATEGORIES_NAME + ") values " +
" (" + myCatDataToken.nextToken() + ", '" + myCatDataToken.nextToken() + "')");
db.execSQL(insertString);
}
For reference I include this method I'm 开发者_JAVA技巧using. mCtx is Context:
private String readTxtFromRaw(Integer rawResource) throws IOException
{
InputStream inputStream = mCtx.getResources().openRawResource(rawResource);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
return byteArrayOutputStream.toString();
}
Clean your Workspace by going to "Project->Clean...". So the whole project will be built again and the generated class your.package.R will be refreshed.
I closed Eclipse and reopened it and it works.
精彩评论