Categories
discuss

Splitting on a Unique Character

I want to build a comma separated list so that I can split on the comma later to get an array of the values. However, the values may have comma’s in them. In fact, they may have any normal keyboard character in them (they are supplied from a user). What is a good strategy for determining a character you are sure will not collide with the values?

In case this matters in a language dependent way, I am building the “some character” separated list in C# and sending it to a browser to be split in javascript.

Answer

You could split it by a null character, and terminate your list with a double null character.

Categories
discuss

How to load tiles from a large bitmap in Android?

If I have a large bitmap file that would normally generate an “Out of memory” exception, how can I load it as tiles? e.g. I have a 10,000×10,000 image, I want to split it up into a 10×10 grid of 1,000×1,000 pixel tiles.

I’ve seen the function Bitmap.createBitmap(sourceBitmap, x, y, width, height) but it requires my large image as the source input.

How can I get a tile from my input image, without fully loading the input image?

Answer

Answer from Romain Guy in Is it possible to chop a bitmap to small pieces without loading the entire thing into memory?:

Android 2.3.3 has a new API called android.graphics.BitmapRegionDecoder that lets you do exactly what you want.

You would for instance do the following:

BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(myStream, false);  
Bitmap region = decoder.decodeRegion(new Rect(10, 10, 50, 50), null);

Easy 🙂

Categories
discuss

Memory-efficient Java library to read Excel files?

Is there a memory-efficient Java library to read large Microsoft Excel files (both .xls and .xlsx)? I have very limited experience with Apache POI, and it seemed to be a huge memory hog from what I recall (though perhaps this was just for writing and not for reading). Is there something better? Or am I misremembering and/or misusing POI?

It would be important for it to have a “friendly” open-source license as well.

Answer

Apache’s POI library has an event-based API that has a smaller memory-footprint. Unfortunately, it only works with HSSF (Horrible Spreadsheet Format) and not XSSF (XML Spreadsheet Format – for OOXML files).

Categories
discuss

java: reflection to obtain an Enum

This is similar but not quite the same as Java: instantiating an enum using reflection

I have a Map<Enum<?>, FooHandler> that I want to use to map Enums (I don’t care which type or even if they are the same type, just as long as they are enum constants) to my FooHandler class.

I would like to populate this map using a text file that I read. I can get it to work, but I have two warnings I would like to get around:

static private <E extends Enum<E>> E getEnum(String enumFullName) {
  // see https://stackoverflow.com/questions/4545937/
  String[] x = enumFullName.split("\.(?=[^\.]+$)");
  if (x.length == 2)
  {
    String enumClassName = x[0];
    String enumName = x[1];
    try {
      Class<E> cl = (Class<E>)Class.forName(enumClassName);
      // #1                          

      return Enum.valueOf(cl, enumName);
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
  return null;
}

public void someMethod(String enumName, String fooHandlerName)
{
   FooHandler fooHandler = getFooHandler(fooHandlerName);
   Enum e = getEnum(enumName);
   // #2

   map.put(e, fooHandler);
}

Warning #1: unchecked cast Warning #2: Enum is a raw type.

I get #1 and could just put a warning I suppose, but I can’t seem to beat warning #2; I’ve tried Enum<?> and that just gives me an error about generic type capture bound mismatch.


Alternative implementations that are worse: Before my <E extends Enum<E>> generic return value, I tried returning Enum and it didn’t work; I got these warnings/errors:

static private Enum<?> getEnum(String enumFullName) {
   ...

Class<?> cl = (Class<?>)Class.forName(enumClassName);
    // 1
return Enum.valueOf(cl, enumName);
    // 2
}
  1. warnings:

      - Type safety: Unchecked cast from Class<capture#3-of ?> to Class<Enum>
      - Enum is a raw type. References to generic type Enum<E> should be parameterized
      - Enum is a raw type. References to generic type Enum<E> should be parameterized
      - Unnecessary cast from Class<capture#3-of ?> to Class<?>
    
  2. errors:

    - Type mismatch: cannot convert from capture#5-of ? to Enum<?>
    - Type safety: Unchecked invocation valueOf(Class<Enum>, String) of the generic method 
     valueOf(Class<T>, String) of type Enum
    - Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not 
     applicable for the arguments (Class<capture#5-of ?>, String). The inferred type capture#5-of ? is not 
     a valid substitute for the bounded parameter <T extends Enum<T>>
    

and this:

static private Enum<?> getEnum(String enumFullName) {
   ...
  Class<Enum<?>> cl = (Class<Enum<?>>)Class.forName(enumClassName);
  // 1
  return Enum.valueOf(cl, enumName);
  // 2
  1. warning: Type safety: Unchecked cast from Class<capture#3-of ?> to Class<Enum<?>>
  2. error: Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not applicable for the arguments (Class<Enum<?>>, String). The inferred type Enum<?> is not a valid substitute for the bounded parameter <T extends Enum<T>>

Answer

For #1 there’s no solution except SuppressWarnings("unchecked").

For #2 there’s a problem with the declaration:

static private <E extends Enum<E>> E getEnum(String enumFullName)

You can return E, but there’s no way for the compiler to determine E. There’s no argument of type E or Class<E> or whatever, which would allow it. You can write it, but there’ll be an unchecked cast somewhere and when you call it, you may get a ClassCastException. So don’t do it.

Just change it into

static private Enum<?> getEnum(String enumFullName)

as this will work and is more fair. You’ll get a warning on each call site and that’s correct as there is something to warn of.

Categories
discuss

Can I change my Windows desktop wallpaper programmatically in Java/Groovy?

Is there a way I can use Java (or Groovy) to change my desktop wallpaper in Windows XP? I have a program that creates a new image every day (or whenever) and I would like a way to automatically update my desktop.

I’ve seem some questions on this site about C++ or .NET, but I did not see anything specific to Java.

Answer

Sorry I’m a bit behind @ataylor’s answer because I was preparing a snippet to do it. Yes, JNA is a correct approach. Here you go:

import java.util.HashMap;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.UINT_PTR;
import com.sun.jna.win32.*;

public class WallpaperChanger {
   public static void main(String[] args) {
      //supply your own path instead of using this one
      String path = "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg";

      SPI.INSTANCE.SystemParametersInfo(
          new UINT_PTR(SPI.SPI_SETDESKWALLPAPER), 
          new UINT_PTR(0), 
          path, 
          new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
   }

   public interface SPI extends StdCallLibrary {

      //from MSDN article
      long SPI_SETDESKWALLPAPER = 20;
      long SPIF_UPDATEINIFILE = 0x01;
      long SPIF_SENDWININICHANGE = 0x02;

      SPI INSTANCE = (SPI) Native.loadLibrary("user32", SPI.class, new HashMap<Object, Object>() {
         {
            put(OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
            put(OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE);
         }
      });

      boolean SystemParametersInfo(
          UINT_PTR uiAction,
          UINT_PTR uiParam,
          String pvParam,
          UINT_PTR fWinIni
        );
  }
}

You need to have the JNA libraries on the classpath for this to work. This was tested in Windows 7, there might be some nuances in XP but I think it should work. That API is presumably stable.

References

Edit (2010/01/20):

I had previously omitted the options SPIF_UPDATEINIFILE and SPIF_SENDWININICHANGE. These are now being used as they were suggested in the Coding4Fun MSDN article.

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..