How do I select multiple images using cn1 file chooser - codenameone

I am creating a mobile app where I need users to be able to select multiple images. I am using the cn1 lib file chooser but I am only able to select one Image. How can I select multiple images. Here is the code I use to select the image.
chooseImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
animateImage.show();
if (FileChooser.isAvailable()){
FileChooser.showOpenDialog(".jpg,.png,.gif", e2->{
String file = (String)e2.getSource();
if (file == null){
animateImage.add("No File Was Selected");
animateImage.revalidate();
}else {
String extension = null;
if (file.lastIndexOf(".") > 0){
extension = file.substring(file.lastIndexOf(".")+1);
}
if ("txt".equals(extension)){
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream fis = fs.openInputStream(file);
animateImage.addComponent(new SpanLabel(Util.readToString(fis)));
} catch (Exception ex) {
Log.e(ex);
}
}else{
try{
Image image = URLImage.createImage((String)e2.getSource());
animateImage.add(image);
}catch (IOException e){
e.printStackTrace();
}
//animateImage.add("Selected file "+file);
}
}
animateImage.revalidate();
});
/*try{
Image image = URLImage.createImage((String)evt.getSource());
animateImage.add(image);
}catch (IOException e){
e.printStackTrace();
}*/
}
}
});
Thanks

There is no support for that in the cn1lib. You can fork the cn1lib and add support for it manually by changing the native code in the lib.
This isn't supported currently in the standard Codename One API, there is an RFE to add it here: https://github.com/codenameone/CodenameOne/issues/2383

Related

Temp png file from storage not uploading

Okay, I don't believe this is a cn1 issue, but I am running out of options. I have an app and I have been using the Capture.capturePhoto to give the user the ability to snap a photo with their device and upload it to my server. Has been working great for several months now. I have been asked to add the ability to upload a photo from the mobiles photo gallery, I thought it would be trivial, but after figuring out how to scale the image down and store it in Storage, I am now stumped with it just sending 0 bytes to my server.
I know it's not my server, that has not changed and can still upload files from various sources including the ones captured with the photo in the cn1 app.
Here is the code that uploads the photo
private void uploadImage(String filename, String name) throws IOException {
String ext = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
if (ext.equals("jpg") || ext.equals("jpeg") || ext.equals("pjpeg") || ext.equals("png")) {
MultipartRequest request = new MultipartRequest() {
Hashtable h;
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
h = p.parse(new InputStreamReader(input));
super.readResponse(input);
}
#Override
protected void postResponse() {
List<Map<String, Object>> media = (List<Map<String, Object>>)h.get("media");
Dialog.show("Photo Uploaded", media.size() + " photo(s) uploaded and available to send.", "OK", null);
}
};
request.setUrl(MyApplication.IMGSERVER);
request.setPost(true);
request.addData(name, filename, "image/" + ext);
request.addRequestHeader("X-Dart-Token", token);
NetworkManager.getInstance().addToQueue(request);
} else {
Dialog.show("Invalid Photo Format", "The photo format (" + ext+ ") is not supported. Try with jpg or png.", "OK", null);
}
}
Here is the relevant parts of code that get and scale the photo from the gallery
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent != null && actionEvent.getSource() != null) {
String filepath = (String)actionEvent.getSource();
if (filepath != null) {
// scale down the image
String filename = "tempfile.png";
boolean success = false;
if (Storage.isInitialized()) {
try {
OutputStream out = Storage.getInstance().createOutputStream(filename);
ImageIO.getImageIO().save(filepath, out, ImageIO.FORMAT_PNG, 500, -1, 1);
out.close();
success = true;
} catch (IOException e1) {
Log.p("image scaling failed " + e1.getMessage());
Dialog.show("Photo Upload", "Unable to scale photo:" + e1.getMessage(), "OK", null);
}
if (success) {
// open dialog and have user provide name
try {
String tmpFilepath = FileSystemStorage.getInstance().getAppHomePath() + filename;
Dialog.show("Image File", tmpFilepath, "OK", null);
uploadImage(tmpFilepath, name);
} catch (IOException err) {
Log.p("Image Upload Failed:" + err.getMessage());
Dialog.show("Picture Uploaded Failed", "Something prevented the upload of the image.", "OK", null);
}
}
}
}
}
}
I purposely cut out a lot of the surrounding code in the above snippet to focus on what I believe to be important.
I left in the Dialog statements that I am using for debugging so I can see what the path is on the device. If I run this in the simulator, and choose a file, it uploads fine, but when I run it on an iPhone, the file sent to the server has 0 bytes, and the Dialog in the uploadImage method will display that '0 photo(s) uploaded'. When using Storage.g.entrySize() on "tempfile.png" it displays the file has not being 0 in size. How can I properly reference this file to send it to the server.
You are saving the gallery image to Storage but the upload method works with FileSystemStorage those aren't compatible so you get incompatible behaviors.

Downloading Files added into database in Angularjs and Spring mvc

I am facing an issue while downloading the file added into the database. I am using AngularJS and Spring MVC architecture.
In a table I am displaying filenames I have added.
Here is my html
fee.html
<td><a href="./filedownload/{{fee.fileName}}/feespath">
{{fee.fileName}}</a></td>
Here is Spring Controller.java
#RequestMapping(value="/filedownload/{fileName:.+}/{path}",method=
{RequestMethod.GET,RequestMethod.POST})
public void filedownload(#PathVariable String
fileName,#PathVariable String path,HttpServletResponse response)
{
Path file = Paths.get(context.getRealPath("/"+path+"/"),
fileName);
if (Files.exists(file))
{
response.setContentType("*/*");
response.addHeader("Content-Disposition", "attachment;
filename="+fileName);
try
{
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
And while adding I am using "feespath" as the path name that I am using in my html. Here is how I am creating a path by name feespath
#RequestMapping(value="/uploadFeeFiles",method=
{RequestMethod.GET,RequestMethod.POST})
public #ResponseBody String uploadFeeFiles(HttpServletRequest
request,HttpServletResponse response,MultipartHttpServletRequest
mRequest,Principal principal)
{
String status="";
try
{
mRequest = (MultipartHttpServletRequest) request;
mRequest.getParameterMap();
Iterator<String> itr = mRequest.getFileNames();
while (itr.hasNext())
{
MultipartFile file = mRequest.getFile(itr.next());
String fileName =
uploadPathService.getFilesPath(file,"feespath");
status = fileName;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return status;
}
I am able to display file names correctly in the table but if I click on it it's redirecting to a blank page with url
http://localhost:8080/MyProject/filedownload/12802889_1263849593630301.jpg/feespath
So I am not able to figure it out. If anyone can introduce some ideas, I'll be very helpful.

Write/Read the image from fileSystemStorage and readjust it before saving

I have saved an image using fileSystemStorage with the name of "profile.png". But how cab I read the image and display it afterward. I had used Storage.getInstance.writeObject and
readObject before but I think it doesnt work for images.
userImg.addActionListener((e) -> {
Display.getInstance().openGallery(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
if (evt == null) {
System.out.println("user cancelled");
return;
}
eventImgpath = (String) evt.getSource();
Image i = Image.createImage(eventImgpath);
Image profileImg = i.scaledWidth(Display.getInstance().getDisplayWidth() / 3);
InputStream stream = FileSystemStorage.getInstance().openInputStream(eventImgpath);
OutputStream out = Storage.getInstance().createOutputStream("profile.png");
Util.copy(stream, out);
Util.cleanup(stream);
Util.cleanup(out);
userImg.setIcon(profileImg);
userImg.setPreferredH(20 + Display.getInstance().getDisplayWidth() / 3);
userImg.getParent().revalidate();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, Display.GALLERY_IMAGE);
});
I have one more question. How can I re-adjust the image as an icon in a label? for eg we can readjust or drag to repostion cover img in facebook before saving it. Since it is a profile image while saving it sometime the face is not shown so I need to reposition the image and save it as a label icon. Is there any example for it?
Thankyou

How to add a local file into a maven project?

Hi I'm trying to use the tokenizer in OpenNLP to develop a maven project. It needs to load a local file, but I don't know how to add it into the project so that even when I launched the project in other machine it still works. Like below, the project need to load this local file, how should I configure the file to be added into the project?
InputStream modelIn;
try {
modelIn = new FileInputStream("E:\\en-token.bin");
// Make sure the "en-token.bin" file is already in your local disk
TokenizerModel model = null;
try {
model = new TokenizerModel(modelIn);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
}
Tokenizer tokenizer = new TokenizerME(model);
String tokens[] = tokenizer.tokenize(string);
List<String> tokenResult = Arrays.asList(tokens);
return tokenResult;
} catch (FileNotFoundException ex) {
return null;
}
Such kind of files should be put into src/main/resources folder which will be packaged into jar file.

Sending SMS from BlackBerry Simulator

I'm developing a BlackBerry Application where I should send Text SMS from BlackBerry Device.
As I'm new to Blackberry, started few days back I'm unable to proceed.
Can anyone Help with providing code snippets for send SMS from BlackBerry Device or Simulator?
Thanks in Advance.
Suresh.
public static void sendSMS(final String no, final String msg) {
// try {
new Thread() {
public void run() {
boolean smsSuccess = false;
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
// / send successfully
smsSuccess = true;
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
smsSuccess = false;
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector
.open("sms://" + no);
TextMessage tmsg = (TextMessage) conn
.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
conn.send(tmsg);
smsSuccess = true;
} catch (Exception e) {
smsSuccess = false;
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
if(smsSuccess)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("success");
}
});
}else
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("failure");
}
});
}
}
}.start();
}
Check out the the above code function .... to send SMS from Blackberry
You haven't specified what language you are developing in, but if you are developing in java and, if you are using Eclipse for your development with the Blackberry Java plugins, you will find a wealth of sample applications in the plugins folder hierarchy. The actual location will depend on where you have installed Eclipse, but e.g. on my machine they are at: C:\Program Files\Eclipse\eclipse 3.6.2 BlackBerry\plugins\net.rim.ejde.componentpack7.0.0_7.0.0.33\components\samples\com\rim\samples\device for the OS7 samples. Similar samples will exist for the different OS plugins you have installed.
There is a long standing sample in most OS sample sets called smsdemo which should give you all the code you need. Even if you are not developing in java, this sample should give you an indication of the path you need to take to fulfil your requirement.

Resources