Android internal Storage error - java

I am really new to android and writing a simple game for android.
In the game, like in most games you have score,
now, I want the score to be saved in Internal Storage, and for some reason, I manage to save the score, but not load it back.
here is the code:
final TextView best = (TextView) findViewById(R.id.best);
public int read = -1;
public StringBuffer buffer = new StringBuffer();
public String scoreTxt = buffer.substring(0, buffer.indexOf(" ") + 1);
public int score = 0;
// Save
try {
fileOutputStream = openFileOutput("record.txt", Context.MODE_PRIVATE);
fileOutputStream.write(scoreString.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this, "Save() works fine", Toast.LENGTH_SHORT).show();
// load
try {
FileInputStream fileInputStream = openFileInput("record.txt");
while ((read = fileInputStream.read())!= -1){
buffer.append((char)read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
best.setText("Best: " + scoreTxt);
Toast.makeText(MainActivity.this, "load() is good too " + scoreTxt, Toast.LENGTH_SHORT).show();
when I run the app, there is no crash or anything special in the logcat, but when ever I use scoreTxt the output is nothing, just " ".
can somebody help me solve this problem? Thanks

You never assign scoreTxt a value in your code.

You need to parse buffer after it has being populated.Now when scoreTxt is initialized buffer is null
You need to replace this
best.setText("Best: " + scoreTxt);
with
scoreTxt = buffer.substring(0, buffer.indexOf(" ") + 1);
best.setText("Best: " + scoreTxt);

In addition I wouldn't store game score into a file because score changes frequently and you want to avoid disk access a lot. Store it in SharedPreferences and from time to time flush it to a file on a background thread.

Related

openAssetFileDescriptor does not truncate OneDrive file

Using the following code, a text file that lives on Google Drive erases first as expected,leaving only the newly written content in the file. If the file lives on OneDrive the first x bytes are overwritten and the remaining original bytes left intact. Does anyone know of a work around for OneDrive files. I need the old contents erased and only the new content from the write to remain.
According to these docs
openAssetFileDescriptor and
openAssetFile
that is what should happen.
I have tried this using Java/Android Studio and C#/Xamarin, Android phone 9 api 28.
public void saveFile(View view)
{
try
{
AssetFileDescriptor pfd = getContentResolver().openAssetFileDescriptor(fileUri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(("Overwritten again " + System.currentTimeMillis() + "\n").getBytes());
fileOutputStream.close();
pfd.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
Couldn't come up with a why it doesn't work as documented, but I have come up with a work around to simulate expected behavior. Wouldn't mind comments if anyone sees a better way.
public void saveFile(View view)
{
try
{
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(fileUri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
//Added if-block to simulate automatic truncate when file located on onedrive.
if( (fileUri.toString()).contains("skydrive"))
{
FileChannel fileChannel = fileOutputStream.getChannel();
fileChannel.truncate(0);
}
fileOutputStream.write(("Overwritten again " + System.currentTimeMillis() + "\n").getBytes());
fileOutputStream.close();
pfd.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
try to use following, just replace "w" with "rwt" to truncate the original file.
getContentResolver().openAssetFileDescriptor(fileUri, "rwt")

Netty HttpStaticFileServerHandler problem

I use netty offical example HttpStaticFileServerHandler as file server, but when I download file from server I met a problem, the mp4 file I download from server is not complete and can't display.
https://github.com/netty/netty/blob/4.1/example/src/main/java/io/netty/example/http/file/HttpStaticFileServerHandler.java
And here is my client code:
FileOutputStream fos = null;
try {
URL website = new URL("http://localhost:8090/export/App/***.mp4");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
fos = new FileOutputStream("/Users/mine/***.mp4");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (Exception e) {
System.out.println("error msg:\n" + e);
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException ioe) {
System.out.println("fos close fail:\n" + ioe);
}
}
Make sure you close your FileOutputStream using fos.close().
Failing to do so means that only part of the data will be written, and that other programs may experience problems when accessing the file.
Another thing you could check is viewing the filesize of the file, those should match at both sides, if the file is way too small, open it with an text editor, and view the contents to check for clues.
I solved this problem. I find the RandomAccessFile is not closed in correct time.
Here is the change:
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "r");
} catch (FileNotFoundException ignore) {
sendError(ctx, NOT_FOUND);
return;
}
...
sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
#Override
public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
if (total < 0) { // total unknown
System.err.println(future.channel() + " Transfer progress: " + progress);
} else {
System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
}
}
#Override
public void operationComplete(ChannelProgressiveFuture future) {
System.err.println(future.channel() + " Transfer complete.");
raf.close();// close raf when transfer completed
}
});

Send Byte Array form Spring boot to an angular application?

I have used a AudioInputStream , i get it from text to speech with MaryTTS . i want to send this audio to the client Angular in this case .How can i do this with http ? I have put the audio to an array of bytes and how can I send it ?
this methode returns an array of bytes .I want to send it to an angular app and play the audio .Any help please ?
public byte[] generateVoice( ) {
LocalMaryInterface maryInterface = null;
try {
maryInterface = new LocalMaryInterface();
} catch (MaryConfigurationException e) {
System.err.println("Could not initialize MaryTTS interface: " + e.getMessage());
e.printStackTrace();
}
try {
if (maryInterface != null) audio = maryInterface.generateAudio("this is the first audio");
} catch (SynthesisException e) {
System.err.println("Synthesis failed: " + e.getMessage());
}
byte[] buffer = new byte[0];
try {
buffer = new byte[audio.available()];
while ((audio.read(buffer)) != -1) {
System.out.println("the buffer is being filled");
}
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
you're going to have to make a stream. take a look at:
npm stream-buffer

Why does my program stop running and does not return error?

I put the declaration in the while loop, and the program would not running and also does not return any error. I suspect the while loop become an infinite loop.
try
{
while (true)
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
But if I put the declaration of input stream out of the while loop, the program runs successfully. Can someone explain why this happens?
try
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
while (true)
{
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
You're reopening your file on every iteration through the loop, which means you are only ever reading the first object from the file. But you're reading the same object over and over again.
As well as opening your file only once, you really should try to detect the end of file without throwing an exception. As a matter of style, exceptions should be thrown when things go wrong, not as a matter of course.
Now I realize that in each iteration, I reopen the input stream, so the loop would not reach to the end of the file, and it becomes infinite.

Cannot read file just written to

I am trying to read from a file to which some user credentials were written. I want to write the file to an internal storage location. The code:
private void writeSendDetails(String name, String number, String emailID) {
//This function writes details to userCredentials.txt and also sends it to server.
String text = "Name: " + userName + "\n" + "Number: " + userNumber + "\n" + "Email ID:" + userEmailID;
FileOutputStream fos = null;
try {
fos = openFileOutput(userCredFile, MODE_PRIVATE);
Log.v(this.toString(), fos.toString());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(fos != null) {
OutputStreamWriter osw = new OutputStreamWriter(fos);
try {
osw.write(text);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v(this.toString(), "IOException caught in osw.write");
e.printStackTrace();
}
try {
osw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.v(this.toString(), "Written everything to userCredentials.txt");
readUserCredentials();
//code to send to server should begin here.
}
private void readUserCredentials() {
//function to read name, number and email ID from userCredentials.txt
/* Steps:
* 1. Check if file exists.
* 2. If it does, read all relevant credentials.
*/
File f = new File(userCredFile);
if(f.canRead()) {
Log.v(this.toString(), "Can open userCredentials for reading from.");
}
try {
FileReader fis = new FileReader(f);
Log.v(this.toString(), "Wrapping a buffered reader around file reader.");
BufferedReader bufRead = new BufferedReader(fis, 100);
String line;
try {
while((line = bufRead.readLine()) != null) {
Log.v(this.toString(), "Line read = " + line);
line = bufRead.readLine();
if(line.indexOf("Name: ") != -1) {
Log.v(this.toString(), "Found name in the string.");
userName = line.substring(6);
} else if(line.indexOf("Number: ") != -1) {
Log.v(this.toString(), "Found number in the string.");
userNumber = line.substring(8);
} else if(line.indexOf("Email ID: ") != -1) {
Log.v(this.toString(), "Found email in the string.");
userEmailID = line.substring(10);
}
}
Log.v(this.toString(), "User credentials = " + userName + " " + userNumber + " " + userEmailID);
} catch (IOException e) {
Log.v(this.toString(), "IOException caught.");
}
} catch (FileNotFoundException e1) {
Log.v(this.toString(), "File not found for reading.");
}
}
The LogCat output shows:
04-14 15:20:43.789: V/com.sriram.htmldisplay.htmlDisplay#44c0c660(675): Written everything to userCredentials.txt
04-14 15:20:43.789: V/com.sriram.htmldisplay.htmlDisplay#44c0c660(675): File not found for reading.
04-14 15:20:43.889: V/com.sriram.htmldisplay.fireflymenu#44c401e0(675): File not found for reading.
My question(s):
1. I need to write the file to internal storage. Am I doing it correctly?
2. Why is the file just written not being read?
Some things for your code:
#Oren is correct, you should use Log.e(TAG, "message", e) instead of the auto-created stuff from eclipse!
you should simply merge the 3 try/catch to one. No need to make it 3 times...
you should use Log.e() as said above for your FileNotFoundException too, so see the stacktrace to check the real reason (which currently covers the hint to solve your issue)
If you would have done at least number 3, you would have seen that the file you try to read could not be found. Thats why your log doesn't show the Can open userCredentials for reading from. output from your if statement.
The reason for that is pretty simple: You create the file by using openFileOutput(userCredFile, MODE_PRIVATE);. If you read the documentation of openFileOutput you will stumble upon:
The name of the file to open; can not contain path separators.
That means that userCredFile can only be something like test.txt. Also this method creates a file in a directory that can't be easily access from "outside".
When you now try to read the file via FileReader(userCredFile) it should be obvious, that android will try to open it in the root directory: /text.txt and it will, of course, fail. No non-root app can write/read in the root directory.
The main question, and also the answer to your issue: Why don't you use the corresponding openFileInput(userCredFile) method to read the file?

Categories