Search in sources :

Example 66 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class SQLMap method createTable.

/**
 * Creates a table matching the given property component if one doesn't exist yet
 * @param cmp the business object
 * @return true if the table was created false if it already existed
 */
public boolean createTable(PropertyBusinessObject cmp) throws IOException {
    String tableName = getTableName(cmp);
    Cursor cr = null;
    boolean has = false;
    try {
        cr = executeQuery("SELECT * FROM sqlite_master WHERE type='table' AND name='" + tableName + "'");
        has = cr.next();
    } finally {
        if (cr != null) {
            cr.close();
        }
    }
    if (has) {
        return false;
    }
    StringBuilder createStatement = new StringBuilder("CREATE TABLE ");
    createStatement.append(tableName);
    createStatement.append(" (");
    String pkName = (String) cmp.getPropertyIndex().getMetaDataOfClass("cn1$pk");
    boolean autoIncrement = cmp.getPropertyIndex().getMetaDataOfClass("cn1$autoinc") != null;
    boolean first = true;
    for (PropertyBase p : cmp.getPropertyIndex()) {
        SqlType tp = getSqlType(p);
        if (tp == SqlType.SQL_EXCLUDE) {
            continue;
        }
        if (!first) {
            createStatement.append(",");
        }
        first = false;
        String columnName = getColumnName(p);
        createStatement.append(columnName);
        createStatement.append(" ");
        createStatement.append(tp.dbType);
        if (columnName.equalsIgnoreCase(pkName)) {
            createStatement.append(" PRIMARY KEY");
            if (autoIncrement) {
                createStatement.append(" AUTOINCREMENT");
            }
        }
    }
    createStatement.append(")");
    execute(createStatement.toString());
    return true;
}
Also used : Cursor(com.codename1.db.Cursor)

Example 67 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class AndroidImplementation method loadNativeFont.

/**
 * Loads a native font based on a lookup for a font name and attributes.
 * Font lookup values can be separated by commas and thus allow fallback if
 * the primary font isn't supported by the platform.
 *
 * @param lookup string describing the font
 * @return the native font object
 */
public Object loadNativeFont(String lookup) {
    try {
        lookup = lookup.split(";")[0];
        int typeface = Typeface.NORMAL;
        String familyName = lookup.substring(0, lookup.indexOf("-"));
        String style = lookup.substring(lookup.indexOf("-") + 1, lookup.lastIndexOf("-"));
        String size = lookup.substring(lookup.lastIndexOf("-") + 1, lookup.length());
        if (style.equals("bolditalic")) {
            typeface = Typeface.BOLD_ITALIC;
        } else if (style.equals("italic")) {
            typeface = Typeface.ITALIC;
        } else if (style.equals("bold")) {
            typeface = Typeface.BOLD;
        }
        Paint font = new CodenameOneTextPaint(Typeface.create(familyName, typeface));
        font.setAntiAlias(true);
        font.setTextSize(Integer.parseInt(size));
        return new NativeFont(0, 0, 0, font);
    } catch (Exception err) {
        return null;
    }
}
Also used : Paint(android.graphics.Paint) Paint(android.graphics.Paint) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 68 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class AndroidImplementation method createBackgroundMedia.

@Override
public Media createBackgroundMedia(final String uri) throws IOException {
    int mediaId = nextMediaId++;
    backgroundMediaCount++;
    Intent serviceIntent = new Intent(getContext(), AudioService.class);
    serviceIntent.putExtra("mediaLink", uri);
    serviceIntent.putExtra("mediaId", mediaId);
    if (background == null) {
        ServiceConnection mConnection = new ServiceConnection() {

            public void onServiceDisconnected(ComponentName name) {
                background = null;
                backgroundMediaServiceConnection = null;
            }

            public void onServiceConnected(ComponentName name, IBinder service) {
                AudioService.LocalBinder mLocalBinder = (AudioService.LocalBinder) service;
                AudioService svc = (AudioService) mLocalBinder.getService();
                background = svc;
            }
        };
        backgroundMediaServiceConnection = mConnection;
        boolean boundSuccess = getContext().bindService(serviceIntent, mConnection, getContext().BIND_AUTO_CREATE);
        if (!boundSuccess) {
            throw new RuntimeException("Failed to bind background media service for uri " + uri);
        }
        ContextCompat.startForegroundService(getContext(), serviceIntent);
        while (background == null) {
            Display.getInstance().invokeAndBlock(new Runnable() {

                @Override
                public void run() {
                    Util.sleep(200);
                }
            });
        }
    } else {
        ContextCompat.startForegroundService(getContext(), serviceIntent);
    }
    while (background.getMedia(mediaId) == null) {
        Display.getInstance().invokeAndBlock(new Runnable() {

            public void run() {
                Util.sleep(200);
            }
        });
    }
    Media ret = new MediaProxy(background.getMedia(mediaId)) {

        @Override
        public void cleanup() {
            super.cleanup();
            if (--backgroundMediaCount <= 0) {
                if (backgroundMediaServiceConnection != null) {
                    try {
                        getContext().unbindService(backgroundMediaServiceConnection);
                    } catch (IllegalArgumentException ex) {
                    // This is thrown sometimes if the service has already been unbound
                    }
                }
            }
        }
    };
    return ret;
}
Also used : AsyncMedia(com.codename1.media.AsyncMedia) AbstractMedia(com.codename1.media.AbstractMedia) Media(com.codename1.media.Media) Paint(android.graphics.Paint) IBinder(android.os.IBinder) MediaProxy(com.codename1.media.MediaProxy) BackgroundAudioService(com.codename1.media.BackgroundAudioService) AudioService(com.codename1.media.AudioService)

Example 69 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class AndroidImplementation method installNotificationActionCategories.

/**
 * Action categories are defined on the Main class by implementing the PushActionsProvider, however
 * the main class may not be available to the push receiver, so we need to save these categories
 * to the file system when the app is installed, then the push receiver can load these actions
 * when it sends a push while the app isn't running.
 * @param provider A reference to the App's main class
 * @throws IOException
 */
public static void installNotificationActionCategories(PushActionsProvider provider) throws IOException {
    // Assume that CN1 is running... this will run when the app starts
    // up
    Context context = getContext();
    boolean requiresUpdate = false;
    File categoriesFile = new File(activity.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES);
    if (!categoriesFile.exists()) {
        requiresUpdate = true;
    }
    if (!requiresUpdate) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);
            if (packageInfo.lastUpdateTime > categoriesFile.lastModified()) {
                requiresUpdate = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    if (!requiresUpdate) {
        return;
    }
    OutputStream os = getContext().openFileOutput(FILE_NAME_NOTIFICATION_CATEGORIES, 0);
    PushActionCategory[] categories = provider.getPushActionCategories();
    javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException("Faield to create document builder for creating notification categories XML document", ex);
    }
    // root elements
    org.w3c.dom.Document doc = docBuilder.newDocument();
    org.w3c.dom.Element root = (org.w3c.dom.Element) doc.createElement("categories");
    doc.appendChild(root);
    for (PushActionCategory category : categories) {
        org.w3c.dom.Element categoryEl = (org.w3c.dom.Element) doc.createElement("category");
        org.w3c.dom.Attr idAttr = doc.createAttribute("id");
        idAttr.setValue(category.getId());
        categoryEl.setAttributeNode(idAttr);
        for (PushAction action : category.getActions()) {
            org.w3c.dom.Element actionEl = (org.w3c.dom.Element) doc.createElement("action");
            org.w3c.dom.Attr actionIdAttr = doc.createAttribute("id");
            actionIdAttr.setValue(action.getId());
            actionEl.setAttributeNode(actionIdAttr);
            org.w3c.dom.Attr actionTitleAttr = doc.createAttribute("title");
            if (action.getTitle() != null) {
                actionTitleAttr.setValue(action.getTitle());
            } else {
                actionTitleAttr.setValue(action.getId());
            }
            actionEl.setAttributeNode(actionTitleAttr);
            if (action.getIcon() != null) {
                org.w3c.dom.Attr actionIconAttr = doc.createAttribute("icon");
                String iconVal = action.getIcon();
                try {
                    // We'll store the resource IDs for the icon
                    // rather than the icon name because that is what
                    // the push notifications require.
                    iconVal = "" + context.getResources().getIdentifier(iconVal, "drawable", context.getPackageName());
                    actionIconAttr.setValue(iconVal);
                    actionEl.setAttributeNode(actionIconAttr);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (action.getTextInputPlaceholder() != null) {
                org.w3c.dom.Attr textInputPlaceholderAttr = doc.createAttribute("textInputPlaceholder");
                textInputPlaceholderAttr.setValue(action.getTextInputPlaceholder());
                actionEl.setAttributeNode(textInputPlaceholderAttr);
            }
            if (action.getTextInputButtonText() != null) {
                org.w3c.dom.Attr textInputButtonTextAttr = doc.createAttribute("textInputButtonText");
                textInputButtonTextAttr.setValue(action.getTextInputButtonText());
                actionEl.setAttributeNode(textInputButtonTextAttr);
            }
            categoryEl.appendChild(actionEl);
        }
        root.appendChild(categoryEl);
    }
    try {
        javax.xml.transform.TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance();
        javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
        javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
        javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os);
        transformer.transform(source, result);
    } catch (Exception ex) {
        throw new IOException("Failed to save notification categories as XML.", ex);
    }
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) Element(android.renderscript.Element) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) PushActionCategory(com.codename1.push.PushActionCategory) IOException(java.io.IOException) PushAction(com.codename1.push.PushAction) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 70 with Name

use of com.codename1.rad.models.Property.Name in project CodenameOne by codenameone.

the class AndroidImplementation method getAppArg.

@Override
public String getAppArg() {
    if (super.getAppArg() != null) {
        // behaviour the existed when AppArg was just another Display property.
        return super.getAppArg();
    }
    if (getActivity() == null) {
        return null;
    }
    android.content.Intent intent = getActivity().getIntent();
    if (intent != null) {
        String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
        intent.removeExtra(Intent.EXTRA_TEXT);
        Uri u = intent.getData();
        String scheme = intent.getScheme();
        if (u == null && intent.getExtras() != null) {
            if (intent.getExtras().keySet().contains("android.intent.extra.STREAM")) {
                try {
                    u = (Uri) intent.getParcelableExtra("android.intent.extra.STREAM");
                    scheme = u.getScheme();
                    System.out.println("u=" + u);
                } catch (Exception ex) {
                    Log.d("Codename One", "Failed to load parcelable extra from intent: " + ex.getMessage());
                }
            }
        }
        if (u != null) {
            // String scheme = intent.getScheme();
            intent.setData(null);
            if ("content".equals(scheme)) {
                try {
                    InputStream attachment = getActivity().getContentResolver().openInputStream(u);
                    if (attachment != null) {
                        String name = getContentName(getActivity().getContentResolver(), u);
                        if (name != null) {
                            String filePath = getAppHomePath() + getFileSystemSeparator() + name;
                            if (filePath.startsWith("file:")) {
                                filePath = filePath.substring(5);
                            }
                            File f = new File(filePath);
                            OutputStream tmp = createFileOuputStream(f);
                            byte[] buffer = new byte[1024];
                            int read = -1;
                            while ((read = attachment.read(buffer)) > -1) {
                                tmp.write(buffer, 0, read);
                            }
                            tmp.close();
                            attachment.close();
                            setAppArg(addFile(filePath));
                            return addFile(filePath);
                        }
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                /*
                    // Why do we need this special case?  u.toString()
                    // will include the full URL including query string.
                    // This special case causes urls like myscheme://part1/part2
                    // to only return "/part2" which is obviously problematic and
                    // is inconsistent with iOS.  Is this special case necessary
                    // in some versions of Android?
                    String encodedPath = u.getEncodedPath();
                    if (encodedPath != null && encodedPath.length() > 0) {
                        String query = u.getQuery();
                        if(query != null && query.length() > 0){
                            encodedPath += "?" + query;
                        }
                        setAppArg(encodedPath);
                        return encodedPath;
                    }
                    */
                if (sharedText != null) {
                    setAppArg(sharedText);
                    return sharedText;
                } else {
                    setAppArg(u.toString());
                    return u.toString();
                }
            }
        } else if (sharedText != null) {
            setAppArg(sharedText);
            return sharedText;
        }
    }
    return null;
}
Also used : BufferedInputStream(com.codename1.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Uri(android.net.Uri) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) android.content(android.content) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Paint(android.graphics.Paint)

Aggregations

IOException (java.io.IOException)36 Component (com.codename1.ui.Component)17 Hashtable (java.util.Hashtable)17 ArrayList (java.util.ArrayList)16 AnimationObject (com.codename1.ui.animations.AnimationObject)15 File (java.io.File)14 Form (com.codename1.ui.Form)13 ByteArrayInputStream (java.io.ByteArrayInputStream)13 FileInputStream (java.io.FileInputStream)13 InputStream (java.io.InputStream)12 Label (com.codename1.ui.Label)11 Button (com.codename1.ui.Button)10 Container (com.codename1.ui.Container)10 EncodedImage (com.codename1.ui.EncodedImage)10 TextArea (com.codename1.ui.TextArea)10 BorderLayout (com.codename1.ui.layouts.BorderLayout)10 Point (java.awt.Point)10 FileOutputStream (java.io.FileOutputStream)10 Paint (android.graphics.Paint)8 BufferedInputStream (com.codename1.io.BufferedInputStream)7