Wednesday, May 27, 2015

How to Connect to a PHP Server on Android

For my current project, I spent a good amount of time surfing the web searching for how to do this until a friend helped me out. So now it's time to share this with you.
First create a PHP file, let's say with the following contents:
$q = filter_input(INPUT_POST,"q");
if($q == "SAY_HELLO"){
    echo "Hello World";
}else{
    echo "No Command Given";
}

Now let's take a look at the java code. First open Android Studio and start a new project. In order to retrieve data from the internet you need to create a child class of AsyncTask. When extending AsyncTask you must specify three parameters < Params, Progress, Result > and define the method doInBackground(Params...params). Params is what is taken when the task is started. Progress is what is what is passed into the onProgressUpdate(Progress...values) method. This method is used to decide what should happen when there's an update in the progress of the task (I won't be going into that here). Result is the value returned from the task. Seeing as we just want to receive a response there isn't much need for the Progress. We can then define our class as so:
public class Request extends AsyncTask{
    ....
}

The next thing we need to do is implement the doInBackground(Params...params) method. In order to connect to the server we'll need to use an HttpURLConnection and pass in the url to the php file we created.
@Override
protected Object doInBackground(String...params){
    URL url = new URL(params[0]); //the url to the php file will be passed in as a parameter
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    ....
}

We'll next need to allow the urlConnection upload a request body, specify the request method, as well as the content type:
@Override
protected Object doInBackground(String...params) throws Exception{
    ....
    urlConnection.setDoOutput(true); //Allow the urlConnection to send requests
    urlConnection.setRequestMethod("POST"); //Set the request method to POST
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    ....
}

Next comes making the actual query. We'll have the query parameter be passed into the method:
@Override
protected Object doInBackground(String...params) throws Exception{
    ....
    String query = "q="+params[1];
    urlConnection.setFixedLengthStreamingMode(query.getBytes().length); //set the amount of data to be sent to the server
    urlConnection.setConnectTimeout(2000); //how long to wait for a response in milliseconds
    ....
}

Almost done! Now we just need to output the data and read the response:
@Override
protected Object doInBackground(String...params) throws Exception{
    ....
    DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
    out.writeBytes(query); //send the query to the server
    out.flush(); //make sure that the query was sent
    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
    String inputLine = in.readLine();
    in.close(); //close the connection
    out.close();
    return inputLine;
}

Great! Now, in our Android Studio project open the MainActivity.java file and in the onCreate(Bundle) method put this:
Request req = new Request();
req.execute("http://www.example.com/hello.php","SAY_HELLO"); //start the request with the url and query paramater
String res = req.get(); //wait for the request to finish and get the result
((TextView)findViewById(R.id.textView)).setText(res);//display the result in a textview
If your layout.xml file is similar to the one below:


    

You should see "Hello World" in a text area on your phone or simulator.

Tuesday, April 21, 2015

3 Resources That Will Help Improve Your Coding Skills

Over the past few years, when searching for a good online resource for programming most I came across were like Code.org. The problem with Code.org was that it only provided tutorials for beginners whereas I considered myself an intermediate programmer and wanted to dive deeper into the world of algorithms, data structures and design. Resources such as the one Oracle provides with their Java Tutorials has always been useful but constantly creating new files for each section I read became tedious. My Java folder became a mess. 
Then, on one fateful day I found it: a website that challenged my abilities as a programmer. A website that helped me learn and get better. Then I found another. And another. 
And now, I'm sharing them with you.


1. Codewars

Codewars provides a way for you to develop your programming skills through their various "katas" which are basically programming challenges. These challenges range from data structures to encryption.  Each time you complete a kata you earn "honor points". After getting a certain amount of points you go up a rank and this continues to the Master 8 Dan rank. Each kata is also ranked, so the more difficult the kata you complete the higher in the ranks you rise. 

When completing a kata there are a variety of languages that you can use. Currently they have support for Java, Javascript, Coffeescript, Ruby, Haskell, C#, Closure, and Python—but are planning to add many more. 

2. Code Fights

Code Fights has provided a way for you to fight other programmers in a race against the clock to complete a challenge. Though, the challenges aren't necessarily what you'd think they'd be; when engaging in combat you'd expect to start from scratch, but instead they provide the code for you. Unfortunately, the code isn't correct—there's a mistake that you need to fix. That mistake is located on only one line of code, and you have a short amount of time to fix it. Think you can do it?
There is a greater amount of depth to this website that would deserve it's own blog post. But, in the spirit of keeping things short and sweet, I'll only mention a few.

Just like in Codewars you gain experience points and increase in rank. What is really exciting about this are the tournaments that are held regularly. It gives you a great sense of accomplishment after you crush your competition and receive the gold.

3. Hacker Rank

Hacker Rank is absolutely amazing. With many languages under it's belt (including the infamous language Brainfuck) Hacker Rank will train you in various domains ranging from functional programming to artificial intelligence. There are a series of challenges (almost too many) for you to complete and just as in the other sites I've mentioned, there's a levelling system to help motivate you.
There is something that I haven't tried on the website though: competitions. With sponsorships from companies Hacker Rank holds competitions that give away (as their FAQ says) big prizes! There isn't much else to say about this website, I suppose that's a good thing. It's not complicated at all; it's simple and straight-forward. That's why it's my favourite of the three.

I'm sure that Codewars, Code Fights and Hacker Rank are just a few of the many sites like them and I can't wait to find some more. If you have any programming resources that you like to use, mention them in the comments below.
Happy Hacking. 

Saturday, April 4, 2015

Shameless Greed from a Video Game Giant

Super Mario 64 HD
When I was younger the first major console that I got was a Nintendo 64. Mario Kart, Super Smash Bros, even Hey You Pikachu—I had (still have) them all. Nintendo started to die down in hype though, Sony and Microsoft were becoming far more mainstream in gaming and even though I've always been using Sony consoles (PS2,PS3,PSP-3000,PSP GO) I only recently hopped onto the XBox train with a purchase of the XBox 360 Kinect back in 2012. But, I've always had a thing for Nintendo. Perhaps it was the nostalgic feeling of playing the Megaman Battle Network series on my GameBoy or just not wanting to try something new. Either way, I loved Nintendo. I loved the characters. I loved the company. That is, until recently.

A few days ago I found this awesome little demo someone made to show off their Super Character Controller script that they created for Unity3D: Super Mario 64 HD. It featured the famous Bo-bomb Battlefield and showed off what was possible with the hard work of the creator. I was one of the lucky few who actually downloaded the game before Nintendo took it down.
On his site the creator says, "I didn’t really expect for this project to get so popular, and was hoping it would function primarily as a educational tool and a novelty.". He didn't plan on monetizing or even completing it but Nintendo saw it as a threat. After having released their Virtual Console on the Wii U they didn't want any clones around. They took it down. People Noticed. Polygon noticed. I noticed.
Screenshot Provided By IGN

I wasn't going to write anything. I was going to look the other way like a lot of people have been doing. Then, scrolling through my Facebook feed, I came across this. Big Angry Joe, a Youtuber with over a million subscribers, had his video flagged by Nintendo due to the fact that he was Let's Play-ing one of their games, Mario Party 10, which came out a few weeks ago. Angry Joe then posted a video, talking about how wronged he felt. Then I remember, how a long time ago, I had turned a blind eye to something Nintendo had recently started doing: charging Let's Play-ers. Nintendo started to take a 40% cut in advertising revenue that the Let's Play-ers make via their videos.This is something that no other company, to my knowledge, has done and hopefully will never do.

I have a Wii U in my basement, and I play Super Smash Bros. on it every time I visit home from school. We bought the console, we bought the games, some have bought the accessories. Still not enough. They want more and they're willing to step on creators like Big Angry Joe to do it. They make great games (though they don't have a great variety), but they have too many scandals around them involving greed. I just wish Nintendo would start being the company that I thought it was as a kid.


Saturday, March 28, 2015

Hey, What Happened to the Bridge?

Imagine this. You're taking a drive down to your friends house and you see there's a bridge that could take you directly to their neighbourhood. You ignore the GPS, which does not recognize it as a legal road, and turn right. You smile. You look up ahead to see the road slowly disappear, piece by piece. You slow to a stop, your smile fades, you look around for signs saying the bridge is unfinished. You could have missed them (you've been driving for a long time so you might be tired). Nope, there isn't one. There never was one. There never will be one. That bridge was started years ago, and hasn't been touched since.

That's how I see unfinished work: a bridge that's supposed to serve some sort of purpose, but after all that hard work and getting people's hopes up, is forgotten because something better and perhaps easier came along. A Twitch game developer would stream everyday and I'd watch him code and create this amazing rpg with a 2D art style that I loved. I come back one day to find him on another project. He said he didn't know when he would get back to the one that made me follow him in the first place. I left the stream—his work no longer inspired me (recently he's started working on the original game again).
Friends of mine come up with ideas for apps that could "change the world". One got me really excited, I told them what we'd have to do and I prepared to invest some time in it. The following week they came up with another idea. I grew irritated, and ignored them as they talked about it. They thought of a new idea every couple weeks, but none were as good as the first. They lost faith in the idea they had before (one I am kind of still hung up on).

image from Commit Strip
I'm not saying that I never used to be that way. I was. If you could see all of the unfinished games that I had developed or incomplete books I wrote as a kid you would be calling me a hypocrite. Notice I said "kid" though—I was 12 and impatient. Since then I've learned to devote myself to something when I say I am going to be devoted to it. For the past while I've been working on a project that started in January, I told myself it would be online by the beginning of February, but other things have gotten in the way of me meeting each deadline. I've decided to start making smaller goals for the project, that way I still feel motivated to do it often. That way I won't risk driving people off of bridges.

Saturday, March 7, 2015

Wow Dude, that's so Mainstream

Scarf, beanie, furrowed eyebrows and sunglasses peering down at the screen of a macbook. Fingers typing away on the black keys, face illuminated by the words they write. Ladies and gentleman, I present to you, the typical Hipster. I first heard this phrase a few years ago, when I was in the tenth grade and didn't really understand it. Hipster. What in the world is a hipster? The context that I heard it was during a conversation between a couple of my friends. They were talking about different music groups and one of them said that the other "was just too much of a hipster to listen to that music". The friend agreed, saying that it was "too mainstream".
Now, the inspiration behind this blog is that I've finally decided to give it a try. I'm going to be, different by working with the hipster stereotype (which makes no sense to me). Yes, I am now sitting inside a café with a cup of coffee, a scarf, sunglasses, beanie, all of the above.
Okay, in truth I forgot all of those in my room. My scarf is lying on my desk chair; it's the middle of winter and I'd get odd looks for wearing sunglasses outside (and I'm wearing contacts so glasses don't work); my eyebrows aren't furrowed, relaxed and normal really; I don't own a beanie—but I am using a macbook. I know it's not much but at least it's something, right? The fact that I actually took a walk off campus to the café across the street is amazing to me (yes, I can be that lazy). Also, I don't think I have my chocolate croissant and hot chocolate in the right place (I know it's supposed to be coffee but, come on, it's chocolate).
Baby steps my friends, baby steps.

Saturday, February 28, 2015

I Want to Steal your Skin, and You Want Mine

image from Galaxyguy111
Lately the internet has been abuzz with the whole "yellow and gold" or "blue and black" debate (it's proven to be blue and black here at Computerphile and at Wired Magazine). This whole thing, the constant arguments with friends and classmates over this silly topic, got me thinking about how others might see the world.
Though not professional (yet), as a writer I have to look from the point of view of many other characters: from a homeless man on the street to a love struck teen to a patient with terminal cancer. Sure, sometimes research is needed because one's imagination can only do so much. But no matter what, you need to try and understand something from another human's perspective.
It's a difficult thing to do though. Even when you're developing a character, there might be something that's just a little bit off that makes them "inhuman". Someone who has been raped would not generally react to any form of touching in the same way as a flirtatious bachelor(ette).  Someone who has experienced a selfish world would not view life in the way of an altruist. I could go on but I think I've made my point.
I don't think it's possible to perfectly see something from another (real life) person's perspective. As Atticus tells his daughter Scout in How To Kill A Mockingbird
You never really understand a person until you consider things from his point of view . . . until you climb into his skin and walk around in it.
Only after seeing how people treat that one person, only after knowing all of their life's experiences, do you know why that person is the way they are. It's something that I constantly remind myself when I feel a conflict arising between me and another party. I need to take a breath, and ask myself why the person said what they said. Why they did what they did. And if I am unable to guess, I ask them. I might have said something that they misheard, or I might have misinterpreted them. I'm not a big fan of conflict.
So, I don't know if you see the dress as yellow and gold, or as blue and black, or neither. Either way, we're all human: complex creatures with emotions that can often rise and control our actions. We all have our own story, I don't know yours, you don't know mine, and I'm happy about that.
It makes me feel unique. Special.

Saturday, February 21, 2015

Altonito and the Hidden Writer in You

A couple of weeks ago I received a beta invite to a site known as Altonito. Well, I decided to just dive in and see what this website had to show.


My first thought after logging in was "Okay, this looks pretty cool" and I quickly grew excited to try this new product. I took a look at what others had already written, articles on CSGO and a few lifestyle articles as well. Finally, I was ready to create something. I clicked on Write and was greeted with a screen describing the main service that Altonito was providing.

"It doesn't matter, if there is a writer hidden in you, or if you are a professional writer. We believe that interesting content resides within passionate people. So if you are passionate about a topic and have an interest in writing, Altonito is for you." 
As expected my eyes drifted towards the little dollar bill at the bottom of the screen: "Monetize your content coming soon".  I hadn't expected that. I would actually, in the future, be able to make money off of my stories. Now that is pretty cool.
I scrolled down and searched for a get-started button. To my dismay, there was none, but instead requests for access to my social media profiles as proof of identity. I was hesitant. The only thing that I was remotely comfortable giving was my Twitter, so, I signed in. Or I at least attempted to. Upon allowing access Twitter told me that I was already signed into the service and I was unable to write. Confused, I went to my Twitter account, removed the app, and tried again.
I repeated this process a few times until I threw up my hands in surrender and signed-in to my Facebook. That was probably the biggest upset on my first day using the service.



I sat in my chair, staring at my computer screen wondering what I should write. I already have this blog, so I couldn't write an article. I decided to write a short story which I entitled Chaser (which I'll update every Tuesday). I hit publish, and sent it out to the world to read.

Other than the social media authentication process, Altonito has proven to be pretty cool. Though, in the future, I think it would be nice for the platform to have a greater social aspect to it. Such as the ability to collaborate with writers and perhaps instant messaging between mutual followers. Overall Altonito seems extremely promising, and I can't wait to see what it will become in the future.