简体   繁体   中英

How can I load in this text file using Java in an Android Application, in an external class?

I've got a text file that has 173,139 words delimited by newlines. Basically, I need to load this 1.7mb file into an array of strings, for easy access. I'm trying to do this in onCreate() for the main activity, which might cause problems of its own because it might make starting the application really slow, but right now I'm just trying to load in the dictionary, I suppose.

I looked up the problem and found that I should use asset manager for this problem, so here's what I have in my Dictionary class:

public class Dictionary {
    private String[] dictionary = new String[173139];
    private String[] acceptedWordsList = new String[173139];
    private String acceptedWords = "";

    public Dictionary(Context context){
        AssetManager am = context.getAssets();
        try {
            String rawText;
            int element = 0;
            InputStream is = am.open("words.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            while((rawText=reader.readLine()) != null){
                dictionary[element++] = rawText;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

and I'm instantiating a Dictionary in my Main Activity in pretty much the first line in the class:

public class MainActivity extends Activity {
    Dictionary dictionary = new Dictionary(this);
    //rest of application code
}

What am I doing wrong here? I've also tried instantiating a Dictionary like this:

Dictionary dictionary = new Dictionary(this.getApplicationContext());

as well as:

Dictionary dictionary = new Dictionary(getApplicationContext());

but all of these seem to cause fatal errors in my application.

So two final questions: is it okay to instantiate in the beginning of the application code like that? And if so, why doesn't that code work when I'm trying to do so?

edit: I was asked for logcat output. My apologies, this is my first "real" android program. I don't know if this is exactly what you're looking for, but I don't want to omit anything that might be helpful either:

http://pastebin.com/raw.php?i=c99LFZzx

Just a thought: your context.getAssets call throws the NPE (possibly because context is null).

I think that's because you did not put Dictionary dictionary = new Dictionary(this); in the onCreate method actually.

I would expect it to work (provided the file is there) if you put that code on onCreate , after super.onCreate(bundle) .

If you are worried about app initialization loading time, I suggest you use an AsyncTask to load your dictionary in a splash activity, so you can provide user feedback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM