简单的安卓翻译应用程序不工作



我做了一个简单的Java CLI程序作为作业,现在我正试图把它变成一个Android应用程序的乐趣/体验。然而,它不起作用……这是一个翻译应用,当我输入一个我知道在字典里的单词时如果用户输入了一个无效的单词它仍然会给我我输入的信息。我认为发生的事情是它没有正确地读取字典文件,因为Eclipse的LogCat在运行时给了我以下消息:"无法打开文件进行读取。"

public class MainActivity extends Activity {
TreeMap<String, String> tree = new TreeMap<String, String>();
public final static String EXTRA_MESSAGE = "";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Scanner dictinput = null;
 try{
     getAssets().open("dict.txt");
    dictinput = new Scanner(getAssets().open("dict.txt"));
 }
 catch (Exception e) {
        System.err.println("Could not open file");
        System.exit(-1);            
 }//Puts the dictionary in a stringbuffer
 StringBuffer dict = new StringBuffer();
 String[] arrtemp = new String[1600];
 while(dictinput.hasNext()) {
     dict.append(dictinput.nextLine());
     dict.append("|");
 }//Then puts it in a string so it can be split at the |'s using .split
 String strstr = dict.toString();
 arrtemp = strstr.split("\|");
 //puts the dictionary into a treemap
 for(int i=0; i<arrtemp.length-1; i++) {
     if(i==0)
         tree.put(arrtemp[i].toLowerCase(), arrtemp[i+1]);
     else {
         i++;
         tree.put(arrtemp[i].toLowerCase(), arrtemp[i+1]);
     }
 }
}
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editmessage);//The only way I've         found to get the text from the user.
    String temp = editText.toString();
    Scanner scan = new Scanner(temp);
    String finalmessage = null;
    while(scan.hasNext()){
     String temp1 = scan.next();
     if (tree.containsKey(temp1.toLowerCase()))
        finalmessage = temp;
     else
         finalmessage = "No match found, try another word or phrase";
 }

    intent.putExtra(EXTRA_MESSAGE, finalmessage);
    startActivity(intent);
}

任何帮助都将非常感激。

您的文本文件位于哪里?我想问题可能是它没有保存在项目文件夹的/res/raw下,之后你可以使用输入流,如:

        InputStream is = this.getResources().openRawResource(
            R.raw.textfilename);
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        while(blah){
           do stuff
        }
    }
    catch(Exception e){
        handle errors
    }

相关内容

最新更新