Dart: sqljocky example

This time we want to get the data from the database directly. We will use the sqljocky package to do this. First of all we create a new console dart application. After that we need to get the package from the pub.

  1. Create a pubspec.yaml file in the project and add the following text:
     name: my_app
     dependencies:
      web_ui: any
  2. Rightclick on the pubspec.yaml file and choose Tools > Pub Install.
    Screen Shot 2013-01-27 at 12.44.10
  3. Now you can see a new package in the packages folder:
    Screen Shot 2013-01-27 at 12.50.26

In the .dart file we now need to add the import to the package:

import 'package:sqljocky/sqljocky.dart';

Now we can access this package. The following code is doing the whole action:

void main() {
 var con = new ConnectionPool(host: 'localhost', port: 3306, user: 'root', password: null, db: 'mymusic', max: 5);
 con.query('select albumName, interpret from cd').then((result)
 {
  var row;
  for (row in result) {
  print('album: ${row[0]} (${row[1]})');
 }
}
);
}

The code is real simple. The library is really doing a lot for us. To read from the result of the select-statement we can use a simple foreach snippet:

var row;
for (row in result) {
 print('album: ${row[0]} (${row[1]})');
}

The output in the console looks like that:

Screen Shot 2013-01-27 at 13.10.04

This are the things I really love about dart. Just a few easy lines of code for a great result.

Android CardsUILib

I recently searched for a Google Now Card library and I found CardsUILib. But I wanted a card with a picture, so I can use it in my quiz app. So I edited the whole library a bit and the result is that:

It’s a great library with a lot of potential. I did a pull request for a picture card. You can find the library here: https://github.com/nadavfima/cardsui-for-android/tree/master/CardsUILib

The edit was real easy, I created a new XML-File:

...

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/selectable_background_cardbank"
android:gravity="center_vertical"
android:padding="8dp" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="154dp"
android:layout_height="127dp"
android:adjustViewBounds="true"
android:baselineAlignBottom="true"
android:scaleType="centerCrop"
android:src="@drawable/url1" />

<TextView
android:id="@+id/description"
style="@style/CardText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="8dp"
android:ellipsize="end"
android:maxLines="7"
android:text="text text" />

...

And the Java class looked like that:


public class MyImageCard extends Card {

public MyImageCard(String title, int image){
 super(title, image);
}

@Override
public View getCardContent(Context context) {
 View view = LayoutInflater.from(context).inflate(R.layout.card_picture, null);
 ((TextView) view.findViewById(R.id.title)).setText(title);
 ((ImageView) view.findViewById(R.id.imageView1)).setImageResource(image);

return view;
}
}

As you see, the changes I made were real simple as you saw. But there were more in the library code. There I just added an Integer for the DrawableRessource.

Dart: Parse JSON to object

As we saw in the first post: http://www.signer.pro/lets-meet-dart/ its real easy to work with Dart. We want to parse the JSON-Objects, that you can get here(http://api.signer.pro/client.php?action=getCds) to Dart-Objects. First of all we will write a normal console application and after that a web application where we display the data a bit nicer.

Dart Console Application

First of all we create a cd-class with all the information we need:

class Cd {
  num id;
  String album;
  String interpret;

 Cd(num id, String album, String interpret){
  this.id = id;
  this.album = album;
  this.interpret = interpret;
 }

 Cd.fromJson(Map json){
  id = json['id'];
  album= json['album'];
  interpret = json['interpret'];
 }
}

Some of the relevant data types in our example are num and String. There is also bool, but we don’t need that one in the example.

So after we wrote the Dart-Object, let’s work with the main-method:

void main() {
List<Cd> listOfCds = new List<Cd>();
var httpClient = new HttpClient();
var conn = httpClient.getUrl(new Uri('http://api.signer.pro/client.php?action=getCds'));
conn.onResponse = (HttpClientResponse resp) {
var input = resp.inputStream;
input.onData = () {
var data = input.read();
var text = new String.fromCharCodes(data);
List l = JSON.parse(text);
l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});
listOfCds.forEach((cd) {
print("album = ${cd.album} interpret = ${cd.interpret}");
});
};
input.onClosed = () => httpClient.shutdown();
};
}

We created a httpClient with the URL to the API. Then we get the response and get the text with the following command:

var text = new String.fromCharCodes(data);

Then we parse the JSON-text into a List. Because we’ve got a JSON-Array with some JSON-Objects. And now something that I love the most of the Dart-Language:

l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});

This way, we can simply loop through a list and do something with the objects. In this case we map the value with the key ‘id’ or ‘album’ and create a Cd-Object with it. After that we add it to a list of Cd’s we defined earlier.

pp1

So, as wee see this is working pretty well. And now we do almost the some for a small web application.

Dart Web Application

As in the console application we define a CD-Object. After that we use the following code in the main-method:

void main() {
List<Cd> listOfCds = new List<Cd>();
ParagraphElement p = new ParagraphElement();
p.text = "loading..";
query("#container").append(p);
var request = new HttpRequest.get('http://api.signer.pro/client.php?action=getCds', (req) {
var text = req.responseText;
List l = JSON.parse(text);
l.forEach((map){
Cd c = new Cd(int.parse(map['id']), map['album'], map['interpret']);
listOfCds.add(c);
});
UListElement ule = new UListElement();
listOfCds.forEach((cd) {
LIElement lie = new LIElement();
lie.text = "${cd.album} (${cd.interpret})";
ule.children.add(lie);
});
p.remove();
query("#container").append(ule);
});
}

We needed to modify the code a bit, so it matches the the  ‘dart:html’ library. But the rest of the code is very similar to the code in the first example above. The HTML looks like that:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ConnectAPI</title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet"></link>
</head>
<body>
<h1>ConnectAPI</h1>
<div class="span12" id="container">
</div>
<script type="application/dart" src="ConnectAPI.dart"></script>
<script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
</body>
</html>

As you see, I’m using bootstrap again for the website. So the result in the browser looks like that:

pp2

Let’s meet Dart

dart

It’s a long time ago, I first heard something about Dart. It’s the Google answer for JavaScript. You can download it over here: http://www.dartlang.org/downloads.html

When you create a new project you’ll get a .css, .dart and a .html file. We want to do a simple counter, so when you click on it, this value will increase.

We start with the HTML-File. This contains a basic website structure. I would use bootstrap for early development, but at the moment we don’t need it.

<!DOCTYPE html>
 <html>
 <head>
 <meta charset="utf-8">
 <title>HelloWorld</title>
 <link rel="stylesheet" href="HelloWorld.css">
 </head>
 <body>
 <h1>HelloWorld</h1>
 <p>Hello world from Dart!</p>
 <script type="application/dart" src="HelloWorld.dart"></script>
 <script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
 </body>
 </html>

New we add a new add a new parameter tag with a uniq id below the “Hello world from Dart”-thing.

<p id="counter"></p>

The next step is the CSS-File so we can fully concentrate about dart-source-code  later. Remove everything except the body and p part and then add the following one for the counter:[/html]

#counter {
 font-size: 24pt;
 text-align: center;
 margin-top: 140px;
 }

Now we can go to the .dart-File. You can remove almost everything, but keep the

import 'dart:html';
void main() {
}

We start with the following code:

void main() {
 query("#counter")
 ..text = "0"
 ..on.click.add(countOneUp);
 }

This is simply setting the text of our HTML-element, with the id ‘counter’, and adding an OnClickEvent. This is very similar to Java, not the syntax, but the structure how you work with it. So now we need to create the OnClickEvent.

void countOneUp(Event event) {
 var tempCount = query("#counter").text;
 int i = int.parse(tempCount);
 i++;
 query("#counter").text = i.toString();
 }

If you know how Java-Syntax is working, this code isn’t hard to understand. But I think the query-command is quite confusing if you us it the first few times. As you see, I did a lot of filetype-parsing.

To run the application simply hit Ctrl + R (I don’t know how this is on Mac ^^). A modified version of chromium is now starting and will run the application. It should look like this now:

You can find the examples here: http://dart.signer.pro/.

As you see, Dart can be pretty nice. But I haven’t done much more at the moment. If I know more, I’ll let you know.

DinPattern – super free patterns