I am kind of learning android...and I would like to know if there is a way to access 3 letter words or 4 letter words or some specif type of words at random from the android User Dictionary class??Considering the fact that android has an auto correct feature I'm guessing it also has a dictionary in it...thus how do I use that...where can I find a proper tutorial?
i have no idea about the code...searched around a lot...please help me with the code and also the explanation possibly :)
I don't know how to access the android dictionary but you can have a "custom" dictionary as a txt file in the app's assets folder. This link has several word lists from around 20,000 words to 200,000 words. You could find more lists with google.
Afterwards, you can read the txt file and add it to an Array List if it matches the word length. A random word can then be selected from the dictionary list. The following code will create the dictionary and select a random word from it.
private ArrayList<String> dictionary;
private int wordLength; //Set elsewhere
private void createDictionary(){
dictionary = new ArrayList<String>();
BufferedReader dict = null; //Holds the dictionary file
AssetManager am = this.getAssets();
try {
//dictionary.txt should be in the assets folder.
dict = new BufferedReader(new InputStreamReader(am.open("dictionary.txt")));
String word;
while((word = dict.readLine()) != null){
if(word.length() == wordLength){
dictionary.add(word);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dict.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Precondition: the dictionary has been created.
private String getRandomWord(){
return dictionaryList.get((int)(Math.random() * dictionaryList.size()));
}
Related
In this portion of my app, I have a database which is absorbing data from my light sensor. It has a RowID associated with each row.
In the background I have an AsyncTaskRunner which is reading that table and writing each row to a CSV file. It should loop through the entire table as data is being written to it, looking for all rows for the current TID that have not been copied to CSV. THen it should write the row values to CSV and go back and mark the row as copied.
THe first loop should come in where no it goes back to the database cursor and looks for the next row which has not been copied to the CSV file. After each copy to CSV it should evaluate the size of that CSV file to make sure it is not full. If not Full then should go back to the Database cursor and look for the next row to write to the CSV file. If isfull then it should loop back to LoopMain and start over creating a new CSV file to write to.
While the full method is not complete yet, I am at the part where the row data is suposed to be written to the CSV file. At the moment, it does not write to it. Before I made this method a For Loop, it did, now it does not. I can not figure out what has changed. I have inserted all of these Log comments to follow the method as it passes values, receives values and then does an action to see where it is failing. THe method passes the section where it is to write to the CSV file and continues on, but the file is empty.
public void lightloop(){
//Loop Main
int loopcounter;
LoopMain: for(loopcounter = 0; loopcounter < 4; loopcounter++ ){
Log.d(CSV, "lightloop loopcounter = " + loopcounter);
String CSVFinalFileName=createlightcsv();
Log.w(CSV, "LightLoop, CSVFinalFileName = " + CSVFinalFileName);
//Loop 2
Loop2: for(int useless=1; useless > 0; useless++ ){
String flightRowId = evaluateLightTable(filenamePrefix); //returns the rowid of the first line not transmitted
Log.w(CSV, "LightLoop, flightRowId = " + flightRowId);
Log.d(CSV, "filefullBoolean " + useless);
if(flightRowId != null){
Log.w(CSV, "LightLoop flightRowId is NOT NULL");
//write row to csv
//Get all row values and put into a string
String lightRowValues=fetchLightRowData(flightRowId, filenamePrefix);
Log.w(CSV, "lightLoop, lightRowValues are " + lightRowValues);
//Append that data to the CSV file
Log.w(CSV, "Opening File Output Stream");
try {
FileOutputStream csvfos = mContext.openFileOutput(CSVFinalFileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
OutputStreamWriter sensorCSVWriter = new OutputStreamWriter(csvfos);
try {
sensorCSVWriter.append("LIGHT " + lightRowValues);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/** try {
sensorCSVWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} **/
//mark row as transmitted
SQLDatabase updatelightrow = new SQLDatabase(mContext);
updatelightrow.open();
SQLDatabase.updateLightRow(flightRowId);
updatelightrow.close();
}// end If rowid is not null
//evaluate size of csv
Boolean filefull = CsvStreamer.checkFileSize(CSVFinalFileName);
if(!filefull){
//return to cursor
Log.d(CSV, "lightloop, File is NOT full");
break Loop2;
}else{
Log.d(CSV, "lightloop, File IS full");
//file is full. close it,
//transmit it,
//open a new one
//goto CSV table and mark it transmitted
break LoopMain;
}
}//end Loop2
}//end LoopMain
}
Can anyone see why this is failing to write to the File?
The csvfos is not in the same scope. I assume the class has a property called csvfos also, hence the method is accessing the property and not the csvfos variable created in the try catch.
Try changing
try
{
FileOutputStream csvfos = mContext.openFileOutput(CSVFinalFileName, Context.MODE_PRIVATE);
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
to
FileOutputStream csvfos = null;
try
{
csvfos = mContext.openFileOutput(CSVFinalFileName, Context.MODE_PRIVATE);
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
Is it possible to write a whole shared_preferences.xml at once?
I want to realize a kind of settings import/export, so i need to read and write the whole file without loosing the xml-tags.
Reading the file is easy, but when i write my values (using PrintWriter) the old values stored in memory overwrite them seconds later.
what can i do to prevent that without writing single values using preference editor.
Now I read it from a file designed like Android's own preferences.xml and write it successively in my own function like this:
public static void preferencesImport(String PreferenceFilepath) {
preferencesImportPreferenceFilepath = PreferenceFilepath;
try {
// Parsing
// see http://theopentutorials.com/tutorials/android/xml/android-simple-xml-dom-parser/
XMLParserHelper parser = new XMLParserHelper(); // reference to described XMLDOMParser helper class
BufferedInputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(preferencesImportPreferenceFilepath));
org.w3c.dom.Document doc = parser.getDocument(stream);
// string value
NodeList nodeListString = doc.getElementsByTagName("string");
for (int i = 0; i < nodeListString.getLength(); i++) {
Element eString = (Element) nodeListString.item(i);
Pref.setString(eString.getAttribute("name"), eString.getTextContent()); // Own getter/setter -> use Android's preference manager instead in similar way
}
// repeat code above for boolean, long, int, float values
stream.close();
} catch (IOException e1) {
// output IOException
} catch (Throwable t1) {
// output Throwable1
}
writer.close();
} catch (Throwable t2) {
// output Throwable2
}
}
This question already has answers here:
how to faster read text file to ArrayList on android
(2 answers)
Closed 9 years ago.
Here is the code of function:
public void loadTextFile(String textFileName, ArrayList<String> dictionary)
{
AssetManager assetManager = getAssets(); //files manager
//reader = public bufferedReader
//word = public String
//dictionary = public ArrayList<String>
//load file to buffer
try {
reader = new BufferedReader(new InputStreamReader(assetManager.open(textFileName)));
} catch (IOException e1) {
e1.printStackTrace();
}
word = " ";
//loop, save words from buffer to dictionary
while(word != null)
{
try {
word = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
word = null;
}
if (word != null) {
dictionary.add(word);
}
}//end while
//buffer close
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} //end function
If I try load small file <1MB, It works fine and rather fast.
If the files(partialy) are more than 1MB, but less than about 3MB, it works slow (4-6min).
If the files are bigger, it's not working, and I have information in emulator:
"The application app (process processing.test.app) has stopped unexpectedly. Please try again". I don't know what is wrong.
I try: pre-allocated ArrayList, load file to few ArrayList's, but still not working.
I will be grateful for any suggestions.
First off, word can become null somewhere along the file and the loop will exit (since you explicitly set word to null on an exception). Do you get a stack trace?
Try to move the code to a background process using AsyncTask AsyncTask
Execute on real device if you have one
my history objects only have 2 fields (id + name). i have to save them. i used sharedpreferences because this is just perfect to save key-value pairs. problem is..there is no possibilty to change to location where the files are saved. i dont want to save them into the sharedpref folder because i want to give the user of the app the possibility to delete all history entries. i have to check which files are history files and which files are preferences files used by the app. this is no proble..but dirty imo. on the other hand..my history files shouldnt be in sharedpref folder..they have nothing to do in that folder..
the other possibility is to store the data in internal storage as xml for example. i would have to write a serializer and parser.
the third possibility (i just remembered writing this question)is to save it via Java Properties. this is probably the easiest solution. its like sharedpref
the last possibility is to store it in sqlite. i dont know..my data is so tiny..and i use a databae to store it?
my question is simply..what do u recommend to use and why. what do you use? same question belongs to the autocomplete values. id like to save the values the user once entered in a textfield. where to save them? where do you save such data?
thx in advance
You can create a separate sharedpreferences file for your history using (say) Context.getSharedPreferences("history") which will create a sharedpreferences file as follows.
/data/data/com.your.package.name/shared_prefs/history.xml
But I'm pretty sure that all sharedpreferences files will be created in /data/data/com.your.package.name/shared_prefs/. I don't think you can change the location.
I may be mis-interpreting your objective but for something like this I would just straight-up use a BufferedWriter from java.io.BufferedWriter to write a new file for each object. Likewise you can read the data with a BufferedReader. The code would look something like this:
public static void save(FileIO files){
BufferedWriter out = null;
try{
//use a writer to make a file named after the object
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(objectSomething)));
//the first line would be ID
out.write(Integer.toString(objectID));
//second line would be the name
out.write(objectName)
//Theres two possible IOexceptions,
//one for using the writer
//and one for closing the writer
} catch (IOException e) {
} finally {try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this example, I have used "objectSomething" as the string name of the file, objectID and objectName are the int and string respectively that your file contains.
to read this data, pretty straightforward:
public static void load(FileIO files) {
BufferedReader in = null;
try {
// Reads file called ObjectSomething
in = new BufferedReader(new InputStreamReader(
files.readFile(ObjectSomething)));
// Loads values from the file one line at a time
varID = Integer.parseInt(in.readLine());
varName = in.readLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
here, I've used varID and varName as local variables in this class that you would use if you needed them in your code throughout your application.
I have a CSV file in drawable/asset folder. In the CSV file there are four columns. First one is for date and rest three are for integer data.
I need to parse this CSV file and save the data in separate arrays.
I have searched for a solution, but I don't get proper idea on how to do this.
I like this csv reader: https://mvnrepository.com/artifact/net.sf.opencsv/opencsv/2.3
Just add it to your project.
Example code (assuming there is the file assets/test.csv):
String next[] = {};
List<String[]> list = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("test.csv")));
while(true) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
You can access the imported data with, for example,
list.get(1)[1]
That would return a string.