Android - Notepad as database storage - android

I've been given a database of english words but they're in a .txt file. not an sql file.
My professor told me I could use it as database for my dictionary application instead of using sqlite.
Can anybody please give me any idea how to access the notepad?
I need to compare an inputWord to the notepad files and if found, it will copy the definition of the inputWord from the notepad and display it onscreen.

Notepad files have UTF-8 Text String stored in them, what you will have to do is to read the whole file, parse the keywords and their definitions , and then search for any keyword in the list.
a pseudocode for that would look like this:
FileInputStream fis = new FileInputStream("the_file_name");
BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
StringBuilder builder = new StringBuilder();
String line = null;
do {
line = br.readLine();
builder.append(line);
} while (line != null);
parseFile(builder.toString);
public void parseFile(String txt){
....... code to parse the txt from file and pass it to variables to use in the comparison
}

Related

Reading data from a json file BufferedReader returns only null

I'm currently learning android with a books called "Android Programming - The Big Nerd Ranch Guide".
As a part of a learning project we create Json serializer for saving and loading data. Writing the file appearently works fine, and I get no error messages on the Logcat. After I terminate the app and recreate it, the data loader is called and raises the following exception:
org.json.JSONException: End of input at character 0
I've looked for this issue online and figured it's probably because the BufferedReader returns an empty response. I've checked and indeed it is the case.
For simplicity sake, I've temporarily put a BufferedReader into the saving function and tried reading the info I've just saved into the file, and still the BufferedReader returns only null.
public void saveCrimes(ArrayList<Crime>crimes)
throws JSONException, IOException {
JSONArray array = new JSONArray();
for(Crime c: crimes)
array.put(c.toJSON());
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFileName, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
Log.d(TAG, array.toString());
} finally {
if(writer == null)
writer.close();
}
// Extracting the data
BufferedReader bufferedReader = null;
try {
InputStream inputStream = mContext.openFileInput(mFileName);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
if (bufferedReader.readLine() == null)
Log.d(TAG, "WHY GOD WHYYYYYYY");
}catch (IOException e){
}
}
(The two log messages from the code, the first one displays the data that is in the JsonArray I'm using)
D/CriminalIntentJSONSerializer: [{"date":"Mon May 14 17:33:08 GMT+00:00 2018","id":"97fe9532-991f-4352-9de1-602fa8dfa93e","isSolved":true,"title":""}]
D/CriminalIntentJSONSerializer: WHY GOD WHYYYYYYY
Would love to hear your insight.
BufferedReader bufferedReader = null;
try {
InputStream inputStream = mContext.openFileInput(mFileName);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
if (bufferedReader.readLine() == null)
Log.d(TAG, "WHY GOD WHYYYYYYY");
}catch (IOException e){
}
Ok. you've created your BufferedReader bufferedReader = null;
What happens when yuou say bufferedReader = new BufferedReader(anything)...Well...it can't call a new instance the same thing that's already been declared...in fact, it's already been instantiated as null. So you can't create a new instance of the same name.
Try deleting the line where you point it at null. Then, substitute
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for the original declaration in your try block
Try to check if mFilename is empty on second try-catch, usually in Android instance disappear easily.
PD: I advise you choice another JSON library to manipulte JSON files, they are lightweight and easy-to-use.
== Edit ==
Have you added writing and reading permissions on AndroidManifest?
If answer is "there it is" try to debug app step-by-step looking for variables and in-variables for checking existence of values.
Could be file isn't writing itself or it's writing empty.
Error basically is empty string or non-format JSON-like:
""
"[{"a": "abdc", "b": "jef2","
Paying attention to BufferedReader because it read lines each and you need all file and then join into string variable.
Also, try to use android file explorer that come in AndroidStudio. There you can explore files, logs and database files and export them to your specific folders (Documents, Downloads, etc). Generally files written by app are stored in data -> <com.your.app.package>.

Copying a specific string from a website

As an aviation lover, I'm trying to build up an Android App to get METAR/TAF. The main goal of one of the project activities is to go to https://www.aviationweather.gov/adds/metars/, and read the METAR/TAF (METHEOROLOGICAL REPORTS) of the airport the user chooses.
As a draft project I have the following xml (read the info from webpage and pasting it into a textViwe):
TextView tv = (TextView) findViewById(R.id.textview1);
try{
HttpClient cliente = new DefaultHttpClient();
HttpPost poste = new HttpPost("https://www.aviationweather.gov/adds/metars/?station_ids=LELL&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submitmet=Submit");
HttpResponse respuesta = cliente.execute(poste);
HttpEntity entidad=respuesta.getEntity();
InputStream mensaje=entidad.getContent();
StringBuffer sb=new StringBuffer();
String linea;
BufferedReader br=new BufferedReader(new InputStreamReader(mensaje,"UTF-8"));
while((linea=br.readLine())!=null){
sb.append(linea);
sb.append("\n");
}
tv.setText(sb.toString());
mensaje.close();
The main thing is, I read the whole information and get the following text*, but I just want to display the lines (METAR in red , TAF in blue):
Any Idea?
I've tried many codes in this website, even tried to get to the webpage with a WebView , but I'd rather display the metheorological information as a text in TextView.
Thanks in advance,
SERGI
You can use Jsoup with the following to access the text you want
Document doc = Jsoup.connect("https://www.aviationweather.gov/adds/metars/?station_ids=LELL&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submitmet=Submit").get();
Elements fontTags = content.getElementsByTag("font");
for (Element fontTag : fontTags) {
String fontTagText = fontTag.text();
}
Final code:
Document doc = Jsoup.connect("https://www.aviationweather.gov/adds/metars/?station_ids=LELL&std_trans=standard&chk_metars=on&hoursStr=most+recent+only&chk_tafs=on&submitmet=Submit").get();
Elements fontTags = doc.getElementsByTag("font");
for (org.jsoup.nodes.Element fontTag : fontTags){
String frase =fontTags.text();
TextView hola=(TextView)findViewById(R.id.hello);
hola.setText(frase);
}

Separate different Strings from text

I want to read a txt file that contains a lot of different chunks of text separated by a string. In xcode this is pretty easy and i just use.
self.Array = [text componentsSeparatedByString: #"NEWSTRING"];
I don't seem to get this to work in android though, I can read in the whole text and put it into an array but it doesn't get separated so its just one long text.
I am using this code
AssetManager mngr;
String line = null;
boolean skillcheck = false;
StringBuffer sb = new StringBuffer(0);
String[] bb = null;
tester = new ArrayList <String>();
try {
mngr = getAssets();
InputStream is = mngr.open("mytext.txt");
InputStreamReader sir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(sir);
while((line=br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
tester.add(sb);
br.close();
} catch (IOException e1) {
}
Any good ways to do this?
You can use String.split method
String[] result = text.split("sometext");
For your acknowledgement
String.split returns the array of strings computed by splitting this
string around matches of the given regular expression
You should use StringTokenizer.
StringTokenizer sTok=new StringTokenizer(stringVariable, "newString");
while(sTok.hasMoreTokens())
System.out.println(sTok.nextToken());
stringVariable is the file contents and newString is the delimiter string.
EDIT
The second parameter of the StringTokenizer's constructor is the delimiter. It can be a new line \n or comma , or whatever you want.

Read values from a txt file and use it for text view [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to read text file in Android?
I am developing a web app where I am getting response from the web in form of response. I am saving that response successfully in the file. I want to read that response from the file and use it as a textview field. Please help me for the same .
App has been activated successfully. Id is****289****.Ref 1 Reference 1.Ref 2 is Reference 2
Fields in bold is what I am getting as response.Please help me for the same
You can read line by line and set lines in text view:
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"file.txt");
if (file.exists())
{
ArrayList<String> readed = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
readed.add(line);
}
}
catch (IOException e) {
}
txtview1.setText(readed.get(i));
txtview2.setText(readed.get(i+1));
txtview3.setText(readed.get(i+2));
}
In what format is the response you are receiving from the server?
If it is XML or JSON you could use a XML or JSON parser and select the fields you need.
If neither of both, but you control the server, you can modify your response output to be in XML or JSON.
At last, if you don't control the server, then most probably you'll need to make use of regex in order to get correctly your values for every request.

Android OrmLite pre-populate database

Is it possible with OrmLite to create a sql script file to easily populate the database with data? I did some searching and couldn't come up with anything easy. I know I can create some objects with data, I'm just looking for a cleaner method.
I'm thinking create a script file, open a a reader at load, and process each file as raw SQL the executeRaw() method. Any thoughts?
Just wanted to post my solution for anyone who might need it
try {
tableDAO.updateRaw("DELETE FROM table");
InputStream is = getResources().openRawResource(R.raw.populate_db);
DataInputStream in = new DataInputStream(is);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
tableDAO.updateRaw(strLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Good one Joe. I think your idea of the executeRaw() is close but use updateRaw() instead. Update handles INSERT, DELETE, and UPDATE statements.
http://ormlite.com/docs/raw-update
You should call TableUtils to create your schema first of course:
http://ormlite.com/docs/tableUtils
Hope this helps. You may want to use the mailing list for questions in the future:
http://groups.google.com/group/ormlite-user/

Categories

Resources