Categories
discuss

Unable to access JSON property with “-” dash

I am unable to retrieve a value from a json object when the string has a dash character:

{
"profile-id":1234, "user_id":6789
}

If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789

I don’t have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?

Answer

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]
Categories
discuss

Consumer closed input channel or an error occurred. events=0x8

01-03 11:28:47.499: ERROR/InputDispatcher(164): channel '4085fe50 com.bce.tip/com.bce.tip.core.MenuActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
01-03 11:28:47.499: ERROR/InputDispatcher(164): channel '4085fe50 com.bce.tip/com.bce.tip.core.MenuActivity (server)' ~ Channel is unrecoverably broken and will be disposed!`

When I click on Imageview action calling but I am calling this onclick to another layer class

Answer

Resolved : 1) Basically this Errors occurs couple of times if your running number of process at a time in single thread . This is like a Deadlock situation.So any Scheduled tasks are there make it Synchronized particular burden objects. 2) Kill the unused processes at the time of Burden happens on MainThread.

Categories
discuss

Dynamically create an object in java from a class name and set class fields by using a List with data

I have a List that contains data with String type -> ["classField1", "classField2", "classField3"]

I have a method (myMethod(List list, String className)) that accept as parameter the List. So, I can pass this List through the parameter to myMethod(List list, String className).

In myMethod, I want to create one object, that will be instance of the className, that is the second parameter. After that I want to set the fields of the class by using the data of the List. Due to the fact that I want to obtain dynamically the fields of the class, the result of the above is that I have to cast each String value of the list, to the type of each field of the class.

I am sure that the order of the Strings inside to the List, are in the right order, and correspond to the fields of the class with the same order.

Does anybody have any idea how to perform the above?

Example:

["StringtempValue", "StringUnitOfMeasurement"] =>

Create instance object:

public class TempStruct {

   private double tempValue;
   private String unitOfMeasurement;

   public TempStruct(double tempValue, String unitOfMeasurement) {
     this.tempValue = tempValue;
     this.unitOfMeasurement = unitOfMeasurement;
   }

}

I try to give a solution with the following way:

Actually I want to create an object of an existing class and I tried to do that with reflection. I use the following code:

Class<?> cls = Class.forName(name);
Object clsInstance = (Object) cls.newInstance();
Field[] objectFields = clsInstance.getClass().getDeclaredFields();

But I get an exception to the 2nd line, when it tries to create the new object. As @JB Nijet said I didn’t know that the method getDeclaredFields() does not return the fields sorted.

Actually, I have a method that accept only List of Strings, so by using reflection I convert the object to List of string, and after that I want to do the opposite. I didn’t think any other way to do it.

Answer

Dynamic instantiation of objects can get pretty complex, and your scenario touches upon several aspects:

  • converting the object values from String to the appropriate type
  • loading the right class from the class name and creating an instance
  • assigning those values into the object

A thorough discussion of each of those points would take up an entire chapter in a no-doubt riveting treatment of Java as a dynamic language. But, assuming you don’t have the time to learn these intricacies, or take a dependency on some huge third party library, let’s whip up something that gets you on your way. Please keep your hands inside the vehicle at all times as the ride is going to get bumpy.

Let’s tackle the issue of type conversion first. The values are provided as Strings, but your object will store them as double, long, int, etc. So we need a function that parses a String into the appropriate target type:

static Object convert(Class<?> target, String s) {
    if (target == Object.class || target == String.class || s == null) {
        return s;
    }
    if (target == Character.class || target == char.class) {
        return s.charAt(0);
    }
    if (target == Byte.class || target == byte.class) {
        return Byte.parseByte(s);
    }
    if (target == Short.class || target == short.class) {
        return Short.parseShort(s);
    }
    if (target == Integer.class || target == int.class) {
        return Integer.parseInt(s);
    }
    if (target == Long.class || target == long.class) {
        return Long.parseLong(s);
    }
    if (target == Float.class || target == float.class) {
        return Float.parseFloat(s);
    }
    if (target == Double.class || target == double.class) {
        return Double.parseDouble(s);
    }
    if (target == Boolean.class || target == boolean.class) {
        return Boolean.parseBoolean(s);
    }
    throw new IllegalArgumentException("Don't know how to convert to " + target);
}

Ugh. This is ugly and handles only intrinsic types. But we’re not looking for perfection here, right? So please enhance as appropriate. Note the conversion from String to some other type is effectively a form of deserialization, and so you’re placing constraints on your clients (whoever is giving you the Strings) to provide their values in specific formats. In this case, the formats are defined by the behavior of the parse methods. Exercise 1: At some point in the future, change the format in a backwards incompatible way to incur someone’s wrath.

Now let’s do the actual instantiation:

static Object instantiate(List<String> args, String className) throws Exception {
    // Load the class.
    Class<?> clazz = Class.forName(className);

    // Search for an "appropriate" constructor.
    for (Constructor<?> ctor : clazz.getConstructors()) {
        Class<?>[] paramTypes = ctor.getParameterTypes();

        // If the arity matches, let's use it.
        if (args.size() == paramTypes.length) {

            // Convert the String arguments into the parameters' types.
            Object[] convertedArgs = new Object[args.size()];
            for (int i = 0; i < convertedArgs.length; i++) {
                convertedArgs[i] = convert(paramTypes[i], args.get(i));
            }

            // Instantiate the object with the converted arguments.
            return ctor.newInstance(convertedArgs);
        }
    }

    throw new IllegalArgumentException("Don't know how to instantiate " + className);
}

We’re taking a lot of shortcuts here, but hey this isn’t the sistine chapel we’re creating. Simply load the class and search for a constructor whose number of parameters matches the number of arguments (i.e., arity). Overloaded constructors of the same arity? Nope, not gonna work. Varargs? Nope, not gonna work. Non-public constructors? Nope, not gonna work. And if you can’t guarantee your class will provide a constructor that sets all the fields like your example TempStruct does, then I’ll call it a day and grab a beer, because this approach is DOA.

Once we find the constructor, loop over the String args to convert them to the types expected by the constructor. Assuming that works, we then invoke the constructor via reflection, wave the magic wand and say abracadabra. Voilà: you have a new object.

Let’s try it with an extremely contrived example:

public static void main(String[] args) throws Exception {
    TempStruct ts =
        (TempStruct)instantiate(
            Arrays.asList("373.15", "Kelvin"),
            TempStruct.class.getName());

    System.out.println(
        ts.getClass().getSimpleName() + " " +
        ts.tempValue + " " +
        ts.unitOfMeasurement);
}

Output:

TempStruct 373.15 Kelvin

GLORIOUS

Categories
discuss

On the fly LESS compiler for java web app?

I am looking for a way to compile CSS LESS files on the server side on demand during development. For example if the browser makes a request to /assets/css/foo.css I want the server to notice that there is an /assets/css/foo.less file and then to have this file complied and the resulting css returned. I am guessing there must be a LESS servlet somewhere that can do this?

I am running tomcat 7 with Spring MVC application

How do I configure a Java Web App to do on the fly LESS compilation?

Answer

I think what you are looking for is a Servlet Filter. I was not aware of an off the shelf one that does LESS compiling and would have started to make one using lesscss-java, but now I can see there is a larger project called Web Resource Optimizer for Java – wro4j with server side LESS support.

Categories
discuss

Sharing images that are stored on internal memory

I have an application in which an ImageView is set and can be clicked to be opened in the gallery.

By default, I use the following code to get a file directory from the external storage to store my jpegs:

File picsDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");

But! Suppose the external storage is not mounted or simply does not exist (Galaxy Nexus), this doesn’t work. So I wrote an if-statement around it and get the internal cache dir as a fall back.

String state = Environment.getExternalStorageState()
if(Environment.MEDIA_MOUNTED.equals(state)){ 
    File picsDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");    
}else{
    context.getCacheDir();
}

The images show up fine in the ImageView, but don’t come through when my intent launches.

Intent intent = new Intent();             
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(imgFile), "image/jpeg");
startActivity(intent);

The gallery gets loaded, but shows a black screen. Presumably because the gallery has no access to files in the cache dir of my app.

As an alternative, I tried using the media content provider that uses MediaStore.Images.Media.INTERNAL_CONTENT_URI, but this leads to an error when trying to inser the image:

java.lang.UnsupportedOperationException: Writing to internal storage is not supported.

What should I do?

Answer

i suppose the problem here is that you are trying open with the gallery a file saved in a private space of memory (getCacheDir return a path relative to your application and only your application can access that memory path)

If you can’t save in external memory, you can try to save in a public path (but that way your media files can be manipulated by every app and if you uninstall your application it doesn’t clean generated media that you saved there)

If you want to use private internal memory, you can write your ContentProvider

i edit to post a content provider i use to acomplish what i said. this is my content provider (i just posted the relevant part you need):

public class MediaContentProvider extends ContentProvider {
private static final String TAG = "MediaContentProvider";

// name for the provider class
public static final String AUTHORITY = "com.way.srl.HandyWay.contentproviders.media";

private MediaData _mediaData;

// UriMatcher used to match against incoming requests
private UriMatcher _uriMatcher;

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public String getType(Uri uri) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public boolean onCreate() {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    // Add a URI to the matcher which will match against the form
    // 'content://com.stephendnicholas.gmailattach.provider/*'
    // and return 1 in the case that the incoming Uri matches this pattern
    _uriMatcher.addURI(AUTHORITY, "*", 1);

    return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {

    Log.v(TAG, "Called with uri: '" + uri + "'." + uri.getLastPathSegment());

    // Check incoming Uri against the matcher
    switch (_uriMatcher.match(uri)) {

    // If it returns 1 - then it matches the Uri defined in onCreate
        case 1:

            // The desired file name is specified by the last segment of the
            // path
            // E.g.
            // 'content://com.stephendnicholas.gmailattach.provider/Test.txt'
            // Take this and build the path to the file
            // String fileLocation = getContext().getCacheDir() + File.separator + uri.getLastPathSegment();
            Integer mediaID = Integer.valueOf(uri.getLastPathSegment());

            if (_mediaData == null) {
                _mediaData = new MediaData();
            }
            Media m = _mediaData.get(mediaID);

            // Create & return a ParcelFileDescriptor pointing to the file
            // Note: I don't care what mode they ask for - they're only getting
            // read only
            ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(m.filePath), ParcelFileDescriptor.MODE_READ_ONLY);
            return pfd;

            // Otherwise unrecognised Uri
        default:
            Log.v(TAG, "Unsupported uri: '" + uri + "'.");
            throw new FileNotFoundException("Unsupported uri: " + uri.toString());
    }
}

then you need in the manifest the reference to your contentprovider, in my case it was

<provider
        android:name=".contentproviders.MediaContentProvider"
        android:authorities="com.way.srl.HandyWay.contentproviders.media" >
    </provider>

and then use it like this

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("content://" + MediaContentProvider.AUTHORITY + "/" + m.id), "image/jpg");

in my case m is an entity that store an id that point to a sqlite db and i use a class that fetch data to populate again the object (with _mediaData), you can just change the code to fit your needs

this way i solved exactly your problem in my application

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