Categories
discuss

Why Java Method Reference of instance method cannot be assigned to Consumer interface

Here is my Code :

public class SearchByLambda {

     private Map<String,Consumer<Person>> searchCritertiaHolder = new HashMap<String,Consumer<Person>>();

     private static final String AGED = "aged";

     public SearchByLambda(){
           searchCritertiaHolder.put(AGED, (Person p)-> {p.filterAgedPerson(p);} );
     }

     private Consumer<Person> getFilter(String personType){
          return searchCritertiaHolder.get(personType);
     }

     public static void main(String[] args) {
          SearchByLambda searchUsage = new SearchByLambda();
          Person p = new Person(59,"shailesh");
          Person p1 = new Person(58,"ganesh");

          searchUsage.getFilter(AGED).accept(p);
          searchUsage.getFilter(AGED).accept(p1);

          Person.printAgedPersons();
     }
 }

 class Person{

       private static List<Person> agedPersons = new ArrayList<>();

       private int age;

       private String name;

       public int getAge() {
              return age;
       }

       public void setAge(int age) {
          this.age = age;
       }

       public String getName() {
            return name;
       }

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

       public Person(int age,String name){
           this.age = age;
           this.name = name;
       }

       public void filterAgedPerson(Person person){
          if(person.getAge() > 58){
              agedPersons.add(person);
          }
       }

       public static void printAgedPersons(){
            for(Person person : agedPersons){
                System.out.println(person.getName());
            }
       }
 }

When I replace following Lambda expression

     searchCritertiaHolder.put(AGED, (Person p)-> {p.filterAgedPerson(p);});

with

              searchCritertiaHolder.put(AGED, Person::filterAgedPerson);

it gives me compilation error. I am using java 8 and and compiling through eclipse. Why is this so? Why cannot I assign method reference for instance method of any arbitrary object to consumer functional interface?

Answer

Your definition of filterAgedPerson takes a Person as an argument, even though it is not a static method. It doesn’t need to, and it shouldn’t if you want to use it as a Consumer<Person>. What you are ending up with is something compatible with BiConsumer<Person, Person>.

It might help to think of it this way: method references to non-static methods always take an “extra” argument which is used as this.

The easiest way for you to fix this with your current code structure is to modify the filterAgedPerson method to not take a Person as an argument

   public void filterAgedPerson() {
      if (this.getAge() > 58) {
          agedPersons.add(person);
      }
   }

As an aside, you might want to also consider making your filters Predicate<Person> instead of Consumer<Person> and moving the results handling elsewhere. This will give you more flexibility as things get more complicated.

Categories
discuss

Unable to Use Android USB Drivers on Windows 10

Following the Standard instructions to make use of the USB Drivers for Android Development provided by Google here

http://developer.android.com/sdk/win-usb.html

Does not work on Windows 10

Answer

1) Right click on the Start menu and select Device Manager

2) Right click on the Android Device and select Update Driver

3) Select Browse my computer for driver software

4) Select Let me pick from a list of device drivers on my computer

5) Select have Disk and find the below location and paste in.

<SDK Location>extrasgoogleusb_driver

Default location might be like below.

C:Users<your username>AppDataLocalAndroidandroid-sdkextrasgoogleusb_driver

6) Click Next

7) Select the Android ADB Interface

8) Allow debugging on your device and your all set

You should now be able too easily develop on Xamarin or any other android platform and debug right to your device

Categories
discuss

Setting Singleton property value in Firebase Listener

I’m currently testing out Firebase along with a Singleton model I plan to use to access during the lifecycle of the whole app. I’m now stuck with something that seems really trivial but I can’t figure it out for the life of me. I have a sample of the model I use: Bookmarks in firebase.

public class BookSingleton {



private static BookSingleton model;

private ArrayList<BookMark> bookmarks = new ArrayList<BookMark>();


public static BookSingleton getModel()
{
    if (model == null)
    {
        throw new IllegalStateException("The model has not been initialised yet.");
    }

    return model;
}


public ArrayList<Bookmark> theBookmarkList()
{
    return this.bookmarks;
}


public void setBookmarks(ArrayList<Bookmark> bookmarks){
    this.bookmarks = bookmarks;
}


public void loadModelWithDataFromFirebase(){
    Firebase db = new Firebase(//url);
    Firebase bookmarksRef = fb.child(//access correct child);


    final ArrayList<Bookmark> loadedBookmarks = new ArrayList<Bookmark>();
    bookmarksRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
                    //getting all properties from firebase...
                    Bookmark bookmark = new Bookmark(//properties here);
                    loadedBookmarks.add(bookmark);



                }
            }
            //bookmarks still exist here at this point
            setBookmarks(loadedBookmarks);

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    //by now loadedBookmarks is empty
    //this is probably the issue?
    //even without this line bookmarks is still not set in mainactivity
    setBookmarks(loadedBookmarks);
}

Now when I start the mainActivity with the instance of the Singleton set I get a null error because clearly the function I wrote to load the model data from firebase sets nothing.

Something like this: MainActivity

public class MainActivity extends AppCompatActivity {

private BookSingleton theModel;



@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Load the model
    theModel = BookSingleton.getModel(this);
      //manually setting this works 
      //        ArrayList<Book> bookSamples = new ArrayList<Book>;
      //        bookSamples.add(aBookSample);

    theModel.loadModelWithSampleData(bookSamples);
    //should have set the singleton model property Bookmarks to the results from firebase

    theModel.loadModelWithDataFromFirebase();
    //returns 0
    Log.d(TAG, "" + theModel.theBookmarkList().size());


    setContentView(R.layout.activity_main);

    //......rest of code

How can I make this work?

Answer

Firebase loads and synchronizes data asynchronously. So your loadModelWithDataFromFirebase() doesn’t wait for the loading to finish, it just starts loading the data from the database. By the time your loadModelWithDataFromFirebase() function returns, the loading hasn’t finished yet.

You can easily test this for yourself with some well-placed log statements:

public void loadModelWithDataFromFirebase(){
    Firebase db = new Firebase(//url);
    Firebase bookmarksRef = fb.child(//access correct child);

    Log.v("Async101", "Start loading bookmarks");
    final ArrayList<Bookmark> loadedBookmarks = new ArrayList<Bookmark>();
    bookmarksRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.v("Async101", "Done loading bookmarks");
            //getting all properties from firebase...
            Bookmark bookmark = new Bookmark(//properties here);
            loadedBookmarks.add(bookmark);
        }

        @Override
        public void onCancelled(FirebaseError error) { throw error.toException(); }
    });
    Log.v("Async101", "Returning loaded bookmarks");
    setBookmarks(loadedBookmarks);
}

Contrary to what you likely expect, the order of the log statements will be:

Start loading bookmarks
Returning loaded bookmarks
Done loading bookmarks

You have two choice for dealing with the asynchronous nature of this loading:

  1. squash the asynchronous bug (usually accompanied by muttering of phrases like: “it was a mistake, these people don’t know what they’re doing”)

  2. embrace the asynchronous beast (usually accompanied by quite some hours of cursing, but after a while by peace and better behaved applications)

Take the blue pill – make the asynchronous call behave synchronously

If you feel like picking the first option, a well placed synchronization primitive will do the trick:

public void loadModelWithDataFromFirebase() throws InterruptedException {
    Firebase db = new Firebase(//url);
    Firebase bookmarksRef = fb.child(//access correct child);

    Semaphore semaphore = new Semaphore(0);

    final ArrayList<Bookmark> loadedBookmarks = new ArrayList<Bookmark>();
    bookmarksRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Bookmark bookmark = new Bookmark(//properties here);
            loadedBookmarks.add(bookmark);
            semaphore.release();
        }

        @Override
        public void onCancelled(FirebaseError error) { throw error.toException(); }
    });
    semaphore.acquire();
    setBookmarks(loadedBookmarks);
}

Update (20160303): when I just tested this on Android, it blocked my app. It works on a regular JVM fine, but Android is more finicky when it comes to threading. Feel free to try and make it work… or

Take the red pill – deal with the asynchronous nature of data synchronization in Firebase

If you instead choose to embrace asynchronous programming, you should rethink your application’s logic.

You currently have “First load the bookmarks. Then load the sample data. And then load even more.”

With an asynchronous loading model, you should think like “Whenever the bookmarks have loaded, I want to load the sample data. Whenever the sample data has loaded, I want to load even more.”

The bonus of thinking this way is that it also works when the data may be constantly changing and thus synchronized multiple times: “Whenever the bookmarks change, I want to also load the sample data. Whenever the sample data changes, I want to load even more.”

In code, this leads to nested calls or event chains:

public void synchronizeBookmarks(){
    Firebase db = new Firebase(//url);
    Firebase bookmarksRef = fb.child(//access correct child);

    final ArrayList<Bookmark> loadedBookmarks = new ArrayList<Bookmark>();
    bookmarksRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Bookmark bookmark = new Bookmark(//properties here);
            loadedBookmarks.add(bookmark);
            setBookmarks(loadedBookmarks);
            loadSampleData();
        }

        @Override
        public void onCancelled(FirebaseError error) { throw error.toException(); }
    });
}

In the above code we don’t just wait for a single value event, we instead deal with all of them. This means that whenever the bookmarks are changed, the onDataChange is executed and we (re)load the sample data (or whatever other action fits your application’s needs).

To make the code more reusable, you may want to define your own callback interface, instead of calling the precise code in onDataChange. Have a look at this answer for a good example of that.

Categories
discuss

How to send data from child controller to Parent controller in AngularJS?

I need some guidance to take the best practice for my task in AngularJS.

Task:

  1. Inside the view : I have one parent controller and two child controllers.
  2. Child controllers work with their own $scope and objects.
  3. When I press save in the view, I need to get the data from child controllers to parent controller in order to prepare an object for posting it to the server.

I am getting confused of what is the best solution for this approach.

Answer

A common way of sharing data between controllers is to use use a service.

You could also broadcast updates to the parent controller

Categories
discuss

No implementation found for void net.sqlcipher.database.SQLiteDatabase

I saw this error when trying to use sqlcipher in my project. I looked it up and found several people resolved it by adding SQLiteDatabase.loadLibs(); However, it says it’s expecting an @NotNull Context context and I wasn’t sure what it means. Has anyone resolved this issue? This and this are two of the sources I used.

The dependency in my gradle.build is compile ‘net.zetetic:android-database-sqlcipher:3.3.1-1@aar’ and since I have this, it means I don’t have to manually move any files to my libs directory, right?

@Override
public void onCreate(SQLiteDatabase db) {
    SQLiteDatabase.loadLibs();

    db.execSQL(CREATE_SCRIPT);
}

Apologies in advance if these are basic questions.

Answer

However, it says it’s expecting an @NotNull Context context and I wasn’t sure what it means.

It means that loadLibs() needs a Context as a parameter.

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