Categories
discuss

How to call T eq(Object) method of Java interface from Scala?

Scala defines an AnyRef class which is after compilation interpreted somewhat as Java’s Object class. The AnyRef class, however, is not exactly equivalent to Object from the language point of view, because it introduces several new methods, such as eq(), which takes AnyRef and returns Boolean and compares references for identity

If there is a class in Java which itself defines the eq() method with a different result type and an interface which this class implements also having this method:

public interface I {
    String eq(Object that);
}

public class A implements I {
    public String eq(Object that) {return "";}
}

then its eq method becomes inaccessible to Scala code if called via interface reference

val i: I = new A
val a = new A
val b = Some(1)           //whatever actually
val s1: String = a.eq(b)   //compiles OK
val s2: String = i.eq(b)   //compilation error

The eq method Scala knows about here is the eq method from the AnyRef class being “glued” to interface I which came from Java without that method, but with an eq() method of its own with a different result type. I can explain this behavior, but can’t solve the real-life task when I have to call this Java eq() method without a possiblity to modify the code of the Java third-party library. Namely I’m talking about Liferay and its Dynamic Query API and the interface named com.liferay.portal.kernel.dao.orm.Property. It has an eq() method taking Object and returning Criterion. This code won’t compile in Scala:

val query = DynamicQueryFactoryUtil.forClass(classOf[BookmarksEntry])
.add(PropertyFactoryUtil.forName("folderId").eq(new Long(folderId)))

because eq won’t be interpreted correctly. Just to mention, the Property class has another overload of the eq() method which takes DynamicQuery as parameter. This overload is accessible from Scala.

Do you know of any way to call that eq(Object) method of Java interface from Scala?

Scala version used is 2.8.1

Answer

Interesting problem: I hadn’t seen this one before. I don’t know how to solve it in Scala, or even if it is possible at all. On such situations, however, the best you can do is create a wrapper in Java. For example:

public class Eq {
    static public String eq(I obj, Object that) {
        return obj.eq(that);
}

You then just call Eq.eq(x, y) instead of x.eq(y).

Categories
discuss

Android.App.Activity – package does not exist

I got an andorid project files that are supposed to compile correctly.

I installed the latest eclipse and Andriod ADT plugins.

I then imported the project and right clicked build.xml to run as ANT build. but I got erors on some basic code which I am sure is originating from my misconfigured setup.

I also tried to run it using ANT from the command line. both times I got the same type of errors

What is wrong ?

    Buildfile: /Users/admin/Downloads/moshe-5/build.xml
    init:
    process.annotations:
        [javac] Compiling 9 source files to /Users/admin/Downloads/moshe-5/build/classes
        [javac] /Users/admin/Downloads/moshe-5/src/ti/moshe/CustomAdapter.java:7: package android.app does not exist
        [javac] import android.app.Activity;
        [javac]                   ^
        [javac] /Users/admin/Downloads/moshe-5/src/ti/moshe/CustomAdapter.java:8: package android.content does not exist
        [javac] import android.content.Context;
        [javac]                       ^
        [javac] /Users/admin/Downloads/moshe-5/src/ti/moshe/CustomAdapter.java:9: package android.graphics does not exist
        [javac] import android.graphics.Color;

Answer

Don’t bother building using ANT. Eclipse and the ADT plugin provide excellent tool to save you the trouble. Simply right click the project, choose run as -> Android application

Categories
discuss

ViewPager PagerAdapter not updating the View

I’m using the ViewPager from the compatibility library. I have succussfully got it displaying several views which I can page through.

However, I’m having a hard time figuring out how to update the ViewPager with a new set of Views.

I’ve tried all sorts of things like calling mAdapter.notifyDataSetChanged(), mViewPager.invalidate() even creating a brand new adapter each time I want to use a new List of data.

Nothing has helped, the textviews remain unchanged from the original data.

Update: I made a little test project and I’ve almost been able to update the views. I’ll paste the class below.

What doesn’t appear to update however is the 2nd view, the ‘B’ remains, it should display ‘Y’ after pressing the update button.

public class ViewPagerBugActivity extends Activity {

    private ViewPager myViewPager;
    private List<String> data;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        data = new ArrayList<String>();
        data.add("A");
        data.add("B");
        data.add("C");

        myViewPager = (ViewPager) findViewById(R.id.my_view_pager);
        myViewPager.setAdapter(new MyViewPagerAdapter(this, data));

        Button updateButton = (Button) findViewById(R.id.update_button);
        updateButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                updateViewPager();
            }
        });
    }

    private void updateViewPager() {
        data.clear();
        data.add("X");
        data.add("Y");
        data.add("Z");
        myViewPager.getAdapter().notifyDataSetChanged();
    }

    private class MyViewPagerAdapter extends PagerAdapter {

        private List<String> data;
        private Context ctx;

        public MyViewPagerAdapter(Context ctx, List<String> data) {
            this.ctx = ctx;
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object instantiateItem(View collection, int position) {
            TextView view = new TextView(ctx);
            view.setText(data.get(position));
            ((ViewPager)collection).addView(view);
            return view;
        }

        @Override
        public void destroyItem(View collection, int position, Object view) {
             ((ViewPager) collection).removeView((View) view);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public void startUpdate(View arg0) {
        }

        @Override
        public void finishUpdate(View arg0) {
        }
    }
}

Answer

There are several ways to achieve this.

The first option is easier, but bit more inefficient.

Override getItemPosition in your PagerAdapter like this:

public int getItemPosition(Object object) {
    return POSITION_NONE;
}

This way, when you call notifyDataSetChanged(), the view pager will remove all views and reload them all. As so the reload effect is obtained.

The second option, suggested by Alvaro Luis Bustamante (previously alvarolb), is to setTag() method in instantiateItem() when instantiating a new view. Then instead of using notifyDataSetChanged(), you can use findViewWithTag() to find the view you want to update.

The second approach is very flexible and high performant. Kudos to alvarolb for the original research.

Categories
discuss

How to change a field name in JSON using Jackson

I’m using jackson to convert an object of mine to json. The object has 2 fields:

@Entity
public class City {
   @id
   Long id;
   String name;
   public String getName() { return name; }
   public void setName(String name){ this.name = name; }
   public Long getId() { return id; }
   public void setName(Long id){ this.id = id; }
}

Since I want to use this with the jQuery auto complete feature I want ‘id’ to appear as ‘value’ in the json and ‘name’ to appear as ‘label’. The documentation of jackson is not clear on this and I’ve tried every annotation that even remotely seems like it does what I need but I can’t get name to appear as label and id to appear as value in the json.

Does anyone know how to do this or if this is possible?

Answer

Have you tried using @JsonProperty?

@Entity
public class City {
   @id
   Long id;
   String name;

   @JsonProperty("label")
   public String getName() { return name; }

   public void setName(String name){ this.name = name; }

   @JsonProperty("value")
   public Long getId() { return id; }

   public void setId(Long id){ this.id = id; }
}
Categories
discuss

What is “android:key” in used for?

In this example XML Layout of a PreferenceScreen:

<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:key="first_preferencescreen">
    <CheckBoxPreference
            android:key="wifi enabled"
            android:title="WiFi" />
    <PreferenceScreen
            android:key="second_preferencescreen"
            android:title="WiFi settings">
        <CheckBoxPreference
                android:key="prefer wifi"
                android:title="Prefer WiFi" />
        ... other preferences here ...
    </PreferenceScreen>
</PreferenceScreen> 

I noticed an android:key for both PreferenceScreens (nested in each other).

I couldn’t find, however, any use for them in application code: The only keys used to access a value by program code are the ones of the actual elements: CheckBoxPreference, EditTextPreference, etc.

Can they be utilized for specifying in code “access the CheckBoxPreference that’s in this PreferenceScreen and not the other”? i.e. hierarchical access?

If not, what is the purpose of the key for a PreferenceScreen? Must it be defined? Must it be unique?

Answer

It is XML attribute belonging to superclass named Preference. It is documented http://developer.android.com/reference/android/preference/Preference.html#attr_android:key

The application can have some use of the key, say if it is listening to changes in particular preferences like: onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)

Yes. The key purpose and value might be restricted a lot, it is certainly unique. But to define how unique and in what scope, will need more reading. (I did not look at more that just few pages of online docs)

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