Managing data in android cache? - android

I'm trying to finish the 'backbone' of my app in the next 3 weeks, however, one of the few obstacles I stutter at is saving data. I've had a look at saving data internally, but there is limited tutorials from what I can find of reading and writing multiple lines to files in the apps cache directory.
Basically what I'm trying to do is save the values stored inside a fragment. This fragment resets all its values when the user clicks a button and changes text to match a page number. (A number of duplicates that contain various values.) I would do multiple fragments, however, thought it would be beneficial to use just one fragment to minimize storage space needed.
I've only got round to writing to the files, and created two methods to manage this which are then called on the click of a button. One creates these files and the other writes to them. Unfortunately I'm inexperienced using adb and could only find that the files are created, but don't know if they are being correctly written to. Is there any chance someone could review this and possibly assist with re-reading the files? Help is much appreciated.
The two methods (Warning: A great number of lines ahead):
public void createEmptyFiles() {
try {
outputTempExerciseFileE1 = File.createTempFile("temp_exercise_1",
".txt", outputTempExerciseDir);
outputTempExerciseFileE2 = File.createTempFile("temp_exercise_2",
".txt", outputTempExerciseDir);
outputTempExerciseFileE3 = File.createTempFile("temp_exercise_3",
".txt", outputTempExerciseDir);
} catch (IOException e) {
e.printStackTrace();
Log.w("rscReporter", "Encountered an error when creating empty files!");
}
}
public void writeTemporaryFiles() {
try {
if (counterAnotherExercise == 1) {
writerTemp = new FileWriter(outputTempExerciseFileE1);
writerTemp
.write(editTextExerciseName.getText().toString() + "\n"
+ counterNoSets + "\n" + counterRepsPerSet
+ "\n" + counterMeanRepTime + "\n"
+ counterMeanRepTimeRefined + "\n"
+ counterSetInterval);
writerTemp.close();
} else if (counterAnotherExercise == 2) {
writerTemp = new FileWriter(outputTempExerciseFileE2);
writerTemp
.write(editTextExerciseName.getText().toString() + "\n"
+ counterNoSets + "\n" + counterRepsPerSet
+ "\n" + counterMeanRepTime + "\n"
+ counterMeanRepTimeRefined + "\n"
+ counterSetInterval);
writerTemp.close();
} else if (counterAnotherExercise == 3) {
writerTemp = new FileWriter(outputTempExerciseFileE3);
writerTemp
.write(editTextExerciseName.getText().toString() + "\n"
+ counterNoSets + "\n" + counterRepsPerSet
+ "\n" + counterMeanRepTime + "\n"
+ counterMeanRepTimeRefined + "\n"
+ counterSetInterval);
writerTemp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Any of the text files should look like:
editTextExerciseName
counterNoSets
counterRepsPerSet
counterMeanRepTime
counterMeanRepTimeRefined
counterSetInterval
Where the two methods are called:
// In a switch statement as there are around 15 buttons
case R.id.button_another_exercise_foreground:
// Increases page number in fragment
counterAnotherExercise++;
// This then checks the page number and changes text
checkPageNo();
// Writing to files is called, files were created in onCreateView()
writeTemporaryFiles();
// Resets all the counters, giving the imitation it is a completely new fragment
counterReset();
// default array exercise is then set to the page number which is then displayed as title
// For example: Exercise 1, Exercise 2, Exercise 3...
textViewExerciseTitle.setText(defaultArrayExercise);
break;
I only know the basics of Java and Android, for myself this is ambitious, however, you gotta learn somewhere! Additional suggestion for saving values are welcomed.

You don't really need files as you are only writing and then reading a handful of fixed data. Use SharedPreferences like this:
to write:
PreferenceManager.getDefaultSharedPreferences(YourActivity.this).edit().putString("editTextExerciseName", "my exercise").commit();
to read:|
PreferenceManager.getDefaultSharedPreferences(YourActivity.this).getString("editTextExerciseName");

Related

Not cheatable Google fit step counter

i have a question to Google Fit.
I am creating a step counter (oh wonder g). This i have already done so far and it not really hard.
But now we come to my problem. I am only reading the steps with the Sensor API. The issue is, i can add new data via for example the Google Fit app and it will be counted in my app too. This introduces cheating and i do not want this.
So i need to have a way to only read "device created" data and not manually added data. Is there a nice way to to this?
From the SDK documentation it is not really clear how to proceed here.
So i need to have a way to only read "device created" data and not
manually added data. Is there a nice way to to this?
You will want to use Private Custom Data Types to achieve that. Read about the different types of Fitness data you can upload to Google Fit here.
1. Public data types
Standard data types provided by the platform, like com.google.step_count.delta. Any app can read and write data of
these types. For more information, see Public Data Types.
2. Private custom data types
Custom data types defined by an specific app. Only the app that defines the data type can read and write data
of this type. For more information, see Custom Data Types.
3. Shareable data types
Custom data types submitted to the platform by an app developer. Once approved, any app can read data of a
shareable type, but only whitelisted apps as specified by the
developer can write data of that shareable type. For more information,
see Shareable Data Types.
I was able to do this with the help of this alogrithm. But remember due to Android fragmentation this code still removes some of the user's data and count it as penalty
private String dumpDataSet(DataSet dataSet, int x) {
List<String> days = new ArrayList<>();
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
days.add("Thursday");
days.add("Friday");
days.add("Saturday");
days.add("Sunday");
String day = days.get(Math.round(x / 24));
Log.d(TAG, "\tDay: " + day);
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = getTimeInstance();
String text = "";
try {
for (DataPoint dp : dataSet.getDataPoints()) {
Log.i(TAG, "\tStepCount getStreamName: " + dp.getOriginalDataSource().getStreamName());
Log.i(TAG, "\tStepCount getStreamIdentifier: " + dp.getOriginalDataSource().getStreamIdentifier());
Log.i(TAG, "\tStepCount App Type: " + dp.getDataType().getName());
Log.i(TAG, "\tStepCount Type: " + dp.getOriginalDataSource().getType());
for (Field field : dp.getDataType().getFields()) {
Log.i(TAG, "\tField: " + field.getName() + " Value: " + dp.getValue(field));
text += dp.getValue(field);
String si[] = dp.getOriginalDataSource().getStreamIdentifier().toLowerCase().split(":");
if ((((si[si.length - 1].contains("soft")) || (si[si.length - 1].contains("step"))) && si[si.length - 1].contains("counter"))) {
totalSteps += Integer.parseInt(dp.getValue(field).toString());
Log.d(TAG, "\tStepCount" + " Added Steps -> " + dp.getValue(field) + " steps");
text += "\n\n";
} else {
Log.e(TAG, "\tStepCount PENALTY ---------------------------------------------------------------");
Log.e(TAG, "\tDay = " + day + " | Hour Number = " + x + " | StepCount" + " PENALTY DEDUCTED -> " + dp.getValue(field) + " steps");
Log.e(TAG, "\tStepCount PENALTY getStreamIdentifier: " + dp.getOriginalDataSource().getStreamIdentifier());
Log.e(TAG, "\tStepCount PENALTY getStreamName: " + dp.getOriginalDataSource().getStreamName());
Log.e(TAG, "\tStepCount PENALTY App Type: " + dp.getDataType().getName());
Log.e(TAG, "\tStepCount PENALTY Type: " + dp.getOriginalDataSource().getType());
Log.e(TAG, "\tStepCount PENALTY ---------------------------------------------------------------");
}
}
}
} catch (Exception ex) {
ex.getStackTrace();
}
return text;
}
----- UPDATE -----
You can also call
DataPoint.getOriginalDataSource().getAppPackageName()
to filter out smartwatches and other apps.
I tried as suggested by Ali Shah lakhani but
DataPoint.getOriginalDataSource().getAppPackageName();
/*I also tried but could not achieve what I wanted*/
DataPoint.getOriginalDataSource().getStreamName();
DataPoint.getOriginalDataSource().getStreamIdentifier();
did not work at least for me while retrieving data. I ended up using readDailyTotalFromLocalDevice() as shown below in order to capture steps captured by device only.
Fitness.HistoryApi.readDailyTotalFromLocalDevice(mApiClient, DataType.TYPE_STEP_COUNT_DELTA).await(1, TimeUnit.MINUTES)
I cross checked the same with some of the apps that avoids manual entries in their app and the count provided by the function above is exactly the same.
Note: If a user is having multiple devices and is using the app on all of them, readDailyTotalFromLocalDevice() will have different value for each and every device since the function is responsible for returning device specific data only.

Android PDF Writer(APW) Enconding

I am using Android PDF Write(APW) to create a PDF, but it doesn't work with some special characters(portuguese).
mypdf.addText(170, 50, 40,"Coração");
The standard enconding is:
mypdf.setFont(StandardFonts.SUBTYPE, StandardFonts.COURIER, StandardFonts.WIN_ANSI_ENCODING);
outputToFile("helloworld.pdf",pdfcontent,"ISO-8859-1");
I'v tried
outputToFile("helloworld.pdf",pdfcontent,"UTF-8");
outputToFile("helloworld.pdf",pdfcontent,"UTF-16");
outputToFile("helloworld.pdf",pdfcontent,"Cp1252");
and didn't succeed.
Any ideas what should I do?
EDIT
The method outputToFile is defined as:
private void outputToFile(String fileName, String pdfContent, String encoding) {
File newFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
try {
newFile.createNewFile();
try {
FileOutputStream pdfFile = new FileOutputStream(newFile);
pdfFile.write(pdfContent.getBytes(encoding));
pdfFile.close();
} catch(FileNotFoundException e) {
//
}
} catch(IOException e) {
//
}
}
The method addText is defined as:
public void addText(int leftPosition, int topPositionFromBottom, int fontSize, String text, String transformation) {
addContent(
"BT\n" +
transformation + " " + Integer.toString(leftPosition) + " " + Integer.toString(topPositionFromBottom) + " Tm\n" +
"/F" + Integer.toString(mPageFonts.size()) + " " + Integer.toString(fontSize) + " Tf\n" +
"(" + text + ") Tj\n" +
"ET\n"
);
}
Besides, I change the font color to white adding the following rawcontent:
mypdf.addRawContent("1 1 1 rg\n");
Then I come back to the black font color:
mypdf.addRawContent("0 0 0 rg\n");
I took all the information provided, wrote the following simple unit test method and ran it.
public void test19192108()
{
PDFWriter mPDFWriter = new PDFWriter(PaperSize.FOLIO_WIDTH, PaperSize.FOLIO_HEIGHT);
mPDFWriter.setFont(StandardFonts.SUBTYPE, StandardFonts.COURIER, StandardFonts.WIN_ANSI_ENCODING);
mPDFWriter.addText(170, 50, 40,"Coração");
String pdfcontent = mPDFWriter.asString();
outputToFile("helloworld19192108.pdf",pdfcontent,"ISO-8859-1");
}
(outputToFilebeing the helper method from the APW PDFWriterDemo class)
The result looks like this:
This seems pretty much to fulfill the expectations.
Thus, in whichever way it doesn't work with some special characters(portuguese) for the OP, some vital information is missing for reproducing the issue.
PS: Depending on the setup of the development environment, there might be an issue with non-ASCII characters in the source code. Thus, it might be a good idea to replace
mPDFWriter.addText(170, 50, 40,"Coração");
with
mPDFWriter.addText(170, 50, 40,"Cora\u00e7\u00e3o");
PPS: Adobe Reader after viewing a file generated like this wants to repair it. The reason is that the cross reference table is broken. The code generating entries for it is this:
public void addObjectXRefInfo(int ByteOffset, int Generation, boolean InUse) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%010d", ByteOffset));
sb.append(" ");
sb.append(String.format("%05d", Generation));
if (InUse) {
sb.append(" n ");
} else {
sb.append(" f ");
}
sb.append("\r\n");
mList.add(sb.toString());
}
(from CrossReferenceTable.java)
Counting the characters in this entry we get 10 + 1 + 5 + 3 + 2 = 21.
According to the specification, though:
Each entry shall be exactly 20 bytes long, including the end-of-line marker
(from section 7.5.4 Cross-Reference Table of ISO 32000-1)
When using (the current version of) the Android PDF Writer, you should fix this code, too.

Android - Remove the last incomplete line in .txt file

The app records the sensor data and write the data into a .txt file into the phone SD card.
During the data collection process, one may press the stop button anytime to stop writing.
The relevant writing part is as follows:
myFile = new File("/sdcard/ResearchData/"
+ txtData.getText() + ".txt");
myFile.createNewFile();
fOut = new FileOutputStream(myFile);
myOutWriter = new OutputStreamWriter(fOut);
myBufferedWriter = new BufferedWriter(myOutWriter);
myPrintWriter = new PrintWriter(myBufferedWriter);
myPrintWriter.write(currentTime - startTime + " " + acceleration[0]
+ " " + acceleration[1] + " " + acceleration[2] + "\n");
Once the STOP button is pressed, the following codes are executed.
myOutWriter.close();
fOut.close();
The codes are functioning okay, but the only problem is that because one may press STOP anytime, so the last line of the .txt file is always INCOMPLETE. Due to the need for data analysis, I need the data to be a nice rectangular matrix. Thus, I need to remove the last incomplete line. How may I do it?
Or solve this question from another angle. Can I make the STOP button synchronous to the writing process? i.e., after one line has been completely written in, then the STOP is checked.
You need a variable of bool type which is initially false and let's call it isStopPressed.
In button's down event, you should assign it to true.
I assume you create your file inside a top function, and modify this file inside onSensorChanged() function.
Then, after this line
myPrintWriter.write(currentTime - startTime + " " + acceleration[0]
+ " " + acceleration[1] + " " + acceleration[2] + "\n");
you need a conditional like,
if(isStopPressed) {
mSensorManager.unregisterListener([Your Sensor Listener]);
myOutWriter.close();
fOut.close();
}
This will provide you the most comprehensive, valid interval for your needs.
You may try setting up a boolean flag, like isStopped to indicate the STOP button is pressed.
When the STOP button is pressed, set the isStopped flag to true.
In your file writing part, check the isStopped flag. if it's true, exit the loop and close the file. Otherwise, the code can continue writing lines to the file.

Displaying multiple lines of text and variables in an AlertDialog using setMessage()

I need to display multiple lines of text in an Alert Dialog. If I use multiple setMessage() methods, only the last setMessage is displayed, as shown below.
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Statistics:");
alertDialog.setMessage("No. of attempts: " + counter);
alertDialog.setMessage("No. of wins: " + counterpos);
alertDialog.setMessage("No. of losses: " + counterneg);
Is there a way to create a new line for each of these in the dialog? Like using \n in System.print.out(); method.
Thanks!
You can do something like this
String alert1 = "No. of attempts: " + counter;
String alert2 = "No. of wins: " + counterpos;
String alert3 = "No. of losses: " + counterneg;
alertDialog.setMessage(alert1 +"\n"+ alert2 +"\n"+ alert3);
You could just create one string of everything you want to show and add "\n" where you'd like the line breaks to be.
alertDialog.setMessage("No. of attempts: " + counter + "\n" +
"No. of wins: " + counterpos + "\n" +
"No. of losses: " + counterneg);
Or even better to use a StringBuilder:
StringBuilder sb = new StringBuilder();
sb.append("No. of attempts: " + counter);
sb.append("\n");
sb.append("No. of wins: " + counterpos);
sb.append("\n");
sb.append("No. of losses: " + counterneg);
alertDialog.setMessage(sb.toString());
And the best way to do it would be to extract the static texts into a string resource (in the strings.xml file). Use the %d (or %s if you want to insert strings rather than ints) to get the dynamic values in the right places:
<string name="alert_message">No. of attempts: %1$d\nNo. of wins: %2$d\nNo. of losses: %3$d</string>
And then in code:
String message = getString(R.string.alert_message, counter, counterpos, counterneg);
alertDialog.setMessage(message);
You can also insert newlines directly in the strings.xml file:
<string name="my_string_text">This would revert your progress.\n\n Are you sure you want to proceed?</string>
Kotlin simplifies the solution by:
chaining the calls of the set methods
using interpolated strings
as follows:
"AlertDialog.Builder
This Builder object to allow for chaining of calls to set methods
"
(https://developer.android.com/reference/android/app/AlertDialog.Builder)
fun alertDemo() {
var counter: Int = 5
var counterpos: Int = 2
var counterneg: Int = 3
val builder = AlertDialog.Builder(this)
.setTitle("Statistics:")
.setMessage("""
|number of
|
|attempts: $counter
|wins: $counterpos
|losses: $counterneg
""".trimMargin())
.show()
}
I had prepared a screen-shot of the result, but as I am new here, I appear to have learned that uploading screenshots may be restricted to higher level community peers. Or did I miss something? Thank you for enlighting (perhaps not only) myself :)
The screenshot comes in a nice format without showing the bars.
PS:
For the minimalists, due to chaining, we could even eliminate the redundant "val builder ="

Attempting to remove an object off screen moves all the objects in play?! - Android. Please Help!

I am building an android game where objects randomly come in from either side of the screen towards a sprite in the middle of the screen. When one passes the tripwire on the central sprite it is dealt with by my collision detection which sets the enemy objects co-ordinates to somewhere off the screen, thats desired but as this happens in my updatePhysics() method when we loop back to the doDraw() method the canvas has redrawn to an empty state (ie. without any enemy objects on it). Any objects that were on screen and not colliding with the sprite are erased too and new ones regenerated. Why is it removing all the enemy objects rather than just updating the position of the ones left in play at that point???
I will include my code to make this simpler to understand. This is the collision detection part of my updatePhysics():
// COLLISION DETECTION
int n = 0,haveHidden = 0; //haveHidden is number of objects that are hidden in this current pass of CD
while(n < mCurrentDistractionsOnScreen){
switch(DistractionsArray[n].dGeneralDirection){
case LEFT_ORIGIN:
// If the X co-ordinate is past the edge of the performer sprite
if((DistractionsArray[n].ObjmX2 > LEFT_TRIPWIRE) && (DistractionsArray[n].ObjmX2 < RIGHT_TRIPWIRE))
{
mConcentration -= DistractionsArray[n].dDamageToInflict;
Log.w(this.getClass().getName(), "Object: " + n + "LEFT Damage: " + DistractionsArray[n].dDamageToInflict + " leaves " + mConcentration);
DistractionsArray[n].hideDistraction();
haveHidden++;
}
break;
case RIGHT_ORIGIN:
// If the X co-ordinate is past the edge of the performer sprite
if((DistractionsArray[n].ObjmX > LEFT_TRIPWIRE) && (DistractionsArray[n].ObjmX < RIGHT_TRIPWIRE))
{
mConcentration -= DistractionsArray[n].dDamageToInflict;
Log.w(this.getClass().getName(), "Object: " + n + "RIGHT Damage: " + DistractionsArray[n].dDamageToInflict + " leaves " + mConcentration);
DistractionsArray[n].hideDistraction();
haveHidden++;
}
break;
}
n++;
mCurrentDistractionsOnScreen -= haveHidden;
}
This is the hideDistraction() method that is a method defined in the DistractionObjects inner class in this thread (DistractionsArray consists of these objects):
public void hideDistraction(){
// Set attributes to default
this.dName = "Default";
this.dVelocity = 0;
this.dMaxPoints = 10;
this.dDamageToInflict = 0;
this.dOrigin = 100;
this.dGestureRequired = "";
// Can be reused again
this.isUseable = true;
Log.w(getClass().getName(), "HIDING FROM: " + this.ObjmX + " " + this.ObjmY + " " + this.ObjmX2 + " " + this.ObjmY2 + " ");
// Position it off-screen
this.ObjmX = -150;
this.ObjmX2 = -150 + this.dDistractionObjectSprite1.getIntrinsicWidth();
this.ObjmY = -150;
this.ObjmY2 = -150 + this.dDistractionObjectSprite1.getIntrinsicHeight();
Log.w(getClass().getName(), "HIDING TO: " + this.ObjmX + " " + this.ObjmY + " " + this.ObjmX2 + " " + this.ObjmY2 + " ");
}
And the doDraw method starts by canvas.save() and at the end does a canvas.restore. To render my objects at their new position it does this:
// For each object in play, draw its new co-ordinates on the canvas
int n = 0;
while(n < mCurrentDistractionsOnScreen){
DistractionsArray[n].dDistractionObjectSprite1.setBounds((int)DistractionsArray[n].ObjmX,
(int)DistractionsArray[n].ObjmY,
(int)DistractionsArray[n].ObjmX2,
(int)DistractionsArray[n].ObjmY2);
DistractionsArray[n].dDistractionObjectSprite1.draw(canvas);
n++;
}
I am literally devoid of any ideas now after trying so many different fixes, even attempted to serialize the position of those other enemy objects on screen in an integer array that is rebuilt in the physics method but nothing!!
To summarise, I need a way of hiding the enemy object off-screen like in hideDistraction() when it passes the tripwire, but I want all the other objects to still continue on course as they are without being moved off screen and re-rendered from scratch.
If you need more details please ask....and if you can, pleaseeee help!
Many thanks
Greenhouse,
You are controlling your loop using the mCurrentDistractionsOnScreen, but you are also resetting the mCurrentDistractionsOnScreen inside of the loop. You likely don't want to be doing this. The exact reason it is removing everything is likely very difficult to pin down (i'm not surprised you couldn't figure it out!). Try re-factoring that main while loop to something like this:
for (Distraction distraction: DistractionsArray) {
switch(distraction.dGeneralDirection) {
case LEFT_ORIGIN:
// Your code goes here ...
break;
case RIGHT_ORIGIN:
// Your code goes here ...
break;
}
}
When pasting your code, remove all references to DistractionsArray[n] and replace them with distraction
EDIT:
If this helps you, then please consider 1) accepting more answers on your questions and 2) Not putting stuff like 'please help' in your titles. It's a site geared towards help, we know what you are looking for ;)
Your hideDistraction() and doDraw code is likely fine.

Categories

Resources