Making lists with Recyclerview

In my dev journey I came across lots of challenges, so I thought it would be really nice to give back to the community and create a series of tutorials. I'm gonna highlight some of the things that got me the most headaches at first.


RecyclerView

The best way to go

 

So you wanna make a list in your app, maybe just a simple grocery list or a more complicated one containing text, images and all the good stuff. What if you wanna get all that information from the cloud? There are many ways to do this, but I'm going to show you how to use the newest, and best of them. That would be the RecyclerView (I'm gonna assume you already know what views and layouts are).

It will seem really complicated at first, because by itself the RecyclerView needs a lot of elements to function but you'll soon realise it all works easily, and logically.


What you need

Let's get a bird's eye view of everything that we need at first. 

 

So you booted up good ol' Android Studio, created a new project, and now you have a layout file, called activity_main.xml and a Java file, called MainActivity. 

As the RecyclerView is a newer thing, or just because google literally forgot it launched it in 2014, we need to tell Android Studio that we need the files containing it, so it can recognise it later.

In order to do that, navigate to the Gradle Scripts in the left pane of your screen, there you'll see a file called build.gradle (Module: app). Open it and scroll to the bottom of the page. There you'll see this:

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
}

Now what you need to do is just change that to this:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:cardview-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.android.support:design:25.0.1'
}

That's it, you imported all the necessary files 👌🏻. Now let's go to your res/layout/ folder, once you're there go ahead and open activity_main.xml. As usual with layouts in android, we gotta write it's tags to create it, so we can give it height, width and anything your ❤️ might desire.

Now go ahead and write, or copy, this code into your layout. What it does basically is create the RecyclerView in our layout, make it as wide and as tall as the entire screen, and most importantly it gives it an unique id, RecyclerView.

<android.support.v7.widget.RecyclerView
android:id="@+id/RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

You're basically done at this point with this layout file, but we gotta write a bit more XML before jumping to the Java part. Btw, if you run your app right now it's probably just generate some random things, don't care about that 👌🏻

Now, right click on your layout folder and tap on New > Layout Resource File. Just give it the name of item.xml and press enter. This layout file will be how every item of the list will look like. It's gonna have two text boxes two keep it simple. Basically the idea here is to make a template then change it's contents with what we want. Here's what you gotta do:

<android.support.v7.widget.CardView
android:id="@+id/item"
android:layout_width="match_parent"
android:layout_height="100dp">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

 <TextView 
  android:id="@+id/subtitle" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content"
  android:layout_below="@id/title" />

</RelativeLayout>
</android.support.v7.widget.CardView>

Congrats, we're all done with the XML part of the job. Now let's get to Java. Let's first review what we've done. We added the RecyclerView to our layout and created a template item. But by themselves they don't really know what to show. So let's add a logic to all of this.


Building the logic

 

As we're done with the XML, open your Java folder. We will write in Java the logic behind the ReyclerView. We'll need 3 main things to make this function properly. Firsly, we need a thing called the Adapter. This is like the backbone of the list, it controls what happens to every item. For example if you want to have the 3rd item of the list red, you'd do this kind of thing here. But you can also make changes to every single item at once.

I want you to right-click on the Java folder and go to New > Java Class, then just name it Adapter.java and press enter to create it. After we're finished, the whole structure will look like this:

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

 public static class ViewHolder extends RecyclerView.ViewHolder {
 ...
 ViewHolder(View itemView) {
super(itemView);
}
}

List<Item> list;

Adapter(List<Item> list) {
this.list = list;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
return new ViewHolder(v);
}

@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
 ...
}

@Override
public int getItemCount() {
return list.size();
}
}

This might look a bit scary at first, but at first you don't have to know everything that's happening there, most of it is autogenerated code. But what we need to focus on is the ViewHolder, here we'll declare all our views, in this case the two TextViews we just made in XML. After you've declared them, your code should look like this:

public static class ViewHolder extends RecyclerView.ViewHolder {

  //Initialise the Views
  TextView title;
TextView subtitle;

//Initialise the ViewHolder
ViewHolder(View itemView) {
super(itemView);
title= (TextView) itemView.findViewById(R.id.title);
subtitle = (TextView) itemView.findViewById(R.id.subtitle);
}
}

Now that we're done with that, we need to give the adapter a list to work with. It's like we're giving it a grocery list containing all our ingredients, after that we'll tell it what to do with them. In the below code, list is the list we'll tell our adapter to use, and <Item> is a custom class we'll soon define. To better wrap your head around it, just swap in your head <Item> with <Animal> and think we're going to add two attributes to it, Height and Color. In this case, list would contain for example Tiger, Dog, Cat, each having a Height and a Color. Height would be the title, and color would be the subtitle. This is the code for it:

//Adapter parameters
List<Item> list;

//Adapter initialization
Adapter(List<Item> list) {
this.list = list;
}

The next function is called onCreateViewHolder, you don't have to care about this one for now, just leave the code how it is.

The most important part of the Adapter is the onBindViewHolder. This function is what controls what happens to the individual items in the list. It sorts through the list and makes your desired changes to every item. To get a good idea of what you can do with it, let's make it change the text of our Title and Subtitle text fields and when we press on the Title it will show us a message with what it contains. You do it like this:

@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
viewHolder.title.setText(list.get(position).getTitle());
  viewHolder.subtitle.setText(list.get(position).getSubtitle());
  
  viewHolder.title.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
  String text = list.get(position).getTitle());
Toast.makeText(view.getContext(), text, Toast.LENGTH_SHORT).show();
 });
}

At this point we're done with the Adapter, don't run your code just get cus you'll have some missing file errors. We're gonna create them right now. As you might've seen, when we set the text of the title and subtitle, we call a .getTitle(); function. We will now define this function is our <Item> file. Think of the function .getHeight(); for a given animal.

Create a new Java file called Item.java, and make it look like this:

public class Item {

  //Those are the values for a specific item in the list
String Title;
String Subtitle;

 //Here's where we initialise these values
public Photo(String Title, String Subtitle) {
this.Title= Title;
this.Subtitle = Subtitle;
}

  //This will be our function we talked about
public String getTitle() {
return Title;
}

//And of course, the second one
  public String getSubtitle() {
return Subtitle;
}
}

Now that we're done, your errors in your Adapter file will disappear. We're really close to finishing it all. Obviously, what we need to do now is define our RecyclerView in our MainActivity and then just enter some values in our list. Those values will be shown in the RecyclerView when we run the app.

First of all, open your MainActivity class, and before the onCreate function, declare these variables:

RecyclerView recyclerView;
Adapter adapter;
ArrayList<Item> list;

Then, in the onCreate(); function you need to initialise the variables, also define some options to the RecyclerView (you don't have to care about them, for now)

recyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

list = new ArrayList<>();

Now, we need to add some content to our list, in order to do that just do this:

list.add(new Postare("Title1", "Subtitle1));
list.add(new Postare("Title2", "Subtitle2));
list.add(new Postare("Title3", "Subtitle3)); 
list.add(new Postare("Title4", "Subtitle4));

Finally, just link the RecyclerView to the Adapter, like this:

recyclerView.setAdapter(new Adapter(list));

You did it 

Wrapping it up, we're all done at this point, you can run your app and see what happens. From now you can change stuff around, add more content to the list, such as images or add more levels of interactivity. 

Let's make it a bit more fun by giving you a challange, try to find a way in which when you press one list item, the text gets underlined. Share your results with me on Instagram or Facebook

 

 

 

 

 

 

 

The importance of motion

In yesterday's post I've talked about how keeping motion in mind can highly improve your app game. Animations breathe life into your app, they give it character and can tell a story.

 

While these tips apply to some other fields, such as iOS and Web development, in this post I'm going to talk more in depth about motion in Android.

Animations are literally everything you see changing on screen, everything that isn't static. This gives you thousands of opportunities to improve on how your app feels and what it transmits to the user. 

 

Before talking about where and how to use animations, let's talk about the many ways of implementing them in Android.

There are two ways of making animations in Android, declaring them in your activity or creating a separate XML file. My preferred way of doing this is the XML route, but your milage may vary. They both have their benefits and drawbacks, but I personally like declaring them in XML just because they'll be easier to find later and your code will be much cleaner.

1. How do they work?

The basic principle behind animations is literally just: a start point, an end point and a known duration. You can pretty much animate everything from text to images. From that you can branch out to these 3 different types of animations:

Opacity

Also knows as "alpha", it's role is pretty self explanatory, it controls the transparency of the object at hand. This is pretty useful for when you want to make things appear on screen or go out with a fade effect for example.

Translation

Translation or "movement" basically controls how the object will move on screen on the X and Y axis. 

Scale

Scale pretty much controls the size of the object. You can use it to grow or shrink something on screen.

While you can totally use these separately, they show their real power when used together. The main idea is to mix and match them until you get the desired result. That's when the magic happens.

 

2. How to use them

I told you that there are two ways of implementing animations in Android, declaring them in XML or directly in Java. Here's how to do it:

 

XML way

For this you have to create a new folder called "anim" in your res folder. There you can simply create new XML files. Once you do that you have to simply define the animation. Remember that you can add multiple animations to an XML file, for example combining a translation with an opacity change.

<?xml version="1.0" encoding="utf-8"?>
<set
android:fillAfter="true"
android:fillEnabled="true">

<translate //the type of animation
android:duration="300" //how much time the animation takes
android:fromYDelta="0%"//starting point
android:toYDelta="-150%" />//end point
<alpha
android:duration="300"
android:fromAlpha="1.0"
android:toAlpha="0.1" />
</set>

Also, what fillAfter and fillEnabled does is to preserve the state of the object after the animation, otherwise every time it would finish they would snap back to their original form.

Now that you declared it in XML, simply add this to your Activity:

Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.animation);

Where animation is the variable's name and R.anim.animation is the path to the XML file you've just created.

To trigger the animation on a specific object type:

textView.startAnimation(animation);

Java method

This method is the least preferred one because it takes up a lot more in your Activity and you can only use it once in that specified Activity. Also you have a lot less control over it. 

final ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(200);

textView.startAnimation(animation);

3. The real magic

Now, it's cool to use animations separately to animate a button or a transition, but the best way to do it is to chain them up. There's a really neat function in Android called onAnimationListener, what it does, as all the Listeners in Android is to trigger an action every time an animation starts or ends. Now here's how to make one.

 

anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
//This is going to trigger at the start of your animation
}

@Override
public void onAnimationEnd(Animation animation) {
//This is going to trigger at the end of your animation
}

@Override
public void onAnimationRepeat(Animation animation) {
//This is going to trigger when your animation repeats itself
}
});

4. Experiment

One of the most important tips I can give you for learning animations, and coding in general is to try doing it yourself, experiment, mix and match until you get what you want, or until you learn something new. Try to find you own ways to do it, search for different sources and come up with something new. Don't forget to have fun in the process.

 

*flies away animation*

 

 

5 Tips to make dope Android apps

I've been thinking for a long while to launch a tutorial series on Android apps, and more, but I wanted to get better at it myself before giving out tips to the world. I've been working on Android apps on and off for the past two years and I'm eager to share some tips to make your life easier and get better at making them.

I'm considering that you're using the latest version of Android Studio (seriously you have no reason not to use it) and having an Android phone with android 5.0 or higher.

 

1. Use ADB over network

This goes without saying, if you wanna develop for any platform I totally recommend you getting a phone/tablet that runs that OS. In this case, get a damn Android phone. That's because when you run your apps in an emulator, you don't really get the real feel of using it, it's a very detached experience and your users will suffer in the end. You're probably already using one anyway,

But, to take this tip to the extreme, there's a thing called ADB over network. What it basically does is to let you build and install your apps on your phone instantly without the need for a USB cable, or a dock. Be mindful to only use this only in your local network because it will make your phone a sitting duck for attacks.

The easiest way to activate ADB over network is to have your phone rooted and download an app like "ADB over network" (pretty explicit name huh?), there are hundreds of them on the Play Store. After you activate it, it's going to give you the local IP address of the phone and open a port. 

If you're on a PC open a command prompt and type: 

adb connect 192.168.1.x

And if you're on the Mac side of things open a terminal window and type:

./adb connect 192.168.1.x

Now you're all set and done. If you've done it right Android Studio will automatically have your phone as a target to install the app on.

 

2. Think design first

I know most of you probably are developers here and you have you're ways of thinking this through, but hear me out for a second. Forget everything that you know about programming. Before being an app developer I started out as a designer, I used to make logos and all kinds of cool stuff, and I still do. This gave me an incredible advantage over other developers because my apps not only work great, they look and feel great. Trust me, I'm never going to download your app if it looks bad, no matter what it does, and no other human being with an eye for good looks will either. So you gotta think about how everything in your app ties together, how the user interacts with it, and if it's a pleasurable experience

If you're really bad at this, you should totally follow the Material Design Guidelines from Google, it will set you up in the right direction and give you many important tips. But remember that rules are made to broken, so feel free to come up with your own ideas, just don't make it look like an iOS app or something.

Here are, in my opinion the most important things to look for:

Colors

One way of improving the looks of your app 10x is to use a great color palette. If you're not using a color palette you're doing it wrong. I like to use flatuicolors, but there are many other alternatives such as materialpalette.

Icons

I've seen some horrible looking icons in my life and I hope people will finally stop using them. If you  don't have a designer or illustrator in your team, you have two options: you either make them yourself in Illustrator (they have to be vectors so they won't get all fuzzy and grainy when scaled), or the best and easiest option is to check Google's own collection of icons right here. Not only that they look amazing, but you can also change their color and size at your heart's contempt.    

Motion

Nowadays there's no real excuse not to use animations in your apps, and this topic deserves it's own article in the future. Seriously now, our phones have beefed up processors and 4000 mAh batteries, a little animation here and there won't hurt anyone. I've been struggling myself a lot to learn how to make good animations in Android. The most important thing to remember is to not go overboard with them. Try to use them as much as possible but in subtle ways, the idea is to complement your app and direct people's attention to the right spot, not needing a GTX TITAN to render them.

3. Let someone else give you feedback

When you make an app, you *probably* know everything about it. Your code is like your secret base, you know every single nook and cranny inside of it. While this is a totally good thing, it will give you a biased view on your app. You might think pressing that button three times and swiping left and right to reveal something is ez pz because you did it 100 times to test it. But I assure you someone new won't have a damn idea what to do. So let other people test it, and ask for feedback. Maybe what you thought was easy is really unintuitive and a complete hassle.

If your grandma can use it, you're doing it right. 

 

4. Share your ideas with others

In today's day and age I feel it's counter intuitive not to communicate with other people. Don't be scared that someone is going to steal your work, and don't be shy to steal other people's work. If it was worth stealing from you, it means it's great and you should continue with it. The point is to mix and match, get inspiration from other people's work and share yours. The result of doing this will benefit you as well as everyone else.

 

5. Advertise yourself

This goes hand in hand with the last point, but you can take it to the next level. I see lots of talented developers finding nowhere to work just because they don't know how to sell their craft, they can't advertise themselves and nobody will take them seriously. 

Dedicate the same amount of time that you work on your projects to hustle. Get out there, show your work to the world. The only prerequisite to this is to make some great work in the first place.

 

6. Use the dark theme in Android Studio

I can't stress this enough people, if you're not using the dark theme you're not a real developer.

 

If you follow the steps you'll improve your app game by a long shot, but aside from these tips try to come up with your own style and don't forget to share your own ideas with me, and the community too. 

Make sure to follow me on Facebook and Instagram to keep up with what I'm doing. You'll see some dope content I promise.

 

 

State of wearable tech

 

The last time I wrote any kind of article was in 2013 when I was doing reviews for a tech blog, so here I am on my own website trying to revive my old occupation. 

Smartwatches, wearable tech, the future. This is what we've been hearing for the past 4 years or so, that wearable tech is going to take over the world, smartwatches are going to replace our classic timepieces and in the end even our beloved phones. So where is that future? It's been 4 years of bold promises, big launches and after all, empty words.

 

I'm a smartwatch geek

I'm not saying all this from your usual "wearable hater" that has never seen or used a smartwatch before. Oh no, not at all. I'm actually one of the biggest smartwatch geeks you'll ever meet. I'm that guy that bought the first Galaxy Gear in 2013 and wore it proudly everyday, sometimes taking photos and talking on it (#noregrets). Of course it was bulky, made me look like a 90's nerd and it had really limited functionality, aside from the camera, I actually enjoyed the camera. To demonstrate how much of a geek I was, I rooted my Galaxy Gear, installed full fledged android 4.3 on it used it liked a Neptune Pine type of thing (if anyone remembers that flop). But the novelty quickly faded away. After 2-3 months I used to wear it but I didn't even connect it to the phone, it's purpose was literally just being a digital watch, and sometimes I played 2048 on it and even Flappy Bird.

 

 

Switching gears

Everything changed when the new Android wear was launched, or so I thought, new hardware, new software and a promise for a better future. But what really caught my eye was the Moto 360. When I first saw it online I fell in love with it. I said hey, this is a smartwatch that looks just like a classical timepiece, it's water resistant, charges wirelessly and heck, it has the latest software straight from google, so I don't have to hack my way with it like the Gear. 

So me being me, of course I've bought one as soon as it landed in my country. It was truly amazing, I could wear it with a suit, or casually, nobody ever noticed it and it could still run 2048! Also being able to change the straps on the fly with fancy leather ones or nylon bands was a big breakthrough compared to the static galaxy gear silicone band. What I enjoyed the most about it, and I still do, is the collection of apps and watch faces. I'm a pretty picky person so I always like to have the nicest looking thing on my wrist. I had like 20 different watch faces that I used to interchange depending on time of day, occasion, mood. A dream come true really. Not so fast. Aside from the really slow update roll out, meaning I had to wait for around 3 months to get the newest software from it (this watch charges completely wirelessly so there isn't any real way to connect it to a computer and sideload custom ROMs), the battery was and still continues to be a pretty big issue for me. With it's antique Ti Omap chip inside from 2010 it doesn't really know what efficiency is, so it sips through the whole juice in less than a day. Truth be told, it was always connected to my phone and the screen was set to always on (because hey, what's good to have a watch if you need to press a button to see the time).

 

 

Back to the basics

I used to live with these issues, it's part of the course for being an early adopter after all (i'm pretty used to that and I'll talk about it more in depth in another post) but after a year and a half of wearing the Moto 360 everyday, I finally gave up and got myself a really fancy Orient watch. At first I thought it won't be as useful, or as "fun" as the Moto, but after 3 weeks of using it I'm totally out of the smartwatch game and now I can understand why everybody's doing the same thing. As for aesthetic purposes, the classic watch isn't "much" better looking than the 360 but it sure has it's timeless flair to it, also maybe most importantly, it won't go out of style in 2 years.

 

Nothing changed

The thing that makes me really said as an avid tester of new tech is the fact that the new options from LG and even Huawei aren't so good. I'm not the only saying this but, the Watch Urbane and the Huawei Watch were really amazing looking compared to their bulky and plasticky successors launched at MWC. The only real option right now in my opinion is the Gear S3 from Samsung, which I gotta admit looks really sick and works pretty well. But then again, it's not for everyone.

 

Verdict

Seems like the state of wearable tech is on an slippery slope right now and I really hope it's gonna get better. I'm not in a need for a smartwatch anymore as my classical watch does it's job perfectly, but we need competition and innovation more than ever, especially in this dying segment.

Hope you liked the article, I flexed my writing skills today after so much time and it was really refreshing, expect more of these and maybe even product reviews soon! Also you should check my Instagram page as I'm the most active there posting dope pictures daily.