Loading data into a content provider - android

I have a long list of words and their definitions in a Google spead sheet. What would be the best way to load this data into a content provider.

You should check out the Android Sample Project called "Searchable Dictionary" from the sdk samples. You can download the samples using the Android sdk manager. The sample does something similar to what you are trying to accomplish.
They have a file called definitions.txt with the words and their definitions in a folder called "raw" under resources. Then in their SqliteOpenHelper class they are loading the words in the onCreate method with in a separate thread.
Here is a snippet of the method they are running.
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2) continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}

Related

Getting current scheduler information for Android app using Android Studio

I'm trying to get the current scheduler information from the path "/sys/block/sda/queue/scheduler" to be output in my application. However, it doesn't seem to return anything, not sure what I am doing wrong here?\
private String getScheduler() {
StringBuffer sb = new StringBuffer();
String file = "/sys/block/sda/queue/scheduler"; // Gets governor for big cores
if (new File(file).exists()) {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(file)));
String aLine;
while ((aLine = br.readLine()) != null)
sb.append(aLine + "\n");
if (br != null)
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (sb.toString().length() == 0) {
return "File not available";
}
return sb.toString();
}
It always return the string "File not available". I know this should work as I did the same thing for returning the current scaling governor. Do I need to request for root permissions within this app, even though my phone is already rooted?
Any help is greatly appreciated! Thank you so much!

Android - Save and Read from file

I have a listview lv_operationListand I'm trying to save it to a file and read it after. I can save and read files but I dont know if what I'm saving and reading is correct.
Basically I want to save the list rows and when I load a program I want to fill the same listview with the saved data.
Saving:
for (int i = 0; i < lv_operationList.getAdapter().getCount() - 1; i++) {
fileOutputStream.write(lv_operationList.getAdapter().toString().getBytes());
}
fileOutputStream.close();
Load?? Maybe something like this?
`fileInputStream = getContext().openFileInput(programName);
Scanner scanner = new Scanner(new DataInputStream(fileInputStream));
while(scanner.hasNext()) {
//Read??
}
//and display on lv_operationList. How?
i think you need to append the contents to the same file so you need to use append_mode like this.
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
out.write("text");
out.write('\n');
in order to read them you can use this method.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("reading line by line",""+text);
}

Android: Read a text file from assets from custom line

I'm using this code to read text from assets:
private void Read(String file){
try{
String Name = file;
Name = Name.replaceAll("'", "");
file = getAssets().open(Name + ".txt");
reader = new BufferedReader(new InputStreamReader(file));
line = reader.readLine();
Text ="";
while(line != null){
line = reader.readLine();
if (line !=null){
Text += line+"\n";
LineNumber++;
if(LineNumber==50){btnv.setVisibility(View.VISIBLE);break; }
}
}
if (LineNumber<50){btnv.setVisibility(View.GONE);}
txtv.setText(Text);
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
So I have to read first 50 lines of text, because the text is more then 300 lines, and all I know is to read file line by line, so if I read 300 lines line by line the app freezes for to long, so I read 50 first lines then 50 other lines and so on...
So after I read the first 50 lines with that code I call this other code to read next ones:
private void ContinueReading(){
if (LineNumber >= 50){
try{
while(line != null){
line = reader.readLine();
if (line !=null){
Text += line+"\n";
LineNumber++;
if (LineNumber==100){break;}
if (LineNumber==150){break;}
if (LineNumber==200){break;}
if (LineNumber==250){break;}
if (LineNumber==300){break;}
if (LineNumber==350){break;}
if (LineNumber==400){break;}
if (LineNumber==450){break;}
}
else{
btnv.setVisibility(View.GONE);
}
}
txtv.setText(Text);
}
catch(IOException ioe){ioe.printStackTrace();}
}
}
But as you see I leave open :
file = getAssets().open(emri + ".txt");
reader = new BufferedReader(new InputStreamReader(file));
And this is no good, is anyway to close them and open them again and start reading from last line, or any idea how to start reading from ex. line 50, then from line 100, etc.. ?
This looks like a good place for an AsyncTask. You can even update the TextView with the text as it's being read from the file.
txtv.setText("");
new MyFileReader().execute(filename);
.
.
.
// inner class
public class MyFileReader extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
try{
InputStream file = getAssets().open(params[0].replaceAll("'", "") + ".txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line;
while ((line = reader.readLine()) != null) {
publishProgress(line + "\n");
}
reader.close();
} catch(IOException ioe){
Log.e(TAG, ioe);
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
txtv.append(values[0]);
}
}
You should use another Thread to read the complete file at once,
Please read this Asynctask in Android
But be care full you can not perform any UI related operations(Like change text of a TextView) on a different Thread instead Of Main Thread....! For that purpose, please also concern below link,
Android “Only the original thread that created a view hierarchy can touch its views.”

Android - Comparing String Input On A Textfile Content

May I ask you to guide me how I can accomplish this problem?
I need to compare an inputWord to a string inside a .txt file and if found, return the whole line but if not, show "word not found".
Example:
inputWord: abacus
Text file content:
abaca - n. large herbaceous Asian plant of the banana family.
aback - adv. archaic towards or situated to the rear.
abacus - n. a frame with rows of wires or grooves along which beads are slid, used for calculating.
...
so on
Returns: abacus with its definition
What i am trying to do is compare my inputWord to the words before the " - " (hyphen as delimiter), if they dont match, move to the next line. If they match, copy the whole line.
I hope it doesnt seem like im asking you to "do my homework" but I tried tutorials around different forums and sites. I also read java docs but i really cannot put them together to accomplish this.
Thank you in advance!
UPDATE:
Here's my current code:
if(enhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
String delimiter = " - ";
String del[];
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (enhancedStem.equals(del[0]))
{
in.close();
databaseOutput.setText(s);
break;
}
}
in.close();
}
catch (FileNotFoundException e) {
databaseOutput.setText("" + e);
}
catch (IOException e1) {
databaseOutput.setText("" + e1);
}
}
Thanks a lot! Here's what I came up, and it returns the definition of inputs properly but the problem is, when i enter a word not found in the textfile, the app crashes. The catch phrase doesn't seem to work. Have any idea how I can trap it? Logcat says NullPointerExcepetion at line 4342 which is
s = in.readLine();
Assuming that the format of each line in the text file is uniform. This could be done in the following manner :
1) Read the file line by line.
2) Split each line based on the delimiter and collect the split String tokens in a temp String array.
3) The first entry in the temp token array will be the word before the "-" sign.
4) Compare the first entry in the temp array with the search string and return the entire line if there is a match.
Following code could be put up in a function to accomplish this :
String delimiter = "-";
String[] temp;
String searchString = "abacus";
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null) {
String s = in.readLine();
temp = s.split(delimiter);
if(searchString.equals(temp[0])) {
in.close();
return s;
}
}
in.close();
return ("Word not found");
Hope this helps.
you may try like:
myreader = new BufferedReader(new FileReader(file));
String text = "MyInput Word";
while(!((text.equals(reader.readLine())).equals("0")));

FileNotFoundException when trying to read xls in android

I'm trying to read excel contents in android, but always get file not found exception
The project is in:
C:\AndroidWorkSpace\AntenaProject
And the code is:
public void TestClick(View view)
{
File inputWorkbook = new File("shidur.xls");
Workbook w;
StringBuilder sb = new StringBuilder("starting");
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
//CellType type = cell.getType();
sb.append(cell.getContents());
}
}
} catch (Exception e) {
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.testText);
tv.setText(sb.toString());
}
i tried to put shidur.xls in the following folders:
C:\AndroidWorkSpace\AntenaProject\res\raw
C:\AndroidWorkSpace\AntenaProject\res
but still getting this exception.
i'm using jxl.jar from http://jexcelapi.sourceforge.net/
thanks for the help
The path that you provide to the File constructor needs to be the absolute path of the file, or you need to use the overload that takes another File object as the first parameter which represents the directory the file lives in.
That being said, constructing a file in this way is for files that are either in local storage (ie. phone's main memory) or external storage (ie. SD card).
To open a file from the res/raw directory, get an InputStream in the following way
InputStream in = getResources().openRawResource(R.raw.file_name);
Then, you will need code that reads the contents of your input stream. I use a static helper method that looks like this, but this could run you into problems if the file is huge. Hasn't happened to me yet, but in principle that's always a risk when loading the entire content of a file into memory
public static String readStream(InputStream in)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch(Exception ex) { }
finally
{
// NOTE: you don't have my IOUtils class,
// but all these methods do is check for null and catch the exceptions that Closeable.close() can throw
IOUtils.safeClose(in);
IOUtils.safeClose(reader);
}
return sb.toString();
}
You should use the following code to open file in the /res/raw
getResources().openRawResource(R.raw.shidur.xls)

Categories

Resources