Save media files to Blackberry SD card - blackberry

I am creating a multimedia app that allows the user to save wallpapers and ringtones. I know the path I need to save them to is "SDCard/BlackBerry/ringtones/file.mp3" (or "/pictures" for wallpapers). I have searched forums and post for a couple days and the only thing I found was how to write text files. For now, assume that the ringtones and pictures are saved in the projects resource folder. If you could provide any input, I would greatly appreciate it.

Saving anything should be about the same. Try something like this:
FileConnection fc;
try {
String fullFile = usedir + filename;
fc = (FileConnection) Connector.open(fullFile, Connector.READ_WRITE);
if (fc.exists()) {
Dialog.alert("file exists");
} else {
fc.create();
fileOS = fc.openOutputStream();
fileOS.write(raw_media_bytes, raw_offset, raw_length);
}
} catch (Exception x) {
Dialog.alert("file save error);
} finally {
try {
if (fileOS != null) {
fileOS.close();
}
if (fc != null) {
fc.close();
}
} catch (Exception y) {
}
}
usedir and filename are your path components, raw_media_bytes is your data, etc etc.

Thanks for your help cjp. Here is the code to saving a resource mp3 file to a sd card:
byte[] audioFile = null;
try {
Class cl = Class.forName("com.mycompany.myproject.myclass");
InputStream is = cl.getResourceAsStream("/" + audioClip);
audioFile = IOUtilities.streamToBytes(is);
try {
// Create folder if not already created
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/ringtones/");
if (!fc.exists())
fc.mkdir();
fc.close();
// Create file
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/ringtones/" + audioClip, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
OutputStream outStream = fc.openOutputStream();
outStream.write(audioFile);
outStream.close();
fc.close();
Dialog.alert("Ringtone saved to BlackBerry SDcard.");
} catch (IOException ioe) {
Dialog.alert(ioe.toString());
}
} catch (Exception e) {
Dialog.alert(e.toString());
}
As cjp pointed out, here is how to save an image resource to a SD card:
EncodedImage encImage = EncodedImage.getEncodedImageResource(file.jpg");
byte[] image = encImage.getData();
try {
// create folder as above (just change directory)
// create file as above (just change directory)
} catch(Exception e){}

Related

Improvements in uploading of files, vaadin

I want to upload file to git without saving on local disk. I use vaadin + java in my webapp, and upload component from vaadin.
public OutputStream receiveUpload(String filename, String MIMEType)
{
this.filename = filename;
FileOutputStream fos = null;
try {
// exist any possibility to no saving file in filepath (only push
// to git)
fos = new FileOutputStream(new File(
filepath + File.separator + filename));
} catch (Exception e) {
// How to omit it, I don't want to save file in filepath...
return null;
}
return fos;
}
public void uploadSucceeded(Upload.SucceededEvent event)
{
try {
// this method read file from filepath. Exist any possibilty to
// transfer file from upload panel to here without saving this
// file in filepath ?
commitToGit(filepath + File.separator + filename);
} catch(Exception e) {
e.printStackTrace();
} finally {
// removing file from filepath, it is no comfortable for me
File file = new File(filepath + File.separator + filename);
if (file != null) {
file.delete();
}
}
}
Look here for the pipe functionality
Best way to Pipe InputStream to OutputStream
in the receiveUpload method you setup the pipe between the uploading file and your git connector.
The uploadSucceeded method is then not needed or can be used to cleanup resources.

How to compress the files in Blackberry?

In my application I used html template and images for browser field and saved in the sdcard . Now I want to compress that html,image files and send to the PHP server. How can I compress that files and send to server? Provide me some samples that may help lot.
i tried this way... my code is
EDIT:
private void zipthefile() {
String out_path = "file:///SDCard/" + "newtemplate.zip";
String in_path = "file:///SDCard/" + "newtemplate.html";
InputStream inputStream = null;
GZIPOutputStream os = null;
try {
FileConnection fileConnection = (FileConnection) Connector
.open(in_path);//read the file from path
if (fileConnection.exists()) {
inputStream = fileConnection.openInputStream();
}
byte[] buffer = new byte[1024];
FileConnection path = (FileConnection) Connector
.open(out_path,
Connector.READ_WRITE);//create the out put file path
if (!path.exists()) {
path.create();
}
os = new GZIPOutputStream(path.openOutputStream());// for create the gzip file
int c;
while ((c = inputStream.read()) != -1) {
os.write(c);
}
} catch (Exception e) {
Dialog.alert("" + e.toString());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("" + e.toString());
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("" + e.toString());
}
}
}
}
this code working fine for single file but i want to compress all the file(more the one file)in the folder .
In case you are not familiar with them, I can tell you that in Java the stream classes follow the Decorator Pattern. These are meant to be piped to other streams to perform additional tasks. For instance, a FileOutputStream allows you to write bytes to a file, if you decorate it with a BufferedOutputStream then you get also buffering (big chunks of data are stored in RAM before being finally written to disc). Or if you decorate it with a GZIPOutputStream then you get also compression.
Example:
//To read compressed file:
InputStream is = new GZIPInputStream(new FileInputStream("full_compressed_file_path_here"));
//To write to a compressed file:
OutputStream os = new GZIPOutputStream(new FileOutputStream("full_compressed_file_path_here"));
This is a good tutorial covering basic I/O . Despite being written for JavaSE, you'll find it useful since most things work the same in BlackBerry.
In the API you have these classes available:
GZIPInputStream
GZIPOutputStream
ZLibInputStream
ZLibOutputStream
If you need to convert between streams and byte array use IOUtilities class or ByteArrayOutputStream and ByteArrayInputStream.

How to copy database into device in Blackberry

i am developing app for blackberry which have Database as back-end. Database has some data so i am import that database from res to sdcard it is working perfectely in the simulator.
When i install my app into device then it is not working what can be the issue i could not understand. Below is my code..
call Method
DatabseCopy db=new DatabseCopy();
db.copyFile("/nm.db","file:///SDCard/Databases/nm.db");
Method
public void copyFile(String srFile, String dtFile)
{
try
{
FileConnection fconn;
fconn = (FileConnection) Connector.open(dtFile,Connector.READ_WRITE);
if(!fconn.exists()) // if file does not exists , create a new one
{
fconn.create();
}
InputStream is = (InputStream)this.getClass().getResourceAsStream(srFile);
OutputStream os =fconn.openOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
{
os.write(buf, 0, len);
}
is.close();
os.close();
}
catch(IOException e)
{
System.out.println("Exception"+e.getMessage()) ;
}
}
Try this:
Before trying this: you have to check the SDCARD is there or not and
System.getProperty("fileconn.dir.memorycard")
Gives directly the path upto:
file:///SDCard/
and then your filename;
private void copyFromResToSDCard()
{
try
{
InputStream is=(InputStream)getClass().getResourceAsStream("/ManualRecords.db");
FileConnection fileconn=(FileConnection)Connector.open(System.getProperty("fileconn.dir.memorycard")+"ManualRecords.db");//Here set your Path with new fileName.db;
if(fileconn.exists())
{
fileconn.delete();
}
fileconn.create();
byte data[]=new byte[is.available()];
data=IOUtilities.streamToBytes(is);
OutputStream os=fileconn.openOutputStream();
os.write(data);
fileconn.close();
is.close();
os.close();
}
catch (Exception e)
{
System.out.println("=============="+e.getMessage());
}
}
Enough;

How to find the url of the uploaded video in YouTube (Through Youtube API)

I am using the following code to upload a video to Youtube through youtube API. My problem is after uploading the video, I need to give the location of the video to the user. How do I find this ?
I'll be really grateful if someone can help me to solve this.
MediaFileSource ms = new MediaFileSource(videoFile, mimeType);
String videoTitle = title;
VideoEntry newEntry = new VideoEntry();
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Tech"));
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent(videoTitle);
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("yt:crop=16:9");
mg.setDescription(new MediaDescription());
mg.getDescription().setHtmlContent(attributionDocument);
mg.setPrivate(true);
mg.setVideoId("Vid1");
ResumableGDataFileUploader uploader = null;
try {
uploader = new ResumableGDataFileUploader.Builder(
service, new URL(RESUMABLE_UPLOAD_URL), ms, newEntry)
.title(videoTitle)
.build();
uploader.start();
while (!uploader.isDone()) {
try {
Thread.sleep(PROGRESS_UPDATE_INTERVAL);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
switch(uploader.getUploadState()) {
case COMPLETE:
System.out.println("Uploaded successfully");
break;
case CLIENT_ERROR:
System.out.println("Upload Failed");
break;
default:
System.out.println("Unexpected upload status");
break;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
I managed to solve this by myself. Instead of using resumable file upload, I used direct upload. My code:
String id = "";
File videoFile = new File(videoLocation);
if (!videoFile.exists()) {
System.out.println("Sorry, that video doesn't exist.");
}
String videoTitle = title;
VideoEntry newEntry = new VideoEntry();
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent(videoTitle);
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("yt:crop=16:9");
mg.setDescription(new MediaDescription());
mg.getDescription().setHtmlContent(attributionDocument);
mg.setPrivate(true);
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Tech"));
MediaFileSource ms = new MediaFileSource(videoFile, "video/quicktime");
newEntry.setMediaSource(ms);
String uploadUrl =
"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
VideoEntry createdEntry = service.insert(new URL(uploadUrl), newEntry);
id =createdEntry.getId();
return id;
}
I hope this will save someone else's day.

Blackberry: Download and display .jpg image

I am trying to pull a .jpg image off of a server, and display it as and EncodedImage in a ZoomScreen. Because this .jpg could be very large I want to save the .jpg to a file and read it from there so i don't have the whole thing sitting in memory.
The problem I'm facing is that Connector.open("http.url.com/file.jpg") is either throwing an IOException with the message "Bad Socket Id", or it is throwing a ClassCastException when i attempt to open a FileConnection to the URL. Here is an example of what i've tried:
try {
FileConnection fileIn = (FileConnection)Connector.open(fileURL);
FileConnection fileOut = (FileConnection)Connector.open(fileDest);
if(!fileOut.exists())
fileOut.create();
InputStream is = fileIn.openInputStream();
OutputStream os = fileOut.openOutputStream();
while(fileIn.canRead() && fileOut.canWrite()){
os.write(is.read());
}
is.close();
os.close();
fileIn.close();
fileOut.close();
EncodedImage image = EncodedImage.getEncodedImageResource(fileDest);
UiApplication.getUiApplication().pushScreen(new ZoomScreen(image));
} catch (Exception e) {
e.printStackTrace();
}
I'm getting most of this from RIM, but I'm missing something. I know the url is correct because i use the same format when i stream audio from the same server. The exception is being thrown on the first line, when i attempt to connect to the server.
Does anyone have experience with this?
Figured it out.
try {
HttpConnection conn = (HttpConnection) Connector.open(fileURL);
InputStream fileIn = conn.openInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
for(int i = fileIn.read(); i > -1; i = fileIn.read()){
os.write(i);
}
byte[] data = os.toByteArray();
EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length);
UiApplication.getUiApplication().pushScreen(new ZoomScreen(image));
} catch (Exception e) {
e.printStackTrace();
}
I hope other people will find this useful.
public void run(){
try{
StreamConnection streamC = (StreamConnection) Connector.open(url+";deviceside=true");
InputStream in = streamC.openInputStream();
byte[] data = new byte[4096];
data = IOUtilities.streamToBytes(in);
in.close();
EncodedImage eImage = EncodedImage.createEncodedImage(data, 0, data.length);
}
catch(Exception e)
{
e.printStackTrace();
}

Resources