I've an issue while trying to save an image to the Storage in iOS. Image is downloaded but not saved.
The code is:
Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
TreeModel tm = new TreeModel() {
#Override
public Vector getChildren(Object parent) {
String[] files;
if (parent == null) {
files = FileSystemStorage.getInstance().getRoots();
return new Vector<Object>(Arrays.asList(files));
} else {
try {
files = FileSystemStorage.getInstance().listFiles((String) parent);
} catch (IOException err) {
Log.e(err);
files = new String[0];
}
}
String p = (String) parent;
Vector result = new Vector();
for (String s : files) {
result.add(p + s);
}
return result;
}
#Override
public boolean isLeaf(Object node) {
return !FileSystemStorage.getInstance().isDirectory((String) node);
}
};
Command tree = new Command("Show tree") {
#Override
public void actionPerformed(ActionEvent evt) {
Form treeForm = new Form("Tree", new BorderLayout());
Tree t = new Tree(tm) {
#Override
protected String childToDisplayLabel(Object child) {
String n = (String) child;
int pos = n.lastIndexOf("/");
if (pos < 0) {
return n;
}
return n.substring(pos);
}
};
treeForm.add(BorderLayout.CENTER, t);
Command back = new Command("Back") {
#Override
public void actionPerformed(ActionEvent evt) {
hi.showBack();
}
};
Button backButton = new Button(back);
treeForm.add(BorderLayout.SOUTH, backButton);
treeForm.show();
}
};
hi.getToolbar().addCommandToOverflowMenu(tree);
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
String photoURL = "https://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/400px-AGameOfThrones.jpg";
StringBuilder fsPath = new StringBuilder(FileSystemStorage.getInstance().getAppHomePath());
fsPath.append("400px-AGameOfThrones.jpg");
URLImage background = URLImage.createToStorage(placeholder, fsPath.toString(), photoURL);
background.fetch();
Style stitle = hi.getToolbar().getTitleComponent().getUnselectedStyle();
stitle.setBgImage(background);
stitle.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
stitle.setPaddingUnit(Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
stitle.setPaddingTop(15);
SpanButton credit = new SpanButton("Link");
credit.addActionListener((e) -> Display.getInstance().execute("https://awoiaf.westeros.org/index.php/A_Game_of_Thrones"));
hi.add(new SpanLabel("A")).
add(new Label("B", "Heading")).
add(credit);
ComponentAnimation title = hi.getToolbar().getTitleComponent().createStyleAnimation("Title", 200);
hi.getAnimationManager().onTitleScrollAnimation(title);
hi.show();
Which was taken from https://www.codenameone.com/javadoc/com/codename1/ui/URLImage.html
The tree is only to see if the image was saved in the Storage.
You are mixing Storage & FileSystemStorage which are very different things see this.
You can use storage which is a flat set of "files" and that's what URLImage.createToStorage does. But then you need to use the Storage API to work with that and it might not be visible in the FileSystemStorage API.
Alternatively you might be looking for URLImage.createToFileSystem().
Related
I was trying not to resort to posting on the forums but everything I've done will not make this work. What I'm trying to do is if an ArrayList doesn't contain a players name then it will add them to the ArrayList, but it's skipping over that and just removing them from the list they were never added to. Ultimate goal out of this plugin is if they are in god mode they can't be hurt.
Command Class:
public static List<String> playerList = new ArrayList<String>();
#Override
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
Player player = (Player) sender;
String p = player.getName();
List<String> isGod = new ArrayList<String>();
if (cmd.getName().equalsIgnoreCase("god") && sender instanceof Player) {
if (!isGod.contains(p)) {
isGod.add(p);
playerList.add(p);
player.sendMessage(ChatColor.GREEN + "Godmode is enabled");
return true;
} else {
isGod.remove(p);
playerList.remove(p);
player.sendMessage(ChatColor.GREEN + "Godmode is disabled");
return true;
}
}
return true;
}
}
Listener Class:
#EventHandler
public void isDamaged(EntityDamageEvent e) {
String player = e.getEntity().getName();
if (playerList.contains(player)) {
e.setCancelled(true);
}
}
}
As dly said yes, you create new empty list every time command is executed. You must init your list as global static in your class in order to make sure that this is only one list for all operations.
public static List<String> isGod = new ArrayList<>(); // <== HERE
public static List<String> playerList = new ArrayList<String>();
#Override
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
Player player = (Player) sender;
String p = player.getName();
if (cmd.getName().equalsIgnoreCase("god") && sender instanceof Player) {
if (!isGod.contains(p)) {
isGod.add(p);
playerList.add(p);
player.sendMessage(ChatColor.GREEN + "Godmode is enabled");
return true;
} else {
isGod.remove(p);
playerList.remove(p);
player.sendMessage(ChatColor.GREEN + "Godmode is disabled");
return true;
}
}
return true;
}
I would like to display DateTime picker in my App, so I'm write below code to display DateTime Picker, every thing is working fine but in Android device date is not displayed properly.
Form dialogtimeForm = new Form("Set time");
dialogtimeForm.setUIID("workersListForm");
if(!Constants.PLATFORMNAME.equals(Display.getInstance().getPlatformName())){
spinner = new DateTimeSpinner(){
#Override
protected Dimension calcPreferredSize() {
return new Dimension(460, 180);
}
};
} else{
spinner = new DateTimeSpinner();
}
spinner.setShowMeridiem(true);
spinner.setMinuteStep(1);
int hours = 0;
int minutes = 0;
boolean showMeridiem = false;
Date date = null;
timeValue = data;
if(timeValue != null && !"".equals(timeValue)){
hours = Util.getHours(timeValue);
minutes = Util.getMinutes(timeValue);
showMeridiem = Util.getAmPm(timeValue);
date = Util.getDate(DBActuallCallDate);
}
if(hours > 12){
hours = hours -12;
showMeridiem = true;
}
spinner.setCurrentHour(hours);
spinner.setCurrentMinute(minutes);
spinner.setCurrentMeridiem(showMeridiem);
spinner.setCurrentDate(date);
dialogtimeForm.add(spinner);
Dialog dialog = new Dialog();
dialog.setDisposeWhenPointerOutOfBounds(true);
commands[0] = new Command(Constants.SETCOMMAND){
#Override
public void actionPerformed(ActionEvent evt) {
int hour = spinner.getCurrentHour();
int minute = spinner.getCurrentMinute();
boolean meridiem = spinner.isCurrentMeridiem();
String time = Util.timeConversion(hour, minute, meridiem);
String workerTime = Util.getFormatedTimeValue(time, spinner.getCurrentDate());
callInField.setText(time);
roasterDao = new RoasterDao();
if(flag.equals(Constants.ACTUALCALLOUTFLAG))
roasterDao.updateActualCallOutTime(workerTime, serialId);
else
roasterDao.updateActualCallInTime(workerTime, serialId);
dialog.dispose();
if(ApplicationScopeBean.dialogShow){
if(flag.equals(Constants.ACTUALCALLOUTFLAG))
Dialog.show("Alert", workerName+Constants.CHECKOUTSUCCESSFULLY+time,"ok",null);
else
Dialog.show("Alert", workerName+Constants.CHECKINSUCCESSFULLY+time,"ok",null);
} else{
if(flag.equals(Constants.ACTUALCALLOUTFLAG))
Toast.makeText(RoasterApp.getContext(), workerName+Constants.CHECKOUTSUCCESSFULLY+time, Toast.LENGTH_LONG).show();
else
Toast.makeText(RoasterApp.getContext(), workerName+Constants.CHECKINSUCCESSFULLY+time, Toast.LENGTH_LONG).show();
}
Container unScheduledWorkerTableContainer = setUnScheduledWorkerTable();
unScheduledWorkerTableContainer.setUIID("unScheduledWorkerTable");
unScheduledWorkerBoxContainer.removeAll();
unScheduledWorkerBoxContainer.add(unScheduledWorkerTableContainer);
unScheduledWorkersForm.revalidate();
}
};
commands[1] = new Command(Constants.CLEARCOMMAND){
#Override
public void actionPerformed(ActionEvent evt) {
Dialog dialog1 = new Dialog();
dialog1.setUIID("listDialog");
String clearCallOutDialog = Constants.CLEARCALLOUTDIALOG;
String clearCallInDialog = Constants.CLEARCALLINDIALOG;
dialog.dispose();
FlowLayout centerLayout = new FlowLayout();
centerLayout.setAlign(Component.CENTER);
centerLayout.setValign(Component.TOP);
Container flowContainer = new Container(centerLayout);
Container boxXAxisLayout = new Container(new BoxLayout(BoxLayout.X_AXIS));
Button okButton = new Button(Constants.OKCOMMAND);
okButton.setUIID("dialogCloseButton");
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
roasterDao = new RoasterDao();
if(flag.equals(Constants.ACTUALCALLOUTFLAG))
roasterDao.updateActualCallOutTime("", serialId);
else
roasterDao.updateActualCallInTime("", serialId);
callInField.setText("");
dialog1.dispose();
dialog.dispose();
Container unScheduledWorkerTableContainer = setUnScheduledWorkerTable();
unScheduledWorkerTableContainer.setUIID("unScheduledWorkerTable");
unScheduledWorkerBoxContainer.removeAll();
unScheduledWorkerBoxContainer.add(unScheduledWorkerTableContainer);
unScheduledWorkersForm.revalidate();
}
});
Button close = new Button(Constants.CANCELCOMMAND);
close.setUIID("dialogCloseButton");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
dialog1.dispose();
dialog.dispose();
Container unScheduledWorkerTableContainer = setUnScheduledWorkerTable();
unScheduledWorkerTableContainer.setUIID("unScheduledWorkerTable");
unScheduledWorkerBoxContainer.removeAll();
unScheduledWorkerBoxContainer.add(unScheduledWorkerTableContainer);
unScheduledWorkersForm.revalidate();
}
});
boxXAxisLayout.add(okButton);
boxXAxisLayout.add(close);
flowContainer.add(boxXAxisLayout);
dialog1.setLayout(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_SCALE));
String dataLabelString = "";
if(flag.equals(Constants.ACTUALCALLOUTFLAG))
dataLabelString = clearCallOutDialog;
else
dataLabelString = clearCallInDialog;
Label dataLabel = new Label(dataLabelString);
dataLabel.setUIID("confirmDialogBody");
dialog1.add(BorderLayout.CENTER, dataLabel);
dialog1.add(BorderLayout.SOUTH, flowContainer);
dialog1.show();
}
};
commands[2] = new Command(Constants.CANCELCOMMAND){
#Override
public void actionPerformed(ActionEvent evt) {
dialog.dispose();
Container unScheduledWorkerTableContainer = setUnScheduledWorkerTable();
unScheduledWorkerTableContainer.setUIID("unScheduledWorkerTable");
unScheduledWorkerBoxContainer.removeAll();
[![enter image description here][1]][1]unScheduledWorkerBoxContainer.add(unScheduledWorkerTableContainer);
unScheduledWorkersForm.revalidate();
}
};
dialog.show("", dialogtimeForm, commands);
please find screenshots.
The Picker API will display native date/time UI on supported platforms. Date, Time, Numbers and Strings are supported on Android but DateTime is only supported on iOS so you are seeing a "fallback" UI.
There is no native equivalent for "DateTime" on Android so you would need
I'm facing an issue with iOS.
I have an App who works perfectly on Android. I build it for Android Debug and when i try to show my form, i got an IndexOutOfBoundsException
Here is my code :
package com.idenovia.calendovia.form;
public class FichePro extends Form {
public static Site site;
public static Boolean isFavorite = false;
public static List<Performance> performances = new ArrayList<Performance>();
public static Long canContactTakeEvent;
public FichePro(final int idPro,final String searchWho, final List<Site> savedSites){
try {
Dialog ip = new InfiniteProgress().showInifiniteBlocking();
ip.getContentPane().getStyle().setBgTransparency(0, true);
ip.getContentPane().getComponentAt(0).getStyle().setBgTransparency(0, true);
Map<String,Object> result;
if(CalendoviaApp.isConnected ==1 && CalendoviaApp.customer.getId() != 0)
result = AccessSite.getSiteFromId(idPro,CalendoviaApp.customer.getId());
else
result = AccessSite.getSiteFromId(idPro,0);
if(result.containsKey("sites")){
site = (Site) result.get("sites");
}else{
site = null;
}
if(result.containsKey("performances")){
performances = (List<Performance>) result.get("performances");
}else{
performances = null;
}
if(result.containsKey("canContactTakeEvent")){
canContactTakeEvent = (Long) result.get("canContactTakeEvent");
}else{
canContactTakeEvent = null;
}
ip.dispose();
} catch (Exception e1) {
e1.printStackTrace();
}
/*
* Form theming and configuring
*/
if(site != null)
setTitle("Dr. "+site.getSiteYou().getShowname());
else{
SearchList searchList = new SearchList(searchWho,"",savedSites);
searchList.show();
}
Container content = new Container(new BoxLayout(BoxLayout.Y_AXIS));
content.setUIID("ctrContent");
setLayout(new BorderLayout());
setTransitionInAnimator(CommonTransitions.createFade(200));
final Font fnt = Font.createTrueTypeFont("CALENDOVIA_APP", "CALENDOVIA_APP.ttf");
Container ctrPhoto = new Container(new BorderLayout());
ctrPhoto.setUIID("ctrPhoto");
// try {
Image image = CalendoviaApp.res.getImage("placeholderProvider").scaled((int)(Display.getInstance().getDisplayWidth()*0.25),(int)(Display.getInstance().getDisplayWidth()*0.25));
for (Site favoris : CalendoviaApp.favorites) {
if(favoris.getId().equals(site.getId())){
isFavorite = true;
}
}
final CheckBox favButton2 = new CheckBox();
final Button favButton = new Button();
if(isFavorite){
favButton.setIcon(FontImage.createFixed("\ue900", fnt, 0x2995d0,(int)(Display.getInstance().getDisplayWidth()*0.2), (int)(Display.getInstance().getDisplayWidth()*0.2)));
}else{
favButton.setIcon(FontImage.createFixed("\ue931", fnt, 0x2995d0,(int)(Display.getInstance().getDisplayWidth()*0.2), (int)(Display.getInstance().getDisplayWidth()*0.2)));
}
favButton.setTextPosition(Component.BOTTOM);
favButton.getStyle().setBgTransparency(0,true);
favButton.getPressedStyle().setBgTransparency(0,true);
favButton.getDisabledStyle().setBgTransparency(0,true);
favButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(isFavorite){
do some stuff like seticon or network access
}else{
do some stuff too
}
}
});
ctrPhoto.add(BorderLayout.WEST, image);
ctrPhoto.add(BorderLayout.EAST, favButton);
Container ctrglobalInfosFichePro = new Container(new BoxLayout(BoxLayout.Y_AXIS));
ctrglobalInfosFichePro.setScrollVisible(false);
ctrglobalInfosFichePro.setScrollableY(true);
ctrglobalInfosFichePro.setUIID("ctrglobalInfosFichePro");
//First Part
Container ctrglobalInfosFirstPart = new Container(new BoxLayout(BoxLayout.Y_AXIS));
ctrglobalInfosFirstPart.setScrollableY(false);
ctrglobalInfosFirstPart.setUIID("ctrglobalInfosFirstPart");
Label lblProviderName = new Label("Dr "+site.getSiteYou().getShowname());
lblProviderName.setUIID("lblNameProvider");
ctrglobalInfosFichePro.add(lblProviderName);
try{
Label lblProviderSpe = new Label(new SectorConvert().getValue(site.getSiteYou().getSectorfirst().intValue()).toString());
lblProviderSpe.setUIID("lblSpeProvider");
ctrglobalInfosFichePro.add(lblProviderSpe);
}catch(Exception e){
} if(site.getSiteOption().getCbcard()||site.getSiteOption().getCheckp()||site.getSiteOption().getSpecies()){
Label lblPaiement = new Label("MOYENS DE PAIEMENT");
lblPaiement.setUIID("lblTitleForSpanLabel");
lblPaiement.setVerticalAlignment(Component.CENTER);
String acceptedPaiement ="";
if(site.getSiteOption().getCbcard()){
acceptedPaiement+=" CB /";
}
Label lblAcceptedPaiement = new Label(acceptedPaiement);
ctrglobalInfosFirstPart.add(lblPaiement);
ctrglobalInfosFirstPart.add(lblAcceptedPaiement);
}
//Second Part
Container ctrglobalInfosSecondPart= new Container(new BorderLayout());
if(site.getSiteYou().getPhonepro().trim().length() != 0){
ctrglobalInfosSecondPart.setUIID("ctrglobalInfosFirstPart");
Button btnAppeler = new Button("Appeler");
btnAppeler.setUIID("btnAppelerFichePro");
btnAppeler.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Display.getInstance().dial(site.getSiteYou().getPhonepro());
}
});
ctrglobalInfosSecondPart.add(BorderLayout.EAST,btnAppeler);
}
ctrglobalInfosFichePro.add(ctrglobalInfosFirstPart);
ctrglobalInfosFichePro.add(ctrglobalInfosSecondPart);
content.add(ctrglobalInfosFichePro);
/*
* Building Form
*/
if(site.getCanaccess()){
Button btnTakeAppointement = new Button("");
btnTakeAppointement.setUIID("");
btnTakeAppointement.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if(site.getNewcontactblocked()){
if(canContactTakeEvent != null && CalendoviaApp.isConnected==1 && CalendoviaApp.customer.getId() != 0){
switch(canContactTakeEvent.intValue()){
case 0:
FicheProCannotTakeEvent ficheProCannotTakeEvent = new FicheProCannotTakeEvent(site, canContactTakeEvent, savedSites, searchWho,true);
ficheProCannotTakeEvent.show();
break;
case 1:
FicheProRdvSelect ficheProRdvSelect = new FicheProRdvSelect(performances,site, savedSites, searchWho, null);
ficheProRdvSelect.show();
break;
[...]
default:
FicheProCannotTakeEvent ficheProCannotTakeEvent4 = new FicheProCannotTakeEvent(site, new Long(4), savedSites, searchWho,true);
ficheProCannotTakeEvent4.show();
break;
}
}else{
FicheProCannotTakeEvent ficheProCannotTakeEvent = new FicheProCannotTakeEvent(site, new Long(0), savedSites, searchWho,false);
ficheProCannotTakeEvent.show();
}
}
else{
FicheProRdvSelect ficheProRdvSelect = new FicheProRdvSelect(performances,site, savedSites, searchWho, null);
ficheProRdvSelect.show();
}
}
});
addComponent(BorderLayout.SOUTH,btnTakeAppointement);
}else{
Button btnParrainage = new Button("");
btnParrainage.setUIID("btnTakeRdvBig");
btnParrainage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Parrainage parrainage = new Parrainage(site, getComponentForm());
parrainage.show();
}
});
addComponent(BorderLayout.SOUTH,btnParrainage);
}
addComponent(BorderLayout.NORTH, ctrPhoto);
addComponent(BorderLayout.CENTER, content);
}
}
I can't find the error where it happens and why...
Thanks for your help
I have a button that display the data obtained from json. below is my code for button action. I need help to display the data obtained to list.
#Override
protected void onMain_ButtonAction(final Component c, ActionEvent event) {
ConnectionRequest r = new ConnectionRequest() {
Hashtable h;
#Override
protected void postResponse() {
}
#Override
protected void readResponse(InputStream input) throws IOException {
InputStreamReader reader = new InputStreamReader(input);
JSONParser p = new JSONParser();
h = p.parse(new InputStreamReader(input));
Hashtable response = p.parse(reader);
Hashtable feed = (Hashtable)response.get("root");
for (Object s : h.values()) {
Vector vec = new Vector(100);
vec = (Vector)s;
int i;
for(i = 0; i<vec.size(); i++){
Hashtable<String, String> ht= (Hashtable<String, String>) vec.get(i);
System.out.println(ht.get("location"));
// findLabel().setText(ht.get("location"));
}
}
}
};
r.setUrl("http://ruslanapp.demo.capitaleyenepal.com/vodka-mobile-interface/getData/locations");
r.setPost(false);
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
r.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueue(r);
}
I want to list the data obtained frm btn above to the list below. how can I do it??
#Override
protected boolean initListModelList1(List cmp) {
cmp.setModel(new com.codename1.ui.list.DefaultListModel(new String[] {"Item 1", "Item 2", "Item 3"}));
return true;
}
You did most of the work well, I suggest avoiding a list and using an infinite container. The PropertyCross demo has pretty much this functionality (including JSON): https://www.udemy.com/learn-mobile-programming-by-example-with-codename-one/
To finish the code above create the model ArrayList above e.g. assuming you are using a MultiList:
// define this in the class variables:
private ArrayList<Map<String, String>> modelData = new ArrayList<Map<String, String>>();
// then in the code (I assumed stuff about your JSON, correct the
// code to extract the data correctly, just set the hashmap values
for (Object s : h.values()) {
Collection<Map<String, String>>) data = (Collection<Map<String, String>>))s;
for(Map<String, String> ht : data) {
String location = ht.get("location");
HashMap<String, String> entry = new HashMap<String, String>();
entry.put("Line1", location);
modelData.add(entry);
}
}
Then in:
#Override
protected boolean initListModelList1(List cmp) {
cmp.setModel(new DefaultListModel(modelData));
return true;
}
Notice that you should use showForm() to show the next form in the postResponse method.
I am trying below mention code for download image from server but it's not working and not giving me any error. Please suggest if any thing wrong which i used.When i am accessing URL from browser it's displaying image to me.
int pos;
public void DisplayContent()
{
f = (Form)createContainer(GlobalVariables.Theme, "ContentPageWise");
body = (Container) findByName("Containerbody", f);
Display_Image = new Image[Page_Details.size()];
for(int i=0;i<Page_Details.size();i++)
{
Hashtable<String,String> hash_page = Page_Details.get(i);
Log.p("imagepath:"+hash_page.get("imgPage"));
pos=i;
GetImagesFromserver(hash_page.get("imgPage"));
Container Cpage = new Container(new BoxLayout(BoxLayout.Y_AXIS));
Label pic = new Label();
pic.setIcon(Display_Image[i]);
Cpage.addComponent(pic);
body.addComponent(Cpage);
}
}
void GetImagesFromserver(String Imagepath)
{
//eg. url like this: http://lmsasr.gizmosupport.com/presentation/tele/internet.jpg
ImageDownloadService imageDownloadService =
new ImageDownloadService(Imagepath, actionListener);
InfiniteProgress ip = new InfiniteProgress();
imageDownloadService.setDisposeOnCompletion(ip.showInifiniteBlocking());
NetworkManager.getInstance().addToQueue(imageDownloadService);
}
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
NetworkEvent n = (NetworkEvent) evt;
Display_Image[pos] = ((Image)n.getMetaData());
}
};