problem to store data into sdcard - android

i have problem to store image into sd car, there are not display file in sdcard which i want.
this is code.
package com.sdcard;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class SdcardActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
URL url = new URL ("http://www.coolpctips.com/wp-content/uploads/2011/05/top-30-android- games.jpg");
InputStream input = url.openStream();
try {
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/top-30-android-games.jpg");
try {
int aReasonableSize = 10;
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, buffer.length);
}
} finally {
output.close();
}
} finally {
input.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}}

add this lines in your code:
catch (Exception e) {
e.printStackTrace();
}
and you will notice an exception that the url is malformed. Add more information about what you want to achieve so that I can write a better answer.
The exception in your comment might be related with some kind of a bug in Android:
http://code.google.com/p/android/issues/detail?id=2764. You can try with this solution: Android java.net.UnknownHostException: Host is unresolved (strategy question) or give IP address instead of DNS.
Here you have tested code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
URL url = new URL ("http://www.coolpctips.com/wp-content/uploads/2011/05/top-30-android-games.jpg");
InputStream input = url.openStream();
try {
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/top-30-android-games.jpg");
int aReasonableSize = 1000;
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;;
try {
while ((bytesRead = input.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}

you should use Environment.getExternalStorageDirectory() instead of mnt/sdcard/
OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/myImage.png");

Your problem is you are referencing your host computers local filesystem inside your android device. C:\ isn't a path that android knows how to interpret.
Host it on a local webserver then use something like http://192.168.0.100/your/url/image.png

Related

how to and input files to apk that can be read from C++?

I use JNI to develop my app, and there are two .dat files used as input files in C++ layer. At present, I push these two files into mobile devices through adb before open related app. I think there is a better solution to prevent from pushing two files into mobile devices.
after trying several solutions, I have solved it by combining three solutions, and the code shown below. Before using the code, you need to create a folder called "assets" parallel to "res" folder. Through this way, you can attach the input file you may use to the apk, and when installing the apk first time, it will automatically store the files to specific path in the target device.
public class CameraPreviewActivity extends AppCompatActivity
implements CameraPermissionHelper.CameraPermissionCallback {
SharedPreferences prefs = null;
public static String TAG = "CameraPreviewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences("com.yourcompany.yourapp", MODE_PRIVATE);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
if(prefs.getBoolean("firstrun", true)){
prefs.edit().putBoolean("firstrun", false).commit();
try {
final InputStream input = getResources().getAssets().open("face_model.dat");
try {
File UPLOAD_DIR = new File("/sdcard");
File file = new File(UPLOAD_DIR, "face_model.dat");
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace(); // handle exception, define IOException and others
}
} finally {
input.close();
}
}catch (IOException e){
e.printStackTrace();
}
try {
final InputStream input = getResources().getAssets().open("shape_pred.dat");
try {
File UPLOAD_DIR = new File("/sdcard");
File file = new File(UPLOAD_DIR, "shape_pred.dat");
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace(); // handle exception, define IOException and others
}
} finally {
input.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}

How to merge the two audio files into a single audio file in android?

I want to get two audio files as input, then merge them byte wise and save it as a single file.
In this code I have tried to do it in Java and it's working fine, but I don't know how to do it in android.
How to do it in android?
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class FileMixer {
public static void main(String[] args)
{
try
{
Path path1 = Paths.get("C:\\Srini\\Wav\\welcome.wav");
Path path2 = Paths.get("C:\\Srini\\Wav\\goodbye.wav");
String path3 ="C:\\Srini\\Wav\\srini12.wav";
File Newfilepath=new File(path3);
byte[] byte1 = Files.readAllBytes(path1);
byte[] byte2 = Files.readAllBytes(path2);
byte[] out = new byte[byte1.length];
for (int i=0; i<byte1.length; i++)
{
out[i] = (byte) ((byte1[i] + byte2[i]) >> 1);
}
InputStream byteArray = new ByteArrayInputStream(out);
AudioInputStream ais = AudioSystem.getAudioInputStream(byteArray);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE,Newfilepath);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
For combining two wav files use this code,
import java.io.File;
import java.io.IOException;
import java.io.SequenceInputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class WavAppender {
public static void main(String[] args) {
String wavFile1 = "D:\\wavOne.wav";
String wavFile2 = "D:\\wavTwo.wav";
try {
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));
AudioInputStream appendedFiles =
new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
AudioSystem.write(appendedFiles,
AudioFileFormat.Type.WAVE,
new File("D:\\wavAppended.wav"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
It is too late. But still, someone might need a proper solution. That is why I am suggesting using AudioMixer-android library. You can also perform a lot of audio processing things.

Android: EACCES (Permission denied) , while I added the uses-permisson in manifest

I'm using a very simple code to download an Image from my localhost : here it is :
package com.pep.www.imagedownloader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
download();
}
});
thread.start();
}
});
}
public void download(){
int read = -1;
byte[] buffer = new byte[5*1024];
URL url = null;
HttpURLConnection ucon = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
File file = null;
try {
url = new URL("http://192.168.1.128/image.jpg");
ucon = (HttpURLConnection) url.openConnection();
inputStream = ucon.getInputStream();
file = new File("mnt/sdcard/image.jpg");
fileOutputStream = new FileOutputStream(file);
while((read=inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer,0,read);
Log.i("LOG","Downling : "+read);
}
Log.i("LOG","Downloaded");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
While I've added this permission in manifest :
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I still get this error :
java.io.FileNotFoundException: mnt/sdcard/image.jpg: open failed: EACCES (Permission denied)
EDIT :
when I change my file path to this :
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/image.jpg ");
I still get this error :
java.io.FileNotFoundException: /storage/sdcard/Pictures/aylar.jpg : open failed: EACCES (Permission denied)
EDIT :
Instead of being so childish and giving downVotes , solve the problem !
Stackoverflow has become a place to play childish games :(
Firstly let me tell you one thing If you are using an emulator then the code will not work you need a real device.As we know we give permission to store image in external storage So You can use this method to save your image and then get back.
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,"myImage.png"));
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
try to use this
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
{
file =new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/image.jpg ");
if(!file.exists())
file.createNewFile();
}
replace
file = new File("mnt/sdcard/image.jpg");
with
file = new File("file:///sdcard/image.jpg");
its simple code any file like image,video,audio etc we can download it.
Button start;
//String HttpMyUrl="http://am.cdnmob.org/_/img/loader-small.gif";
String HttpMyUrl="http://ringtones.mob.org/ringtone/RIusrm-7xATkRQlLw1o89w/1424909358/fa1b23bb5e35c8aed96b1a5aba43df3d/stefano_gambarelli_feat_pochill-land_on_mars_v2.mp3";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start= (Button) findViewById(R.id.startBtn);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(HttpMyUrl));
request.setTitle("File Download");
request.setDescription("File is being Downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String fileName = URLUtil.guessFileName(HttpMyUrl,null, MimeTypeMap.getFileExtensionFromUrl(HttpMyUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
DownloadManager manager =(DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});

How to copy files from assets to sd card during Installation

I am not able to copy files from my assets folder to the Sd card. How can I accomplish this? Or is there a way to copy files from assets or any other folder to sd card during installation of the app?
Here is my code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CopyAssets();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream("/sdcard/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
You should not hard code storage directory . use Environment.getExternalStorageDirectory()
String destFile = Environment.getExternalStorageDirectory().toString().concat("/ans");
try {
File f2 = new File(destFile);
InputStream in = getAssets().open("try.xml");
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out
.println(ex.getMessage() + " in the specified directory.");
} catch (IOException e) {
System.out.println(e.getMessage());
}
add permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
To write files in the sdcard you have to give the permission on the manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Did you?
Add this code to your onCreate. So the first time your app starts after installation the function to copy assets to SD card and then its never called as you enter the app again.
SharedPreferences score = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor score_inc = score.edit();
int counter = score.getInt("counter",0);
float font_size = score.getFloat("font_size",20.0f);
if(counter==0)
{
//Put your function to copy files here
score_inc.putInt("counter", ++counter);
score_inc.commit();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}

how to read bytes from a video file in android

I have a question that I want to read bytes from video resided in sdcard in chunk size 1024,
means I have to read 1024 bytes from the file at a time. I am able to fetch number of bytes from the video but I can't get it in chunks, I don't know how to achieve this. Please suggest me the right solution regarding the same.
Thanks in advance.
import java.io.*;
public class FileUtil {
private final int BUFFER_SIZE = 1024;
public void readFile(String fileName) {
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
int n = 0;
while ((n = in.read(buffer, 0, BUFFER_SIZE)) > 0) {
/* do whatever you want with buffer here */
}
}
catch(Exception e) {
e.printStackTrace();
}
finally { // always close input stream
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Based on the code from http://www.xinotes.org/notes/note/648/

Categories

Resources