I've been doing some work in Android, and I've found after three or four different attempts, I can't seem to get Android to save my file anywhere. In fact, it doesn't even create a folder in data/ for my app.
Here's how I'm trying to save the file - this is in my main activity also.
#Override
public void onStop(){
super.onStop();
try{
FileOutputStream memboricOut = getApplicationContext().openFileOutput("memboric.core", Context.MODE_PRIVATE);
brain.save(memboricOut);
}catch(Exception e){
System.err.println("Could not save memboric core.");
e.printStackTrace();
}
}
And inside brain.save():
public boolean save(FileOutputStream fileOut) {
try{
ObjectOutputStream oo = new ObjectOutputStream(fileOut);
oo.writeObject(this);
oo.close();
fileOut.close();
System.out.println("Memboric Core saved successfully.");
return true;
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
This code seems to do nothing. I've also placed the saving in onDestroy as well.
Have I just chosen bad placement for the saving? I can't imagine what could possibly being going wrong.
Do you have the permission to save files ?
You can add that by adding android.permission.WRITE_EXTERNAL_STORAGE permission to you AnroidManifest.xml.
oo.writeObject(this);
Is brain have serializable data?
Class Brain implements java.io.Serializable {
public String toString() {
return "serialized data";
}
}
If not, DataOutputStream maybe a better choice.
DataOutputStream oo = new DataOutputStream(fileOut);
oo.writeInt(value); // if breain have int value
oo.flush();
oo.close();
Saved data will be appear in /data/data/(your.package.name)/files/memboric.core
Check the file with emulator (or rooted device).
Related
So I have this app, but its to big for the play store because it has lots of pdfs, so I decided to use play asset delivery to retrieve the pdfs. I have done everything like it says in google docs, I have created an asset-package, changed everything in the manifest, build.gradle and build a bundle! But the play asset delivery just isn't working! I can't get my pdf files that are on the "pdfs->src->main->assets" !! Can someone please help me? Am I choosing the right package name?
My source code to retrieve the pdf is the following :
mPDFView = (PDFView) findViewById(R.id.pdf);
Context context = null;
try {
context = createPackageContext(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
AssetManager assetManager = context.getAssets();
try {
InputStream is = assetManager.open("A abóboda.pdf");
mPDFView.fromStream(is).load();
} catch (IOException e) {
e.printStackTrace();
}
I'm trying to implement a simple alarm in android by using the
MediaPlayer. However, every time I try to prepare() it, I get an error.
Here's my code. I'm a total beginner concerning Java and Android so
perhaps I'm doing something inherently wrong.
private void playDiscreteAlarm()
{
alarmSound = new MediaPlayer();
alarmSound.setAudioStreamType(AudioManager.STREAM_RING);
Resources res=context.getResources();
AssetFileDescriptor fd = res.openRawResourceFd(R.raw.discrete_alarm);
try {
alarmSound.setDataSource(fd.getFileDescriptor());
fd.close();
alarmSound.setLooping(true);
alarmSound.prepare();
alarmSound.start();
}
catch (IOException e)
{
Log.d("error\n");
}
}
The weird thing is that this worked once and after that stopped working.
It works when I use MediaPlayer.create() however I need to use the ringer volume instead of the media volume, and I believe this is the way to do it.
I fixed the problem, though I'm not sure what caused it. I just used a different and maybe slightly simpler method.
Here's what I did:
private void playDiscreteAlarm()
{
String filename = "android.resource://" + context.getPackageName() + "/raw/discrete_alarm";
alarmSound = new MediaPlayer();
alarmSound.setAudioStreamType(AudioManager.STREAM_RING);
try {
alarmSound.setDataSource(context, Uri.parse(filename));
alarmSound.setLooping(true);
alarmSound.prepare();
alarmSound.start();
}
catch (Exception e)
{
System.out.println(e);
}
}
Thanks !
Hey Guys I did a little App, where I type into a textbox a specific value (height, weight) and save it into a file.
I did this but I do not know, which path I have to use for Android.
Hope you can help :)
public void SaveList(View view) {
//Pf`enter code here`ad, im privaten Speicherbereich
File file = new File("I need this path :)");
try {
OutputStreamWriter fdg = new OutputStreamWriter(new FileOutputStream(file));
fdg.write(""+this.weight);
fdg.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can use Environment.getDataDirectory() to get the root directory, if you dont have an SD card.
If you have an SD card, use Environment.getExternalStorageState()
Read more about them in the docs
Thus, change your code as follows
File file = new File(Environment.getDataDirectory()+"/your_folder_name/your_file_name");
This will create a file with name your_file_name in the folder your_folder_name in your internal storage.
I want to add audio to my java game, but I don't know how to put it in practice. By I've read, Java only plays wav files, but this files are too big.
I've read a little about JLayer, but I actually need something like soundpool in android, for handle all in game effects. Do you know how to do it? I've to build a class that does it?
Here is some code for you that I've used in a game a while back using JLayer:
public class MP3 {
public void play(final InputStream in) {
new Thread() {
#Override
public void run() {
try {
new Player(in).play();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}.start();
}
}
private HashMap<String, URL> soundMap = new HashMap<String, URL>();
public void loadSounds() {
String[] filenames = {
"5_seconds_remaining.mp3",
"10_seconds_remaining.mp3",
"button_press_loud.mp3"
};
for (String s : filenames) {
soundMap.put(s.substring(0, s.indexOf('.')), getClass().getResource("sounds/" + s));
}
}
public void playSound(String name) {
try {
new MP3().play(new BufferedInputStream(soundMap.get(name).openStream()));
} catch (IOException ex) {}
}
I recommend TinySound. It supports ogg/vorbis files (a free compression format comparable to mp3, but does not require licensing as mp3 does).
http://www.java-gaming.org/topics/need-a-really-simple-library-for-playing-sounds-and-music-try-tinysound/25974/view.html
A link is provided there to the github source for this library.
It is also possible to use Java as a synthesizer (I've been dabbling with this) but I'm still working on making something 'practical' for use in a game.
I am writing a custom event and would like some help please. Most of what I am about to talk about is based on the help provided at Custom event listener on Android app
So here is my issue. I am writing an app that needs to download updated images from the web, store the images on the phone, then later display those images. Basically, I download any needed images during a splash screen. Then when the images are downloaded and stored, the splash screen clears and any necessary (newly downloaded) images are displayed on the screen. Here is the problem: the download process is done via an asynctask so the part where the images are loaded on to the screen can't be done inside the asynctask. It has to be done on the main UI thread. I would like to create an event and a custom event listener for the main thread to listen for that basically tells the main UI thread that it is safe to start loading the downloaded images from memory.
According to the discussion from the link above, I came up with this so far... a download listener interace
public interface DataDownloadListener {
void onDownloadStarted();
void onDownloadFinished();
}
an event class...
public class DataDownloadEvent {
ArrayList<DataDownloadListener> listeners = new ArrayList<DataDownloadListener>();
public void setOnDownload(DataDownloadListener listener){
this.listeners.add(listener);
}
}
My problem is that I don't understand where to put the last two steps in those instructions. I thought I would have to put the listener and event inside the class that actually initiates the downloads. But where? Here is my function that initiates the download and saves it to the device:
public String download(String sourceLocation) {
String filename = "";
String path = "";
try {
File externalStorageDirectory = Environment
.getExternalStorageDirectory();
URL urlTmp = new URL(sourceLocation);
filename = urlTmp.getFile()
.substring(filename.lastIndexOf("/") + 1);
path = externalStorageDirectory + PATH;
// check if the path exists
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
filename = path + filename;
f = new File(filename);
//only perform the download if the file doesn't already exist
if (!f.exists()) {
Bitmap bitmap = BitmapFactory.decodeStream(urlTmp.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(
filename);
if (bitmap != null) {
bitmap.compress(getFormat(filename), 50, fileOutputStream);
Log.d(TAG, "Saved image " + filename);
return filename;
}
}
else{
Log.d(TAG, "Image already exists: " + filename + " Not re-downloading file.");
}
} catch (MalformedURLException e) {
//bad url
} catch (IOException e) {
//save error
}
return null;
}
And the last step about registering the listener, where do I put that? The instructions say to put that somewhere during initialization. Does that mean in the onCreate method of my main activity? outside the class in the import section of the main activity? Never done a custom event before, so any help would be appreciated.
According to the discussion from the link above, I came up with this so far... a download listener interace
public interface DataDownloadListener {
void onDownloadStarted();
void onDownloadFinished();
}
an event class...
public class DataDownloadEvent {
ArrayList<DataDownloadListener> listeners = new ArrayList<DataDownloadListener>();
public void setOnDownload(DataDownloadListener listener){
this.listeners.add(listener);
}
}
Ok...
Now in your download procedure, at the start of the download, cycle all the elements on the listeners ArrayList and invoke the onDownloadStarted event to inform all your listeners that the download is just started (in this event i presume you'll need to open the splashscreen).
Always in your download procedure, at the and of the download, cycle all the elements on the listeners ArrayList and invoke the onDownloadFinished event to inform all your listeners that the download is finished (now close the splashscreen).
How to cycle listeners on download completed
foreach(DataDownloadListener downloadListener: listeners){
downloadListener.onDownloadFinished();
}
How to cycle listeners on download started
foreach(DataDownloadListener downloadListener: listeners){
downloadListener.onDownloadStarted();
}
Don't make it static if possible... In the class that you'll use to download your files, simply add what you put in your DataDownloadEvent class (listeners arrayList and facility methods for adding and removing). You have no immediate need to use a class in that way (static members I mean).
Example
public class DownloadFileClassExample{
private ArrayList<DataDownloadListener> listeners = new ArrayList<DataDownloadListener>();
public DownloadFileClassExample(){
}
public void addDownloadListener(DataDownloadListener listener){
listeners.add(listener);
}
public void removeDownloadListener(DataDownloadListener listener){
listeners.remove(listener);
}
//this is your download procedure
public void downloadFile(){...}
}
Then access you class in this way
DownloadFileClassExample example = new DownloadFileClassExample();
example.addDownloadListener(this); // if your class is implementing the **DataDownloadListener**
or use
example.addDownloadListener( new DataDownloadListener{...})