How to format how values are saved to a text file? - android

I am currently saving values to a text file in my application. The values are read from an EEG headset every second and are then stored within the text file.
The values are read using a handler e.g.:
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// msg.what determines the type of each message
switch (msg.what) {
case TGDevice.MSG_EEG_POWER:
eegPower = (TGEegPower) msg.obj;
//trace code
Log.d("LSD", "highAlpha: " + eegPower.highAlpha);
Log.d("LSD", "lowAlpha: " + eegPower.lowAlpha);
Log.d("LSD", "highBeta: " + eegPower.highBeta);
Log.d("LSD", "lowBeta: " + eegPower.lowBeta);
Log.d("LSD", "lowGamma: " + eegPower.lowGamma);
Log.d("LSD", "midGamma: " + eegPower.midGamma);
Log.d("LSD", "delta: " + eegPower.delta);
Log.d("LSD", "theta: " + eegPower.theta);
//adding all the EEGpowers to an arraylist to help add them to file
ArrayList<String> EEGPowers= new ArrayList<String>();
EEGPowers.add("highAlpha: " + eegPower.highAlpha);
EEGPowers.add("lowAlpha: " + eegPower.lowAlpha);
EEGPowers.add("highBeta: " + eegPower.highBeta);
EEGPowers.add("lowBeta: " + eegPower.lowBeta);
EEGPowers.add("lowGamma: " + eegPower.lowGamma);
EEGPowers.add("midGamma: " + eegPower.midGamma);
EEGPowers.add("delta: " + eegPower.delta);
EEGPowers.add("theta: " + eegPower.theta);
for(String s: EEGPowers){
writeToFileEEGPower(s);
}
//rest of handler...
The following method is the method used to save the values to file:
public void writeToFileEEGPower(String data){
//creating time for the file
Time t= new Time();
int timeFileSecond= t.second;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "MathsGame" + timeFileSecond + timeFileDate + timeFileYear + android.os.Build.SERIAL;
//creating the file where the contents will be written to
File file= new File(dir, fileName + ".txt");
FileOutputStream os;
try{
boolean append= true;
os= new FileOutputStream(file, append);
String writeMe =data + "\n";
os.write(writeMe.getBytes());
os.close();
} catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
The method and handler work as is, however my issue is that the values are not formatted as I would like when they are saved and are very messy as you can see:
E.g. of current text file:
I would like my text file to be formatted like this:
How can I implement this formatting in my code?
EDIT (Attempt at formatting):
//Declared globally outside handler
final int maxWordLength = 15;
String spaces[] = new String[maxWordLength];
//Within handler:
//setting up the array of maxlength etc
spaces[0] = "";
for(int i=1; i<maxWordLength ;i++){
spaces[i] = spaces[i-1]+" ";
}
int seconds=0;
//CREATING THE HEADER IN THE TEXT FILE
writeToFileEEGPower(order("Seconds")+order("highAlpha")+order("lowAlpha")+order("highBeta")+order("LowBeta")+
order("lowGamma")+order("midGamma")+order("Delta")+order("Theta")+ "\n");
//creating the string to be written to file
String line = order(seconds+"")+order(eegPower.highAlpha+"")+order(eegPower.lowAlpha+"")+order(eegPower.highBeta+"")+
order(eegPower.lowBeta+"")+order(eegPower.midGamma+"")+order(eegPower.delta+"")+order(eegPower.theta+"")+ "\n";
//write the string to file
writeToFileEEGPower(line);
Current sample output in text file:

You can define your max 'word' length, and complete every 'word' with empty spaces.
for example:
STEP 1
Define maxWordLength. this value describe the width of each column. Should this value will be slightly larger than the longest word (In this example length of 'highAlpha:'=10, choose number>10).
final int maxWordLength = 15;
STEP 2
Create array of empty spaces.
String spaces[] = {""," "," "," "," ", /*....*/ " "};// Complete the missing words up to the last word with 15 spaces.
Or create it dynamically:
String spaces[] = new String[maxWordLength];
spaces[0] = "";
for(int i=1; i<maxWordLength ;i++){
spaces[i] = spaces[i-1]+" ";
}
STEP 3
Define the 'Seconds' var, create the order function at your class and write the header row to the file:
int seconds=0;
//table header row
writeToFileEEGPower(order("Seconds")+order("highAlpha")+order("lowAlpha")+order("highBeta")/+.../);
private String order(String value){
return (value + spaces[maxWordLength-value.length()]);
}
STEP 4
For each handleMessage create a line and save it to the file:
String line = order(seconds+"")+order(eegPower.highAlpha+"")+order(eegPower.lowAlpha+"")+order(eegPower.highBeta+"")//+...;
writeToFileEEGPower(line);

Related

How to replace the word in the string by using replace in Android?

I want to replace one word in the String by using substring. But it seen didn't work.
for example: The string is 0000 , and I want to replace the first word from 0 to 1.
It should be 1000. but it doesn't.
The code is like the following
String WorkStatus = "0000";
if(WorkStatus.substring(0, 1).matches("0"))
{
WorkStatus.substring(0, 1).replace("0", "1");
Log.d(TAG, "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d(TAG, "WorkStatus = " + WorkStatus + "\n");
}
It didn't work , the string always show 0000. And what I want is "1000"
Do I missing something ?
use this
String WorkStatus = "0000";
//You use matches, while you might as well use equals
if (WorkStatus.substring(0, 1).equals("0")) {
//reassign workstatus to workstatus where the first entry is a '1' + the last three chars "000"
WorkStatus = WorkStatus.substring(0, 1).replace("0", "1") + WorkStatus.substring(1, WorkStatus.length());
Log.d(TAG, "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d(TAG, "WorkStatus = " + WorkStatus + "\n");
}
You didnt assign the modified string to WorkStatus
Another possibility is converting the string to a char[] and replacing the index, instead of working with substrings.
String WorkStatus = "0000";
char[] chars = WorkStatus.toCharArray();
if (chars[0] == '0') {
chars[0] = '1';
WorkStatus = new String(chars);
}
If you want other chars to become 1 instead of zero, alter the chars[0] into chars[index], where index is the index you want to change from 0 to 1
Or, even easier, use a StringBuilder:
int yourIndex = 2; //your index which you want to check for 0 and change to 1
StringBuilder sb = new StringBuilder("0000");
if (sb.charAt(yourIndex) == '0')
sb.setCharAt(yourIndex, '1');
WorkStatus = sb.toString();
method replace has a return value of the string after replaced
you shuold resign the result to the String
WorkStatus=WorkStatus.substring(0, 1).replace("0", "1")+ WorkStatus.substring(1, WorkStatus.length();
if you asign it to a new variable like the below code, you can get what you needed.
String newWorkStatus=WorkStatus.substring(0, 1).replace("0", "1")+WorkStatus.substring(1);
Log.d("LOG", "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d("LOG", "WorkStatus = " + WorkStatus + "\n");
Log.d("LOG", "New WorkStatus = " + newWorkStatus + "\n");
WorkStatus.substring(0, 1).replace("0", "1"); returns 1, you should use StringBuilder instead of String.
My solution:
StringBuilder WorkStatus = new StringBuilder("0000");
int pos = WorkStatus.indexOf("0", 0);
if (pos != -1) {
WorkStatus.replace(pos, pos + 1, "1");
}
System.out.print(WorkStatus);

Strange Output When Write Using NFC

so now i have a project of NFC, i write a vcard file but the output is not what i want this is the code:
private NdefMessage getNoteAsNdef() {
// byte[] textBytes = mName.getText().toString().getBytes();
// EditText tName = mName;
// EditText tNumber = mNumber;
String nameVcard = "BEGIN:VCARD" +"\n"+ "VERSION:2.1" +"\n" + "N:;" + (EditText) findViewById(R.id.mName) + "\n" +"ORG:"+"\n"+ "TEL;WORK:" +(EditText) findViewById(R.id.mNumber)+ "\n" + "END:VCARD";
byte[] uriField = nameVcard.getBytes(Charset.forName("US-ASCII"));
byte[] textBytes = new byte[uriField.length + 1];;
System.arraycopy(uriField, 0, textBytes, 1, uriField.length);
NdefRecord textRecord = new NdefRecord(
NdefRecord.TNF_MIME_MEDIA, "text/x-vcard".getBytes(), new byte[0], textBytes);
return new NdefMessage(new NdefRecord[] {
textRecord
});
}
the output is some kind of weird word and always have an "#"
i don't get it, is there something i must add?
If you use (EditText) findViewById(R.id.mName) and plus + a String, it will get the method toString of editText .This is not what you want to get.So you should use ((EditText) findViewById(R.id.mName)).getText().toString() instead.
String nameVcard = "BEGIN:VCARD" +"\n"+ "VERSION:2.1" +"\n" + "N:;" + (EditText) findViewById(R.id.mName) + "\n" +"ORG:"+"\n"+ "TEL;WORK:" +(EditText) findViewById(R.id.mNumber)+ "\n" + "END:VCARD";
you are using directly toString() on the EditText object. You should change
(EditText) findViewById(R.id.mName)
with
((EditText) findViewById(R.id.mName)).getText().toString()
for every EditText

How can I create Android logcat entries that provide a link to source code in Eclipse? [duplicate]

Is there any way to access automatically any Log in Logcat by a double click ?
Actually, when there is an error crashing my Android Application, I can double click on the line saying for instance
at com.myapp.mypackage$Class.function(File.java:117)
And by Double-clicking on this line, I am automatically redirected to the related line of my code.
But, when I try to generate the same line in another Log, example :
Log.e("TAG", "at com.myapp.mypackage$Class.function(File.java:117)");
The Double-Click doesn't work anymore ...
Any ideas ?
If you want to create a log in logcat that can be clicked and go to your line use the following method to create it:
Enjoy!
public static void showLogCat(String tag, String msg) {
StackTraceElement[] stackTraceElement = Thread.currentThread()
.getStackTrace();
int currentIndex = -1;
for (int i = 0; i < stackTraceElement.length; i++) {
if (stackTraceElement[i].getMethodName().compareTo("showLogCat") == 0)
{
currentIndex = i + 1;
break;
}
}
String fullClassName = stackTraceElement[currentIndex].getClassName();
String className = fullClassName.substring(fullClassName
.lastIndexOf(".") + 1);
String methodName = stackTraceElement[currentIndex].getMethodName();
String lineNumber = String
.valueOf(stackTraceElement[currentIndex].getLineNumber());
Log.i(tag, msg);
Log.i(tag + " position", "at " + fullClassName + "." + methodName + "("
+ className + ".java:" + lineNumber + ")");
}
If you don't mind the clutter in your log, you can easily just add a new Exception() to the log message
Log.e("TAG", "Looky here see", new Exception());

Is there any way to access automatically any Log in Logcat by a double click?

Is there any way to access automatically any Log in Logcat by a double click ?
Actually, when there is an error crashing my Android Application, I can double click on the line saying for instance
at com.myapp.mypackage$Class.function(File.java:117)
And by Double-clicking on this line, I am automatically redirected to the related line of my code.
But, when I try to generate the same line in another Log, example :
Log.e("TAG", "at com.myapp.mypackage$Class.function(File.java:117)");
The Double-Click doesn't work anymore ...
Any ideas ?
If you want to create a log in logcat that can be clicked and go to your line use the following method to create it:
Enjoy!
public static void showLogCat(String tag, String msg) {
StackTraceElement[] stackTraceElement = Thread.currentThread()
.getStackTrace();
int currentIndex = -1;
for (int i = 0; i < stackTraceElement.length; i++) {
if (stackTraceElement[i].getMethodName().compareTo("showLogCat") == 0)
{
currentIndex = i + 1;
break;
}
}
String fullClassName = stackTraceElement[currentIndex].getClassName();
String className = fullClassName.substring(fullClassName
.lastIndexOf(".") + 1);
String methodName = stackTraceElement[currentIndex].getMethodName();
String lineNumber = String
.valueOf(stackTraceElement[currentIndex].getLineNumber());
Log.i(tag, msg);
Log.i(tag + " position", "at " + fullClassName + "." + methodName + "("
+ className + ".java:" + lineNumber + ")");
}
If you don't mind the clutter in your log, you can easily just add a new Exception() to the log message
Log.e("TAG", "Looky here see", new Exception());

how to get end of file(EOF)

I have this code..
String you = buf.readLine();
Log.d("STRING", ikaw);
StringTokenizer st = new StringTokenizer(you);
double lat = Double.parseDouble(st.nextToken());
double lng = Double.parseDouble(st.nextToken());
int type = Integer.parseInt(st.nextToken());
String text = st.nextToken();
Log.d("File Reading stuff", "success = " + lat);
Log.d("File Reading stuff", "success = " + lng);
Log.d("File Reading stuff", "success = " + type);
Log.d("File Reading stuff", "success = " + text);
How am i suppose to test if it is already the end of file?
I don't know how many lines there are in my file and I need to print all of them.
I know i should place my code inside a while loop, but I have no idea how to get the end of file.
I assume the code you have listed is inside a loop, and I assume buf is an instance of BufferedReader. You just need to check for null after you call readLine(). It returns null when you've hit the end of the file.

Categories

Resources