I am executing this code to save some data to a file in my android phone but when saving it the FileNotFoundException triggers and I dont know why since I copy from many different places but is not working for me.
Hints?
public void safeToExcelFile(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
}
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
String fileName = "hola" + ".txt";
String contenido = "pues algo a ver si va";
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS);
File dir = new File(root.getAbsolutePath()+"/MyAppFile");
if(!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, fileName);
Toast.makeText(this, dir.getPath(), Toast.LENGTH_LONG).show();
try{
FileOutputStream fos = new FileOutputStream(file);
fos.write(contenido.getBytes());
fos.close();
Toast.makeText(this, "Se guardo", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "Archivo no encontrado", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, "Error al guardar", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}else{
Toast.makeText(this, "No puedes guardar", Toast.LENGTH_LONG).show();
}
}
Toma hermano
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
String fileName = "hola" + ".txt";
String contenido = "pues algo a ver si va";
String path = getExternalFilesDir(null) + "/" + fileName;
try{
FileOutputStream fos = new FileOutputStream(path);
fos.write(contenido.getBytes());
fos.close();
Toast.makeText(this, "Se guardo", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Toast.makeText(this, "Archivo no encontrado", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, "Error al guardar", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}else{
Log.d("Error", "No hay permiso");
}
Haz un log del path y verás dónde se guarda el fichero. Es el sitio correcto para almacenar ficheros locales.
I finnaly figured out the answer, i got the solution from https://blog.cindypotvin.com/saving-data-to-a-file-in-your-android-application/ if you are interested
try {
File testFile = new File(this.getExternalFilesDir(null), "Cuentas.csv");
if (!testFile.exists())
testFile.createNewFile();
Toast.makeText(this, testFile.getPath(), Toast.LENGTH_LONG).show();
// Adds a line to the file
BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true));
writer.write("This is a test file.");
writer.close();
// Refresh the data so it can seen when the device is plugged in a
// computer. You may have to unplug and replug the device to see the
// latest changes. This is not necessary if the user should not modify
// the files.
MediaScannerConnection.scanFile(this,
new String[]{testFile.toString()},
null,
null);
} catch (IOException e) {
//Log.e("ReadWriteFile", "Unable to write to the TestFile.txt file.");
Toast.makeText(this, "Error al guardar", Toast.LENGTH_LONG).show();
}
Related
Hello everyone i try to get commands from txt file and I want to run these commands in order for a certain period of time.I can get the commands from the txt file correctly but when I want to do these commands using handlers for a certain period of time but there is a problem.The problem is handlers work together,the other Handler comes into play before the first Handler's time expires.When i did that with same runnable it did same thing.
My txt file looks like:
Ileri,5,1 /n
Sol,10,1 /n -->10 is operation time 1 is The number of repetitions.
Sag,5,1 /n
Geri,10,1 /n
My output:
I/System.out: Ileri
6000
1
I/System.out: Sol
11000
1
I/System.out: Sag
6000
1
I/System.out: Geri
11000
1
I/System.out: A
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer=new Timer();
String yon;
String saniye1;
String tekrar;
int i=0,j=0,c=0,d=0;
ArrayList<String> listS=new ArrayList<String>();
try {
Scanner s=new Scanner(new File("/data/data/com.example.emrecan.myapplication/files/komutlar.txt"));
while(s.hasNextLine())
{
listS.add(s.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] line2=new String[100];
for(String str:listS)
{
String[] line=str.split(",");
line2[c]=line[i];
line2[c+1]=line[i+1];
line2[c+2]=line[i+2];
c=c+3;
}
//String gonderilecek=new String();
String [] line3=new String[c+2];
while(d<c)
{
line3[d]=line2[d];
d=d+1;
}
d=0;
tekrar=line3[2];
int tekrar1=Integer.parseInt(tekrar);
while(d<tekrar1)
{
while(j<=c-2)
{
yon = line3[j];
saniye1 = line3[j + 1];
sure1 = Long.parseLong(saniye1);
sure1=sure1*1000;
sure1=sure1+1000;
System.out.println(yon);
System.out.println(sure1);
System.out.println(tekrar1);
e=0;
switch (yon)
{
case "Ileri":
runnable=new Runnable() {
#Override
public void run() {
sure1=sure1-1000;
if(sure1>0)
{
handler.postDelayed(this,1000);
mp.start();
}
else
{
handler.removeCallbacks(runnable);
}
}
};
handler.postDelayed(runnable,1000);
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Sol":
runnable2=new Runnable() {
#Override
public void run() {
sure1=sure1-1000;
if(sure1>0)
{
handler.postDelayed(this,1000);
mp2.start();
}
else
{
handler.removeCallbacks(runnable2);
}
}
};
handler.postDelayed(runnable2,1000);
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Sag":
runnable3=new Runnable() {
#Override
public void run() {
sure1=sure1-1000;
if(sure1>0)
{
handler.postDelayed(this,1000);
mp3.start();
}
else
{
handler.removeCallbacks(runnable3);
}
}
};
handler.postDelayed(runnable3,1000);
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Geri":
runnable4=new Runnable() {
#Override
public void run() {
sure1=sure1-1000;
if(sure1>0)
{
handler.postDelayed(this,1000);
mp4.start();
}
else
{
handler.removeCallbacks(runnable4);
}
}
};
handler.postDelayed(runnable4,1000);
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(), "Sıkıntı var!", Toast.LENGTH_LONG).show();
break;
}
j=j+3;
}
j=0;
d=d+1;
System.out.println('A');
}
}
});
I solved my problem by using thread.sleep(); and i'm writing here because someone might need my code.
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer=new Timer();
///data/data/com.example.emrecan.myapplication/files/komutlar.txt
String yon;
String saniye1;
String tekrar;
int i=0,j=0,c=0,d=0;
ArrayList<String> listS=new ArrayList<String>();
try {
Scanner s=new Scanner(new File("/data/data/com.example.emrecan.myapplication/files/komutlar.txt"));
while(s.hasNextLine())
{
listS.add(s.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] line2=new String[100];
for(String str:listS)
{
String[] line=str.split(",");
line2[c]=line[i];
line2[c+1]=line[i+1];
line2[c+2]=line[i+2];
c=c+3;
}
String [] line3=new String[c+2];
while(d<c)
{
line3[d]=line2[d];
d=d+1;
}
d=0;
tekrar=line3[2];
int tekrar1=Integer.parseInt(tekrar);
while(d<tekrar1)
{
while(j<=c-2) {
yon = line3[j];
saniye1 = line3[j + 1];
sure1 = Long.parseLong(saniye1);
sure1 = sure1 * 1000;
//sure1 = sure1 + 1000;
System.out.println(yon);
System.out.println(sure1);
System.out.println(tekrar1);
e = 0;
while (sure1>0)
{
switch (yon) {
case "Ileri":
try {
outputStream.write(1);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Sol":
try {
outputStream.write(2);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Sag":
try {
outputStream.write(3);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Geri":
mp4.start();
try {
outputStream.write(4);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
default:
Toast.makeText(getApplicationContext(), "Sıkıntı var!", Toast.LENGTH_LONG).show();
break;
}
sure1=sure1-1000;
}
j=j+3;
}
j=0;
d=d+1;
System.out.println('A');
}
try {
outputStream.write(10);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
I am posting some data to server but i am getting {"status":false,"error":"Invalid API Key."} response from server. My API Key is correct but where is the problem i don't know. Please friends help me. I tried lot but i did not find solution. I have used following code for posting data to server.
public void tryingOne(String dtl){
HttpConnection httpConn = null;
InputStream is = null;
OutputStream os = null;
String url="http://api.geanly.in/ma/index?API-Key="+apikey;
String details = "&orderInfo={\"booking\":{\"restaurantinfo\":{\"id\":\"5722\"},\"referrer\":{\"id\": \"9448476530\" }, \"bookingdetails\":{\"instructions\":\"Make the stuff spicy\",\"bookingtime\": \"2011-11-09 12:12 pm\", \"num_guests\": \"5\"}, \"customerinfo\":{\"name\":\"Vinodh SS\", \"mobile\":\"9345245530\", \"email\": \"vind#gmail.com\", \"landline\":{ \"number\":\"0908998393\",\"ext\":\"456\"}}}}";
try {
System.out.println("url####"+url);
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream outStream = new DataOutputStream(httpConn.openDataOutputStream());
outStream.write(details.getBytes(),0,details.length());
outStream.flush();
outStream.close();
//Reading Resp. from server
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1) {
sb.append((char) chr);
}
System.out.println("Response from srvr " + sb.toString());
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (httpConn != null) {
try {
httpConn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Please help me friends...
Thanks
you need to trim the variable "apikey".
I was getting same problem when connecting with Picasa Server.
For sending data using HttpConnection use the class in this tutorial. It also gets the response from the server.
please can anyone tell me how to store the RMS data to file and how to modify it?
You can use this code for write the data in a file.
private void writeTextFile(String fName, String text) {
DataOutputStream dos = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
dos = fconn.openDataOutputStream();
dos.write(text.getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (dos != null)
dos.close();
if (fconn != null)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
I had a part of code which suppose to get an image from website and store it into the sdcard. The following code was working find when i develop on sdk1.5. However, it was not working now after i change it to android sdk 2.0. This line got problem; FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename);
Here is the code that i have:
void downloadFile(String fileUrl) {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(filepath + "/"
+ this.filename);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
Context context = this.getBaseContext();
new MediaScannerNotifier2(context, filepath + "/" + this.filename,
"image/jpeg");
// displaying download completion message
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Wallpaper Downloaded").setCancelable(false)
.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
btn_setwall.setEnabled(true);
btn_download.setEnabled(false);
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (Exception e) {
Log.e("MyLog", e.toString());
}
}
The error occur in the 3rd catch. However, when i move this line
FileOutputStream fos = new
FileOutputStream(filepath + "/" +
this.filename);
to the 2nd try/catch, then it will occur in the 2nd catch.
Can please help me on this?
Maybe try getting rid of .getAbsolutePath()
This works for me on 2.2:
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);
I'm trying to play a recorded wave file. While playing, an exception is thrown at the following statement:
Player player = Manager.createPlayer(is, "audio/mpeg");
My entire code for playing the wave file is as follows:
if (types[cnt].equals("audio/x-wav")) {
Class clazz = Class.forName("RecordAudio");
InputStream is =
clazz.getResourceAsStream("file:///SDCard/BlackBerry/original.wav");
//create an instance of the player from the InputStream
Player player = Manager.createPlayer(is, "audio/mpeg");
player.realize();
player.prefetch();
//start the player
player.start();
}
What could be the problem?
The function getResourceAsStream is for pulling resources from a JAR/COD file, not from the filesystem. Plus, this is simpler than you are making it. Just pass the file name and path to createPlayer, like so:
try {
String filename = "file:///SDCard/BlackBerry/original.wav";
Player player = javax.microedition.media.Manager.Manager.createPlayer( filename );
} catch (IOException e) {
System.out.println("Error creating player");
} catch (MediaException e) {
System.out.println("Error media type");
}
I believe it is because of wrong MIME type. Try this:
String fileName = "file:///SDCard/BlackBerry/original.wav";
String mimeType = "audio/x-wav";
String types[] = javax.microedition.media.Manager
.getSupportedContentTypes(null);
for (int cnt = types.length - 1; cnt >= 0; --cnt) {
if (types[cnt].equals(mimeType)) {
InputStream is = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open(
fileName, Connector.READ);
} catch (IOException e) {
System.out.println("Error reading file");
}
try {
is = fconn.openInputStream();
} catch (IOException e) {
System.out.println("Error opening stream");
}
Player player = null;
try {
player =
javax.microedition.media.Manager.createPlayer(
is, mimeType);
} catch (IOException e) {
System.out.println("Error creating player");
} catch (MediaException e) {
System.out.println("Error media type");
}
try {
player.realize();
} catch (MediaException e) {
System.out.println("Player cannot be released");
}
try {
player.prefetch();
} catch (MediaException e) {
System.out.println("Player cannot be prefetched");
}
// start the player
try {
player.start();
} catch (MediaException e) {
System.out.println("Player cannot be started");
}
}
}
Also see in console what kind of exception was thrown.