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.
Related
I just want to rename a file through android code my code is below. when I use fin.renameTo() function as in below code this rename function is completely ignored and it doesn't display any of message either true or false. my current API Level is 27
btnRenameFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
File fin = new File("/storage/sdcard1/VideoFiles/ADHM.mp4");
File fout = new File("/storage/sdcard1/VideoFiles/ADHM.mp4.xyz");
if(fin.exists()) {
Toast.makeText(getApplicationContext(),"File Exists",Toast.LENGTH_LONG).show();
if (fin.renameTo(fout))
Toast.makeText(getApplicationContext(),"Renamed Successfully",Toast.LENGTH_LONG).show();
else Toast.makeText(getApplicationContext(),"Not Renamed",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(),"File Does not Exist",Toast.LENGTH_LONG).show();
}
}
catch (Exception ex){
Toast.makeText(getApplicationContext(),ex.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
First of all, kindly confirm whether renameTo() is successful with simple if statement.
if (fin.renameTo(fout))
{
System.out.println("File renamed successfully");;
}
else
{
System.out.println("File rename failed");;
}
Since it is platform dependent and Exception is not thrown when rename failed.
Also, fout file format is changed to .xyz
Try ADHM_XYZ.mp4
File fin = new File("/storage/sdcard1/VideoFiles/ADHM.mp4");
File fout = new File("/storage/sdcard1/VideoFiles/ADHM.mp4.xyz");
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 just playing around with Android Studio and I'm trying to figure out how to Download a file into /system.
I understand I need root for this and I already got that part working, the only trouble I'm having is with
request.setDestinationInExternalPublicDir("/system/", "test.jpg");
The goal is to download a file and save it to /system with the file name being test.jpg.
So the end is the file is located at /system/test.jpg.
The issue with this is that DownloadManager is saving it to internal storage and is creating a new folder named 'system'.
I can tell it has something to do with setDestinationInExternalPublicDir but I'm just not sure what to change it to.
Thanks again
What I did is that:
(It's a part in one of my projects)
/*****DOWNLOAD FILE*****/
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://github.com/pelya/android-keyboard-gadget/blob/master/hid-gadget-test/hid-gadget-test?raw=true"));
request.setDescription("hid-gadget-test");
request.setTitle("hid-gadget-test");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "hid-gadget-test"); /*****SAVE TO DOWNLOAD FOLDER*****/
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
File mvfile = new File("/sdcard/"+Environment.DIRECTORY_DOWNLOADS+"/hid-gadget-test");
while (!mvfile.exists()) {} /*****WAIT UNTIL DOWNLOAD COMPLETE*****/
try {
Thread.sleep(5000);
} catch (InterruptedException ignored) {}
try { /*****RUN MV-COMMAND TO MOVE TO ROOT DIR*****/
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes("mv /sdcard/"+Environment.DIRECTORY_DOWNLOADS+"/hid-gadget-test /data/local/tmp/hid-gadget-test\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "IOException", Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
Toast.makeText(getApplicationContext(), "InterruptedException", Toast.LENGTH_SHORT).show();
}
The wait-until-download-complete-thingy is a bit hacky, I found it here. It will maybe not work with files that take more than 5 seconds to download
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).
Sound does not play when I run the JAR, but it does when I run it in eclipse.
Here is where I load the clips:
public void init(){
System.out.println("grabbing Music");
String currentDir = new File("").getAbsolutePath();
name=new File(currentDir+"\\music\\").list();
clip=new Clip[name.length];
soundFile=new File[name.length];
for(int x=0;x<name.length;x++){
System.out.println(currentDir+"\\music\\"+name[x]);
try {
soundFile[x]= new File(currentDir+"\\music\\"+name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile[x]);
DataLine.Info info= new DataLine.Info(Clip.class, sound.getFormat());
clip[x] = (Clip) AudioSystem.getLine(info);
clip[x].open(sound);
clip[x].addLineListener(new LineListener(){
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
}
}
});
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
}
I do not get any errors when running it in Eclipse. There should be no possibility of an invalid directory error, so what is wrong?
-When the jar is run in CMD i get no errors.
edit: I feel like I am loading the audio wrong, hence why I pasted the code I used to load the files in. In my searches I haven't seen anyone use File to load in a sound file. Wonder if that is the problem?
First thing that goes into my mind is that you didn't attached your sound library classes into your jar.
In order to run your current code, the folder music should be in the same folder the jar file is located in.
Another solution is to package your music folder inside the jar file and then change your code to:
InputStream is = getClass().getResourceAsStream("/music/" + name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(is);
How about-
Right click on your project in Eclipse. Then New -> Source Folder.
Name the source folder anything. e.g. music_src.
Copy or drag the entire music directory in music_src. Then make the jar.
File systems have a hard time looking into jars.
Try using URL instead. A URL can locate a location within a jar. This happens a lot with folks trying to access resources in jars for the first time.
Otherwise things look fine.