Reputation: 250
I made a simple Java CLI program for an assignment, and now I'm trying to make it into an Android app for fun/experience. However, it's not working... It's a translation app, and when I put in a word that I know is in the dictionary it still gives me my message I put in for if the user puts in an invalid word. I believe what's happening is it's not ever reading in the dictionary file properly, as Eclipse's LogCat is giving me the following message on runtime: " Can't open file for reading."
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);
}
Any help would be greatly appreciated.
Upvotes: 0
Views: 145
Reputation: 26
Where is your textfile located? I would imagine the problem might be it is not saved under /res/raw in your project folder, after which you can use an inputstream like:
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
}
Upvotes: 1