Category: Coding

  • Android RecyclerView notifyItemChanged() IllegalStateException “Cannot call this method while RecyclerView is computing a layout or scrolling”


    If your Android app is crashing with error IllegalStateException “Cannot call this method while RecyclerView is computing a layout or scrolling”, you may try placing your notifyitemchanged inside a Runnable.

    Assuming you have a call to notifyItemChanged() inside onBindViewHolder() that is making your app crash with IllegalStateException, you may try something like this:

  • Ubuntu: Show current Git branch on Terminal prompt


    There are times when I keep running git status or git branch to check which branch I’m on and I just found that I could do something to show the name of my current Git branch on my Terminal prompt, thanks to a colleague.

    In the following screenshot I’m working in the directory “sample_app”, on Git branch that is named “static-pages”:

    ubuntu-terminal-prompt-git-branch-

    In Ubuntu, here’s how I did it.

    Create .bash directory in Home:
    mkdir ~/.bash

    Go to the new directory
    cd ~/.bash

    Clone the git-aware project from GitHub:
    git clone git://github.com/jimeh/git-aware-prompt.git

    Edit your .bashrc file. I use Vim editor for this:
    vim ~/.bashrc

    Add the following to the top of your .bashrc:

    If you want colored prompts, add the following to the bottom of your .bashrc:

    Otherwise, if you doon’t like colors, use this instead:

    Open a new Terminal tab or restart Terminal. Navigate to any directory that has a Git repository and your Ubuntu’s Terminal prompt should now show the current Git branch’s name.

  • Setup/update Ruby on OS X El Capitan 10.11.5

    I need to learn Ruby on Rails for my new job. I’m a little thrilled about this chance to learn a new language, and I’m trying to get started with it on my Macbook which runs OS X El Capitan 10.11.5. I already have Ruby here, I don’t remember if pre-installed though. It’s out of date and I wanted to upgrade, as this resource Getting Started with Rails recommends version 2.2.2 or higher.

    First step I took was to get RVM (Ruby Version Manager):
    curl -sSL https://get.rvm.io | bash -s stable --ruby

    Then I received this message:

    ” * To start using RVM you need to run source /Users/catzie/.rvm/scripts/rvm
    in all your open shell windows, in rare cases you need to reopen all shell windows.”

    And so I ran:
    source /Users/catzie/.rvm/scripts/rvm

    Then:
    rvm install 2.4

    Which returned this message:

    Already installed ruby-2.4.0.
    To reinstall use:

    rvm reinstall ruby-2.4.0

    Finally, I ran this:
    rvm use 2.4 --default

    My next step was to install SQLite3 on my OS X as per instructions found here on SQLite – Installation.

    I got this message after following the instructions:

    SQLite version 3.17.0 2017-02-13 16:02:40
    Enter “.help” for usage hints.
    Connected to a transient in-memory database.
    Use “.open FILENAME” to reopen on a persistent database.
    sqlite>

    More on this in the future.

    Reference: Can I upgrade to the current version of Ruby (2.2.3) on OS X v10.6.8?

  • Manila homemade cakes, cupcakes, cookies, brownies & more desserts at The Tiny Cakery

    Manila homemade cakes, cupcakes, cookies, brownies & more desserts at The Tiny Cakery

    Update: We have rebranded into Catzie’s Cakery.


    When I’m not busy tapping codes on my keyboard, I either watch anime or bake. And there’s this “tiny” baking business in Manila I’m running, and really have a good time baking for people – friends, family, and even people I haven’t met prior to handing over their ordered desserts.
    Last year I launched the official website: The Tiny Cakery, reaching my goal of completing it before year 2016 ends.

    Visit website: http://thetinycakery.catzie.net/
    Visit website: http://thetinycakery.catzie.net/

    Coding it wasn’t easy to me. It’s mostly front-end coding and the masonry grid layout gave me a lot of problem, and combining it with Slick Carousel did not make things simpler due to some conflict.

    Here’s an Instagram video demo of what it looked like shortly before I launched the site:

    It’s not a high-income business — no, it’s not even a medium-income business. I barely make anything with my The Tiny Cakery income. But I really like what I do there and I like the feeling of fulfilment it provides, so I keep doing it. The time when I needed to upload a price list came due to increased number of price inquiry, and I prepared a one-page website for it last year with a price list being its major component. I knew I had to develop a better website, with product grid including photos that will make people drool (lol), and more informative pages so they know right away how to order.

    I worked on the official website later last year in 2016. I won’t call it a “version 2.0” of the older website because I don’t really consider that “price list website” its “official website”.

    Catzie coding the Tiny Cakery websiteNext step would be a “baking schedule” calendar where customers will see which days I will be baking the goods, and which days are available for booking a pickup on what available locations in Metro Manila. And after this, I want to add an “Add to Cart” feature, initially with manual payments. I believe that even with manual payments, this will make our lives easier. Instead of long chats with customers, they can simply go to the site, select desired products, select date and time of pickup, and then confirm it with me. After that, they confirm orders by downpayment (standard procedure) and then meet up with me on the set schedule.

    Hoping 2017 brings us more freshly baked homemade desserts by The Tiny Cakery, and more convenient ways to order with the help of technology. <3

  • Simple SMS Reader app in Android using BroadcastReceiver class

    Before I began coding Android apps, I was amazed how verification processes go like this: The Android app tells you they’ll send you an SMS containing verification code, and that you need to enter such code into a text field on the Android app. But when you receive the SMS, the verification code appears on the text field before you even type! I was like, whoa, how do they do that?

    Now that I am able to develop simple Android apps, I already have an idea how it’s done.

    We extend a class called BroadcastReceiver and implement its onReceive() method. This receiver is then registered either in the AndroidManifest.xml file, or registered as needed in a .java file (e.g., Activity)

    I’m registering mine in my MainActivity file. I’ll provide the link to my project files on Github later on this page, but for now here’s what it looks like:

    I first created a class called SmsReceiver which extends the BroadcastReceiver class that I mentioned earlier. Inside it, there’s an implemented method onReceive(), where we first check if the Intent’s action is android.provider.Telephony.SMS_RECEIVED, otherwise we do nothing. We read message(s) that the Android devices just received and get the originating address (e.g. phone number of sender) and message body. Then lastly, the TextViews in the XML file are updated with the originating address and message body so you could see that thea app works.

    By the way, I used a Handler in this app so that I could set the values of TextViews inside the MainActivity’s XML file. A new Handler object is passed from MainActivity.onCreate() to the SmsReceiver constructor. And later on once the message originating address and message body are available in BroadcastReceiver.onReceive(), we use the handler to “post” and set the TextView values.

    Now, for the source files of this Android app…

    Feel free to download my Android project files here: Android-Incoming-SMS-Reader

    Resource:
    http://stackoverflow.com/a/14648933

  • Mac OS: How to batch edit file extension via Terminal

    Today I had a directory of images whose file name extensions are .jpeg. I need them as .jpg but I didn’t want to rename them one by one.

    Here’s how we can change the file extensions in a directory by batch. And by the way, I am on Mac OS El Capitan version 10.11.5 with Homebrew package manager.

    First, open your Mac’s Terminal.

    Type the command rename just to check if you have it installed in your system. If the Terminal displays usage instructions on rename then you already have it.

    If rename is a command not found, then install it via Homebrew using this command:

    Once the rename command is available, navigate to the directory where your files that need new extensions are.

    Then edit the following command to suit your needs before running:

    The syntax for this is actually rename "s/OLD_EXTENSION/NEW_EXTENSION/" *.OLD_EXTENSION

    That’s all! I hope that worked for you.

    Resource: Changing extension to multiple files

  • Installing Laravel 5 on Apache in Mac OS X El Capitan

    Last time, I wrote a guide on How to install Laravel 5 in Windows with XAMPP. I’ve been coding more often on Mac computers recently, and now I need to setup Laravel on a MacBook Pro, so I decided I’ll write a guide on how to install Laravel 5 on Mac OS X El Capitan too. 🙂

    First, I’ll assume you already have a local development environment set up on your Mac.

    Environment Requirements

    This guide won’t cover setting up Laravel on Homestead, so let’s make sure our development environment meets the following requirements:

     

    • PHP >= 5.6.4
    • OpenSSL PHP Extension
    • PDO PHP Extension
    • Mbstring PHP Extension
    • Tokenizer PHP Extension

    Install Composer

    See the instructions on the Composer download page on how to install composer.

    After installing, you shall get a file composer.phar in the directory where you ran the installation commands for Composer.

    Make ‘composer’ executable from anywhere

    Right now, if you want to run Composer, you will have to navigate to the folder where you stored composer.phar and run a command like php /usr/local/bin/composer.phar. Let’s make our lives easier by creating an alias, an be able to run Composer simply by typing the composer command. 😉

    Let’s move composer.phar to the path /usr/local/bin by running this command:

    And to finally create the alias, type this command to edit bash_profile:

    Add the following line to your bash_profile:

    Restart terminal or open a new terminal tab. Type composer and this should be able to run Composer.

    Download Laravel via Composer

    Navigate to your document root, (mine is at /webcontent) and run the following command to download and install Laravel into a folder named “laravel5”. Change the folder name as you like.

    Now, I will assume that you have your Laravel at this path: /webcontent/laravel5/

    Verify folder permissions

    Update (2016-10-20): I formed the habit of setting permissions of all my bootstrap/cache/* and storage/* directories to 775 (not 755), which means the owner and group members are granted all rights (read, write, execute). 755 will only grant write access to user, and not group members. The owner of all my Laravel files is my own user (e.g., catzie) and the group owner is _www. My own user and the user called _www are both members of the group _www. Permissions on bootstrap/cache and storage/* is drwxrwxr-x

    The contents of the following directories are required to be writable, otherwise, Laravel will not run:

    • storage
    • bootstrap/cache

    Before I set the directories as writable, when I access my Laravel at http://localhost/laravel5/public, I only get an “Error 500” without any detail. Then after setting proper permissions, my Laravel became accessible.

    We are going to set the permission into 755. Some information about 755:

    Tip: you don’t want to set these folders to 777 because you will make attackers happy when they find out they can write to your files/folders! We want to keep attackers unhappy. 😀

    Set permissions on storage folder

    Let’s navigate to /storage then set the permission of /storage contents to 755 through these commands:

    By the way, the -R in the chmod command affects files and directories recursively. It is equivalent to --recursive. The asterisk * lets the chmod apply the change to all contents of present directory /storage.

    Set permissions on bootstrap/cache folder

    After setting 755 as permission on bootstrap/cache, I still had an error, saying file_put_contents(/webcontent/laravel5/bootstrap/cache/services.php): failed to open stream: Permission denied

    To pass the issue, I ran these commands:

    I don’t know why, but setting it to 755 doesn’t work. When I first set to 777, then reset to 755 though, it works!

    Okay, now I get a different error: file_put_contents(/webcontent/laravel5/storage/framework/views/<someHashedString>.php): failed to open stream: Permission denied

    It seems that my /views folder is not writable. But hey, I already set permissions recursively for contents of storage folder! 🙁

    I decided to try the trick I did earlier with bootstrap/cache, which is first setting to 777 then resetting it into 755:

    First, I set it to 777 then viewed Laravel in my browser. It finally loaded the Laravel home screen. But no, I don’t want to leave the folders under /webcontent/laravel5/storage/ with permission 777 because it can be a security risk. So, I set it back to 755:

    I refreshed my browser and Laravel is still running. Whoohoo! Finally!

    If any of you has an idea why setting to 777 then resetting to 755 works, please let me know through the comments area. 😆

    Update: I realized the right thing to do is chmod all directories under storage with 775 to enable group members to write too. And then, chown the folders from “catzie” to “_www”. Since _www is the user who always needs to write to those folders, just let him own them. :p And here I am hoping that I don’t encounter problems when it’s user “catzie” who’s trying to access those folders and their files.

    Update again: My directories and files are owned by group “staff” but only user “catzie” is member of the group called “staff”. This can be checked by the command id -Gn _www and id -Gn catzie. To add user “_www” to the group staff, I will run the following command:

    This -a(dds) “_www”, which is an object of -t(ype) “user”, to the group “staff”. –source

    Create your first Laravel route

    Now that we are able to load the home/welcome page of Laravel, let’s proceed and create a new route.

    With your favorite text editor, open app/Http/routes.php and add the following code:

    When I visited the URL http://localhost/laravel5/public/ohayou, I got this error:

    When I changed AllowOverride None into AllowOverride All in Apache config file /etc/apache2/httpd.conf, all it did was show me the error file_put_contents(/webcontent/laravel5/bootstrap/cache/services.php): failed to open stream: Permission denied again when accessing http://localhost/laravel5/public/ohayou and even the home page.

    y-u-no

    Y U BRING BACK SAME PROBLEM?!

    Despite being potential security risk, this fixed my problem and allowed me to access the URL http://localhost/laravel5/public/ohayou:

    Err, then I tried to set it back to 755 again…

    And yep, still works! I hope this always works from now on. @_@ lalala~

    Test Laravel with MySQL database

    For us to be ready to develop a web app with Laravel, let’s test one last thing: the connection to database. In this section, we’ll use Artisan to run “migrations”.

    Artisan is the command line interface that’s included in Laravel. And when we run migrations, tables are created based on schemas defined in the migrations in the directory /webcontent/laravel5/database/migrations.

    Create database

    I’ll be using Terminal to check MySQL. If you prefer PhpMyAdmin, that’s okay.

    Create a database named “laravel5”:

    Then select that database:

    You’ll see that there are no tables yet, since we only just created the database without adding any table:

    Change database settings on .env file

    When I finished installing Laravel, a .env file was generated for me. In case your installation only has a .env.example file, copy that into a new file that’s named .env

    Now that you have a .env file, go ahead and edit it and fill in the correct values for your database connection. Do change the value of the following:

    Run migration

    Laravel’s pre-made migration files will create tables for us, such as the “users” table.

    Run this so that the migrations create database tables:

    Oops, I got an error again: PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'The stream or file "/webcontent/laravel5/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied' in /webcontent/laravel5/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:107

    Ohhh, I checked the details about the file laravel.log located at /webcontent/laravel5/storage/logs and this is what I found:

    I believe that laravel.log is generated by Laravel… which means that the user laravel uses is _www and not MY user. But we are at the same “group”. Maybe the right thing to do is simply add “write” permission to “group”.

    Lemme try that with this command…

    And now, this is what my laravel.log looks like:

    Whoa, it worked! retried my php artisan migrate and the command ran successfully. 😀

    Check if tables are created

    Back to the MySQL command line, I’m running these commands to check if tables have been created:

    There you have it! Laravel can connect to your MySQL database. 🙂

    Command reference:

    To create new user and grant it all privileges to an existing database, use this:

    Possible hiccups and solutions/workaround

    No supported encrypter found when running php artisan route:list

    When I run the command php artisan route:list to get a list of my Laravel routes, I got the error:

    To fix this, make sure you have a .env file in your Laravel root directory. If you don’t, copy and rename from .env.example then edit the values as needed.

    Then, run this on your Terminal: php artisan key:generate which should generate and save a key on your .env file.

    If that still doesn’t work, maybe it has something to do with the cipher you are using. Edit config/app.php and set the value of cipher to 'AES-256-CBC' so that you have 'cipher' => 'AES-256-CBC',

    Now try to run php artisan route:list again.

    Explanation:

    For Laravel 5.1, if the .env file does not exist, duplicate the .env.example file, rename it to .env, then run php artisan key:generate (as opposed to hardcoding a default in the config/app.php file).
    The artisan command should update the APP_KEY in the .env file with a 32 character string to match the length expected by the ‘cipher’ => ‘AES-256-CBC’ (in the config/app.php file).
    Source: No supported encrypter found. The cipher and / or key length are invalid.

    PDOException when running php artisan migrate

    I wanted to run php artisan migrate in Laravel to generate by database tables but I was getting this error:

    What fixed this issue for me was changing DB_HOST value in .env from ‘localhost’ to ‘127.0.0.1’. This is a known issue in my Mac. I need to use 127.0.0.1 in web app settings to use the database. Hope I find time to fix it 😆

    Reference(s):
    Add a user to the admin group via command line
    Setting folders as writable in Unix systems
    Installing Composer on OS X
    CHMOD settings
    Making some Laravel folders writable

  • Add “options menu” to an AppCompatActivity (Android App Development)


    Adding an “options menu” to an Android app’s Activity is quite simple.

    This is an example of what an Android options menu looks like. Look at the icon that looks like 3 dots vertically stacked.

    android options menu

    My dev environment status as of writing this

    Android Studio version: v. 2.1
    OS: Mac OS X El Capitan v. 10.11
    My Android app build status:

    • compileSdkVersion: 24
    • buildToolsVersion: 24.0.2
    • minSdkVersion: 16
    • targetSdkVersion: 24

    Add “options menu” to an Android AppCompatActivity

    #1 Create menu layout file

    Create res/menu/main.xml, creating the menu folder if not yet existing.

    Add the following to res/menu/main.xml:

    #2 Enable menu by adding MenuInflater to the Activity

    Add the following overriding method to your AppCompatActivity:

    #3 Add listener for selected options menu item

    Again, add the following overriding method to your AppCompatActivity. Replace the Toasts with whatever you need to do upon menu item selection:

    That’s it! Your Android Activity should now have an options menu on the actionbar

    My resources for adding my options menu to Activity

    Adding the App Bar
    Android SDK: Implement an Options Menu

  • Java: method to convert degrees into directions (16-wind compass rose)

    I’m working on a weather app for Android. The data for wind direction that I get from the weather API is in form of degrees (0 to 360). I want to display wind direction in a user-friendly format such as N (North), NNE (North-northeast), NE (Northeast), ENE (East-Northeast), E (East), ESE (East-Southeast), SE (Southeast), SSE (South-Southeast), S (South), SSW (South-Southwest), SW (Southwest), WSW (West-Southwest), W (West), WNW (West-Northwest), NW (Northwest), and NNW (North-Northwest). I think this is more user-friendly, at least when compared to degrees format.

    16-wind compass rose
    The eight half-winds are the points obtained by bisecting the angles between the principal winds. The half-winds are north-northeast (NNE), east-northeast (ENE), east-southeast (ESE), south-southeast (SSE), south-southwest (SSW), west-southwest (WSW), west-northwest (WNW) and north-northwest (NNW). Notice that the name is constructed simply by combining the names of the principal winds to either side, with the cardinal wind coming first, the ordinal wind second. The eight principal winds and the eight half-winds together yield a 16-wind compass rose, with each compass point at a 22 1⁄2° angle from the next.

    Points of the Compass

    And here is the Java method that I prepared so I can convert direction data from degrees into directions (16-wind compass rose):

  • Android app development: click a ListView item programmatically


    I’m going to share a code snippet that you may use to programmatically click a ListView item in your Android app. This will not simply highlight the desired ListView item, but also trigger the onItemClick listener.

    This code is what I placed in a Fragment’s onLoadFinished() method:


    Simply replace the default_position value with the index number of the ListView item you want to click/select programmatically.

    That item should be highlighted (assuming you have like, touch selectors) and also trigger the onItemClick listener on Android.


    A possible error is . If this happens, wrap your code around a Runnable(), like this: