Monday, August 21, 2017

Android with Kotlin: Using Lambda Expressions

The lambda expressions that we will see in Kotlin, are not really a complete novelty ..., in Java they can be used and it is something that other languages like C # already have it from approximately the year 2006 (with .Net 3.0 ).

But what are lambda expressions?

Lambda expressions allow you to pass functionality as an argument in a very simple way and without having to use anonymous classes. This makes coding a lot simpler.

Suppose we have the following function:

fun compare(a: String, b: String): Boolean = a.length < b.length

Mediante una expresión lambda se podría hacer los siguiente:

max(strings, { a, b -> a.length < b.length })

"Max" is a function that takes the value of the second argument, where this second argument is itself a function.

The general format of a lambda expression is:

{
   Param1, param2 -> // parameters separated by comma
   Param1 + param2 // code to execute
}

To finish this with a very practical example, let's first consider the implementation of an "OnItemClicListener" in a ListView in Java, traditionally it would look like this:

mListView.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
  int position, long id) {

  Log.d("onItemClick", "Se hizo clic") // my code.

  }
});

With a lambda expression in Kotlin, it would be simplified this way:

mListView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->

    Log.d("onItemClick", "Se hizo clic") // my code.

}

As you can see, the difference in simplicity and reduction of code is extremely appreciable. However, suppose that view and id are parameters which will not be used, the expression could be simplified even more by replacing those arguments that will not be in use by an underscore:

mListView.onItemClickListener = AdapterView.OnItemClickListener { parent, _, position, _ ->

    Log.d("onItemClick", "Se hizo clic") // my code.

}

Even better, suppose the following classic example of the OnClickListener of a button in Java:

button.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v){

doSomething();

}
});

In Kotlin, it is reduced to a single line:

button.setOnClickListener({ view -> doSomething() })

If the parameters are not used, directly instead of replacing them with an underscore, you can remove them, leaving:

button.setOnClickListener({ doSomething() })

Finally, since the parameter function is unique and the lambda too, I can remove the parentheses with:

button .setOnClickListener { doSomething() }

Something to point out is that Android Studio itself is guiding us and, if it finds that we can replace the code we write for a lambda expression, we next update it automatically by the hand of the "yellow lamp" that usually appears on the margin Left of our code.

Kotlin Lambda Expressions

You can see a complete and implemented example of this and other issues, in the following application that I left complete in Github:

https://github.com/paveliz/ClimaApp_en_Kotlin

Ver la versión en Español de este artículo acá:

https://paveliz.blogspot.com.ar/2017/08/android-con-kotlin-usando-lambda.html

Thursday, September 3, 2015

Managing two fragments in a simple example

When I started to study fragments on Android, I discover the following example on the Developer Android Site: http://developer.android.com/guide/components/fragments.html

Basically, 1 Activity that change two fragments according the layout. It's sounds very useful but this documentation lacks of code that can help me to understand how to create this kind of layouts and fragment interaction.

This is because I created this small example focused on solve the two fragments interaction with 1 main layout.


1) Layouts

I created two activity_main.xml layouts, one in the "layout" folder (default) and the second one in the "layout_land" folder. Android will use this layout on screen rotation to landscape.

activity_main.xml (portrait)

The main layout in portrait mode, will only include the main fragment directly.

activity_main.xml (landscape)

The main layout in landscape mode, will include the main fragment and a second framelayout that I will use as a "container" for the second fragment that will be added programmatically. 

Notice that this layout use a LinearLayout with an Horizontal Divider and of course, Horizontal orientation:

android:divider="?android:dividerHorizontal"android:orientation="horizontal"

Also, notice that I'm using the "android:layout_weight" property according the Android Developer documentation: http://developer.android.com/guide/topics/ui/layout/linear.html#Weight

2) Second fragment detection

Because the main activity will use the both activity_main.xml according the layout orientation I need to find a way to detect if I'm using the layout with one fragment or the layout with two fragments, because if not..., well..., nothing it's going to work well.

To do this, I basically "ask" with the following line if the second framework exists or not:

if (findViewById(R.id.fragment_detail)!=null)

If this conditions its "True", it's because I'm in landscape mode and I'm using the Two Fragments Layout so I need to call the second fragment and show it. If not, there is nothing to worry, because I'm using the main fragment layout that it's already included and called in the layout.

As a result, the main activity will add the second fragment only when he detect need to do it.

3) Fragment calls a method in the Activity (NO hardcoding)

I need to find a way to manage the OnItemClickListener from the ListView in the DetailFragment but calling a method in the MainActivity.

Why?

Basically:

a) I don't want to put references or calls to others Activities inside the OnItemClickListener event in the DetailFragment. It supposed that fragments need to be "reusable", so you should not put references to external activities inside.

b) I want to call an independent method created in the MainActivity from the OnItemClickListener event in the DetailFragment but, I don't want to create a "hardcoding" relationship between both parts. Because again..., I don't know who is going to reuse this fragment in the feature calling it from another activity!

The Result:
- I created an Interface that includes a method.
- I implemented this method in the MainActivity.
- I got an instance of the Activity that creates the DetailFragment in the "onAttach" event inside the DetailFragment.
- I used the instance to access the method that then is called in the ListView.
This is a "clear" way to call a method from a Fragment to an Activity without compromise the independence of the fragment.

As a result, I created what I understand it's a very simple example that covers:

- Managing different layouts between landscape and portrait.
- Implementing and reusing fragments between layouts.
- Uncouple methods calling between fragments and activities.

Main Layout in Portrait:

 


Main Layout in Landscape:





Hope it helps you to understand these concepts. But if you find any doubts or if you find any issue or suggestions to improve this example, please, don't hesitate to contact me.

Tuesday, April 23, 2013

Entrepreneur’s DNA: It’s not only about the idea, but also about the contacts


Entrepreneur’s DNA: It’s not only about the idea, but also about the contacts
‘How many could reach the goal and how many actually reach it?’ I asked myself a while ago when thinking about professional sportsmen. Is it only a matter of perseverance? Is it contacts? Is it resources? Or maybe just that “luck” factor that we all need...

The same happens with entrepreneurs. It isn’t only a question of having an idea but also of being brave enough to go after it and being helped by the appropriate people so as to implement this idea in the real world.

Who was the one who really saw Facebook’s potential? Mark himself knew there was something good about it but he wasn’t very sure about what to do with it. It was then when ex-Napster Sean Parker came into the picture. A controversial figure, with the extensive experience of having developed a product, faced investors, big companies, trials, and even of having lost them. But with all this businessman experience, he can see the product and he can also see the entrepreneur.

Sean didn’t only see Facebook’s potential but he also had enough knowledge that would allow him to make a “key” contribution to the project, and so it was. Facebook wins the first investment capital by the hand of Sean’s contacts.

Being an “entrepreneur” is a process of discovery. In the Gold Rush days, discoverers spent never-ending hours straining water to find gold. Persevering, analyzing our ideas and taking them from the paper to the action is the key process.

‘The best way to have a good idea is to have lots of ideas’, Linus Pauling.

The Launch: what is the most important thing about the launch of my idea? Making an extensive and complex development or just quickly looking for a way of letting the world try my idea? People have to know it! Immediate feedback is essential!

‘Grooveshark’s first version was a Frankenstein… But it’s always better to win back the audience later than to waste years just thinking about the perfect concept that may never be ready”, Andrés Barreto.

Friends, Contacts and Partners: how much am I doing to improve my profile? (see also “Personal Branding: today more than ever!”). Or, if that question is too complex to answer: how much am I doing for my contacts? Those which will afterwards help me to enrich the entrepreneurship by adding their vision, advice and more contacts.
The entrepreneurship business is also about sharing. I had the chance of listening to Alec Oxenford’s advice about enterprise, sharing and having a partner (Alec is the Co-Founder and Co-CEO of OLX): “It’s better to have part of the whale than 100% of the minnow”, told us humorously.

‘I’ve been blessed to find people who are smarter than I am, and they help me to execute the vision I have’, Russell Simmons. Founder of Def Jam Records.

I believe that these components are the ones that, all together, make an idea, an enterprise grow, and they are the key to its potential success.

Last but not least, I would like to share an example about this issue which I personally experienced with a project called Liibook (I hope I can write a specific article about it in the future). Federico Roma (founder), talented and visionary graphic designer, had the idea of a platform of books publication available on the Internet and open to everyone. With only his idea, he looked out for 2 key contacts which supported him from the business perspective, the entrance into the market, as well as from a technological point of view to carry out at least the first implementation.

What is important about this initiative is the fact that Federico bet on his idea and the contacts that made it possible for that idea to reach its goal. A year after winning Wayra, the Wheel in Sillicon Valley and his presentation on 2012’s TechCrunch, Liibook landed in San Francisco where it is expected that it will receive investments that will lead to more growth. All this was achieved thanks to Federico’s vision and his trust on the contacts that knew how to support and help him.

Monday, March 4, 2013

Personal Branding: Today more than ever!


Some time ago, I had the chance of reading a very interesting article about how important “Personal Branding” is for managers nowadays. I instantly remembered reading a catchy book by Tom Peters, “The Brand You50”. At that point, I understood that Personal Branding not only means belonging to a big company, being an expert in one or more technical areas, doing business or giving talks, but it also refers to taking advantage of each of these skills and activities to gain leverage in order to create a Personal Branding. The key is to use all these elements from your personal CV to build a trademark of yourself. But, where do we start?

In the past, it was possible to be relatively safe by only staying in the shadows… Nowadays, this is more difficult. (Michael Goldhaber, Wired)

Don't compromise yourself. You're all you've got. (Janis Joplin)

Globalization, competition, massive layoffs, crisis such as Argentina’s in 2001 or Europe’s nowadays, then, show managers that a university degree or expertise are only one part of success, they have to go out and sell themselves and find new ways of showing their professional skills, their potential and values.  Peters refers to this as the “White Collar Revolution”, but in his review (that he himself brands as alarming) he is just describing reality. The “standard” employee is not essential. You will be replaced if your work is not special; no matter how hard you work, no one will pay attention to it and, obviously, you will start to earn less money. The key is personal reinvention… And Tom says: Do it to yourself, before they do it to you”. Then, when we finally face the reality, or others “make” us face the reality that job security doesn’t exist, it’s high time for you to take the initiative and reinvent yourself. Tom goes deeper into this issue: it is important not to think that your job is not good, but rather that it is not the only possibility we have and that each of us can and must give more from ourselves.

Nowadays, there are several options available to improve and spread our personal profile. Writing in blogs, keeping profiles updated in LinkedIn, making comments on topics of interest on Twitter are only some of the possibilities. Of course this is not a success formula; it’s only part of the process. The real value is what each of us is and does. A well-known concept arises, then – “specialization”.

Basic and clear concepts:

Profession = marketable skills!
Distinction = Unforgettable!
Build a network of connections = Word-of-mouth advertising!

The key is to be an “expert” and stand out from the crowd in some specific area in which one performs excellently!

The future of professional careers will be to find the expert of the expert. Hatum, PhD in Management and Organization, Warwik Business School (England).

In the future labor world, stability will no longer be the main variable companies will offer us. Constant change forces us to be adaptable. Hugo Pardo Kuklinkski, CEO of Imagine Postdigital, founder of Funky Mobile Ideas.

Nowadays, it is vital for us to leave the anonymity of the office to show the world our expertise. “The Brand I” or “Personal Branding” are topics which demand you to see yourself as your own company and show that you need to spread what you do and who you are.

Fletchers straighten arrows; carpenters shape wood; the wise master themselves. (Buda)

This isn’t as simple as it seems, though. So as to finish this article, I will leave you with a key question that can be the starting point for you: What do I want to be? What do I want to represent?

In an article for IAE alumni magazine, Martín Frias (Pragmativa Digital Marketing Director) says: “it’s important to know where one is headed. You don’t need to “get on the wave” only to follow the herd. The idea is to create content.

So, this simple concept has some aspects to analyze and we could continue going deeper for a long time. The following list is a summary of the concepts taken from the original article which inspired this post and Tom’s book. They are guidelines we can have in mind when implementing this idea of “The Brand I”:

1) Have a clear goal: what do I want to be? How do I want to be recognized?

2) Complete Commitment with the project.

3) You are your clients, so connect with them!

4) You are your contact list, never stop enlarging it!

5) Upgrading: keep your profile updated.

6) Honesty: lie is your worst enemy. Trust and openness are two of the most valuable assets which make up the concept of personal branding.

7) Self-promotion: take part in talks and means of communication in an active and regular way.

8) Add value; remember that everything you say or write should add value to your audience.

9) Trial and error: you have to make mistakes in order to learn. Although it is important to be careful, don’t forget that everything remains in the Web!

10) Come on! Try it!

Monday, February 11, 2013

Windows Phone 8: Five characteristics to bear in mind


On October 29th Windows Phone 8 was officially launched. But, what is it? Wasn’t Windows Phone already on the market? Are we changing everything again?

It is a combination of everything and I believe it would be better to start with a brief introduction before going into some of its characteristics.
Windows Phone has been on the market since 2010 and its current version is 7.8, although only a few know of the upgrades of 7, 7.5 Mango and 7.5 Tango. Following the launch of its already classic and well-known operating system  - Windows 8 -, Microsoft has also launched a new Windows version for mobile devices. So much so, that this new version differs from its predecessor in many aspects and brings up the so-called “fragmentation” problem that are already present in Android. According to its main distinctive features, WP8 is prepared to and designed for dual-core processors, something that users have been demanding for a long time. So far, the newest equipment available launched this year* (e.g. Nokia Lumia 900) are not dual-core. The recently launched Lumia 920, which includes WP8, has a Qualcom dual-core. Generally speaking, fragmentation problems cause almost no impact on users, since they all expect to change their equipment for a better and faster one. However, these problems demand regular applications upgrades and tests in different platforms for developers and companies. 

In my opinion, these new version offers original features and I consider it an achievement since Microsoft was a bit "late" in entering the mobile market.

Let’s see now some of its most important characteristics:

Data Sense

As part of its operative system, WP8 includes network consumption control with any server we have, plan setting and alarms. So far so good. But when Data Sense is on, it works on data together with new IE10, which reduces transfer and speed rates significantly. Apart from that, Data Sense automatically checks for nearby Wi-Fi Spots and, if so, reroutes traffic to them. According to Microsoft, Data Sense decreases data plan consumption by as much as 45%.

Kid's Corner 

Behind this function lies the idea of kids using mobile devices without parents worrying as regards which applications they use or games they play, the so-called “parental control”. According to local statistics, 66% of parents let their children use mobile devices. Microsoft promotes this feature as easy-to-use, with the possibility of quickly setting the games, applications and pictures that are available and those which block the device, or even select the image for each application. Paid applications and the store remain unavailable, so parents don’t need to worry about the card. Kids can customize the screen, the wallpaper and even include their names. When Kid’s Corner is closed, the device goes back to its usual configuration.

Wallet 

Microsoft adds an application where not only can the user safely save their credit card data, but also use them via NFC. This app is linked with others so as to show available offers and shops, as well as providing account summaries and consumption history.
Microsoft shows great progress here and provides a good opportunity for new developments and business with this innovative feature, also giving Microsoft the chance to compete against Apple platform. It’s been at least two years since Android equipments from Samsung included NFC technology, thus launching to fame platforms such as Google Wallet, iPhone 5 and iOS 6. Users still wonder: when will Apple “become friends” with this standard?






“Live” lock screen

It isn’t the most original of functions, but it presents some differences with Android system. Live lockscreens have tiles with information of different data apps such as news or sports, together with a list of unread e-mails and received messages. Apparently, it won’t be just an animated wallpaper which only consumes battery like Android’s, but it will be something useful.

Rooms 

This appears to be an innovative concept in the mobile devices world, but in some way it already exists in social networks like Google+. In the contacts hub there is a new access or section called “together”, which allows the user to create different Rooms among available users:

Room Chat: A chat between the members of a room. Everyone can see messages and, with the new “location” service, where each of them is.

Shared Calendar: Each Room has a shared calendar which can be seen and updated by any member of the group. If a member updates anything, this is synchronized in every member’s equipment.

Shared Photo Album: It gives members of a group the possibility of sharing pictures and videos. Users only need to upload a picture and it will be available only for the group members.

Shared Notes: By using the famous Office “Notes”, users can share these with the rest of the group.


There a lot more of interesting innovations and integrated components of Windows Phone 8, but I don’t want to expand on them too much. I hope you like this post and, hopefully, I will continue with this topic in the future.



References:
http://www.wpcentral.com/keep-track-data-usage-data-sense-windows-phone-8
http://www.wpcentral.com/kids-corner-windows-phone-8
http://www.wpcentral.com/introducing-windows-phone-8-wallet
http://www.wpcentral.com/live-wallpapers-revealed-windows-phone-8-facebook-espn-usa-today-and-bing
http://www.wpcentral.com/windows-phone-8-rooms-feature