Categories
discuss

Is there a way to use “<%= someObject.ClientID %>” in an external javascript file?

Is there a way to use “<%= someObject.ClientID %>” in an external javascript file?

If I use the code

<%= someObject.ClientID %>

in a script tag inside my as(c/p)x page, it works fine. On the rendered page, the ClientID is resolved. Howvever, if I put in an external JS file and just add:

It doesn’t. Is there a way to do this or am I stuck with leaving that code in the as(c/p)x file?

Side question — what is the act of doing <%=… %> in your markup file called?

Answer

This is totally possible.

In your .aspx page, create a script reference to an aspx page that contains your javascript code:

<script src="../MyJavaScriptFile.js.aspx" type='text/javascript'></script>

Then, in MyJavaScriptFile.js.aspx you can write the following:

<%@ Page Language="C#" AutoEventWireup="false"  ContentType="text/javascript" %>

<% 
    var foo = new Whatever();
    foo.ClientId = 123;
%>

// Start Javascript
var clientId = <% HttpContext.Current.Response.Write(foo.ClientId); %>;

.

Also helpful – this technique supports querystring parameters:

 <script src="../MyJavaScriptFile.js.aspx?username=<% somevalue %>" 
       type='text/javascript'></script>

Then, in MyJavaScriptFile.js.aspx, I can reference the value with

var username = '<% Request.QueryString["username"] %>';

It’s not the “best practice” way to do things, but it gets the job done in a way that my caveman brain can understand without resorting to fancy workarounds.

Categories
discuss

Type safe heterogeneous container pattern to store lists of items

I’m trying to implement a type-safe heterogeneous container to store lists of heterogeneous objects.

I have seen several exameples of type-safe heterogeneous container pattern (link) but all of them store a single object of a type.

I have tryed to implement it as follows:

public class EntityOrganizer {  

    private Map<Class<?>, List<Object>> entityMap = new HashMap<Class<?>, List<Object>>();

    public <T> List<T> getEntities(Class<T> clazz) {
        return entityMap.containsKey(clazz) ? entityMap.get(clazz) : Collections.EMPTY_LIST;
    }

    private <T> void addEntity(Class<T> clazz, T entity) {
        List<T> entityList = (List<T>) entityMap.get(clazz);
        if(entityList == null) {
            entityList = new ArrayList<T>();
            entityMap.put(clazz, (List<Object>) entityList);
        }
        entityList.add(entity);
    }   
}

But the problem is this code is full of unchecked casts. Can someone help with a better way of implementing this?

Many thanks

Answer

The question is, what is “unchecked cast”?

Sometimes casts are provably safe, unfortunately the proof is beyond javac’s capability, which does only limited static analysis enumerated in the spec. But the programmer is smarter than javac.

In this case, I argue that these are “checked casts”, and it’s very appropriate to suppress the warning.

See 2 other related examples:

Heterogeneous container to store genericly typed objects in Java

Typesafe forName class loading

Categories
discuss

Eclipse “Build Automatically” not cascading

I have a project in Eclipse (Indigo but similar in Helios) which has files in src/main/resources which get processed to generate *.java source files in target/generated-sources/xyz. The project settings have “Build Automatically” enabled so whenever these resource files are edited and saved the corresponding *.java files are generated. I’ve added target/generated-sources/xyz to the projects Build Paths. This all works perfectly.

The problem is that the changes to the generated *.java files are inconsistently rebuilt. If I have one of those files open in the editor, then it notices that it changed and asks if I want to reload it. Reloading the *.java files is enough for it to recognize that it has changed and trigger a rebuild. If I don’t have it open then it doesn’t automatically pick up the changes.

Any ideas on what I can do to let Eclipse (Indigo preferably) know that these generated files are being updated? Or better yet tell it to monitor those folders directly?

Thanks.

Answer

Try configuring Eclipse to automatically refresh. I’m not sure about Indigo, but in Helios, it’s in Preferences → General → Workspace → Refresh Automatically.


Here it is in Indigo:

screenshot

Categories
discuss

Android fill percent of layout

How do I make elements in a layout occupy 50, 25, 10, etc. percent of the horizontal/vertical space available?

Answer

You could achieve this with something like that : ( for vertical here )

<LinearLayout 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:weightSum="100">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="60">
    </LinearLayout>
</LinearLayout>`

See android:weightsum documentation

Categories
discuss

Simple export and import of a SQLite database on Android

I am trying to implement a simple SQLite export/import for backup purposes. Export is just a matter of storing a copy of the raw current.db file. What I want to do for import is to just delete the old current.db file and rename the imported.db file to current.db. Is this possible? When I try this solution, I get the following error:

06-30 13:33:38.831: ERROR/SQLiteOpenHelper(23570):
    android.database.sqlite.SQLiteDatabaseCorruptException: error code 11: database disk image is malformed

If I look at the raw database file in a SQLite browser it looks fine.

Answer

I use this code in the SQLiteOpenHelper in one of my applications to import a database file.

EDIT: I pasted my FileUtils.copyFile() method into the question.

SQLiteOpenHelper

public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db";

/**
 * Copies the database file at the specified location over the current
 * internal application database.
 * */
public boolean importDatabase(String dbPath) throws IOException {

    // Close the SQLiteOpenHelper so it will commit the created empty
    // database to internal storage.
    close();
    File newDb = new File(dbPath);
    File oldDb = new File(DB_FILEPATH);
    if (newDb.exists()) {
        FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
        // Access the copied database so SQLiteHelper will cache it and mark
        // it as created.
        getWritableDatabase().close();
        return true;
    }
    return false;
}

FileUtils

public class FileUtils {
    /**
     * Creates the specified <code>toFile</code> as a byte for byte copy of the
     * <code>fromFile</code>. If <code>toFile</code> already exists, then it
     * will be replaced with a copy of <code>fromFile</code>. The name and path
     * of <code>toFile</code> will be that of <code>toFile</code>.<br/>
     * <br/>
     * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
     * this function.</i>
     * 
     * @param fromFile
     *            - FileInputStream for the file to copy from.
     * @param toFile
     *            - FileInputStream for the file to copy to.
     */
    public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {
            fromChannel = fromFile.getChannel();
            toChannel = toFile.getChannel();
            fromChannel.transferTo(0, fromChannel.size(), toChannel);
        } finally {
            try {
                if (fromChannel != null) {
                    fromChannel.close();
                }
            } finally {
                if (toChannel != null) {
                    toChannel.close();
                }
            }
        }
    }
}

Don’t forget to delete the old database file if necessary.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..