Indie Graphics Builder #2 (Create Sprites for Your Game)

Kickstarter project i am suporting, if you are developing a game and you are in need of same graphic sets this is what you need!Kickstarter_logo1

Ready to develop your game?  My friends and I bring you the “The Indie Graphics Builder.”  For way less then the price you’d pay an artist to make graphics for your game, with IGB, you can create: Animations, characters, spaceships, maps, platforms, puzzles, icons, menu’s, by yourself.

The list goes on and on.  In fact, it goes on as long as you want it to.  The more our kickstarter funding, the more weeks, months, and years we’ll be making graphics for you.

With a little effort you can make your assets different then other people.  A lot of what we make will be in pieces.  So you can construct, change, and make unique your own graphic creations.

 

ListView with checkboxes inside

This example will show howto use checkboxes inside a ListView.

First we will create the activity which contain the listview. It extends ListActivity so we only need to set the main layout and create the adapter for the ListView.

public class CheckboxListActivity extends ListActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_checkbox);

		CheckboxListAdapter adapter = new CheckboxListAdapter(
				getLayoutInflater());

		getListView().setAdapter(adapter);
	}
}

This is the layout file for the activity. It only contains the ListView.




    
    

This is the layout for every element which will be created inside the adapter for every row in the list. It contains a Textview and our CheckBox. Nothing special here.




    

    

The class SampleData will be used as container for a name and the state of the CheckBox.

public class SampleData {

	private String name;

	private boolean selected;

	public SampleData(String name, boolean selected) {
		super();
		this.name = name;
		this.selected = selected;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean isSelected() {
		return selected;
	}

	public void setSelected(boolean selected) {
		this.selected = selected;
	}

}

The class CheckboxListAdapter contains the code to create the view containing a text and the CheckBox for every row in the list. The layoutinflator is used to inflate element_example which we have created before. The class is implementing OnClickListener to be able to serve as listener for the checkbox clicks.

The information from SampleData will be assigned to the TextView and the Checkbox. The SampleData object is tagged to the Checkbox so it can be retrieved in the onClick function to change the state of “selected”

public class CheckboxListAdapter extends BaseAdapter implements OnClickListener {

	/** The inflator used to inflate the XML layout */
	private LayoutInflater inflator;

	/** A list containing some sample data to show. */
	private List dataList;

	public CheckboxListAdapter(LayoutInflater inflator) {
		super();
		this.inflator = inflator;

		dataList = new ArrayList();

		dataList.add(new SampleData("Peter", false));
		dataList.add(new SampleData("Bob", false));
		dataList.add(new SampleData("Sara", true));
		dataList.add(new SampleData("Mitch", false));
		dataList.add(new SampleData("Tracy", false));
		dataList.add(new SampleData("Joe", false));
		dataList.add(new SampleData("George", false));
		dataList.add(new SampleData("Nancy", false));
		dataList.add(new SampleData("Susi", true));
		dataList.add(new SampleData("Homer", false));
		dataList.add(new SampleData("Lisa", false));
		dataList.add(new SampleData("Jack", false));
	}

	@Override
	public int getCount() {
		return dataList.size();
	}

	@Override
	public Object getItem(int position) {
		return dataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View view, ViewGroup viewGroup) {

		// We only create the view if its needed
		if (view == null) {
			view = inflator.inflate(R.layout.element_example, null);

			// Set the click listener for the checkbox
			view.findViewById(R.id.checkBox1).setOnClickListener(this);
		}

		SampleData data = (SampleData) getItem(position);

		// Set the example text and the state of the checkbox
		CheckBox cb = (CheckBox) view.findViewById(R.id.checkBox1);
		cb.setChecked(data.isSelected());
		// We tag the data object to retrieve it on the click listener.
		cb.setTag(data);

		TextView tv = (TextView) view.findViewById(R.id.textView1);
		tv.setText(data.getName());

		return view;
	}

	@Override
	/** Will be called when a checkbox has been clicked. */
	public void onClick(View view) {
		SampleData data = (SampleData) view.getTag();
		data.setSelected(((CheckBox) view).isChecked());
	}

The full example can be get at github

Autoclose dialog after some time

Example of an dialog in android using the class DialogFragment which will close itself after aproximate three seconds. Basicly is just a DialogFragment which starts a thread when it is shown which will sleep for the three seconds and then close the dialog again.

public class AutocloseDialog extends DialogFragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.autoclose, container);
		getDialog().setTitle("Hello");

		return view;
	}

	@Override
	public void show(FragmentManager manager, String tag) {
		Log.i("sample_autoclosedialog", "showing dialog");
		new CloseThread(this).start();
		super.show(manager, tag);
	}

	@Override
	public int show(FragmentTransaction transaction, String tag) {
		Log.i("sample_autoclosedialog", "showing dialog");
		new CloseThread(this).start();
		return super.show(transaction, tag);
	}

	class CloseThread extends Thread {

		private AutocloseDialog dialog;

		public CloseThread(AutocloseDialog dialog) {
			super();
			this.dialog = dialog;
		}

		@Override
		public void run() {
			try {
				sleep(3000);
				dialog.dismiss();
				Log.i("sample_autoclosedialog", "dialog dismissed");
			} catch (InterruptedException e) {
				Log.e("sample_autoclosedialog", "exception", e);
			}
		}

	}
}

You can get the full example project at github.

AsyncTask for Image download

If you have an ImageView which will has to display an image which has to be downloaded first it is best practise to download the image in a seperate Task.

The following AsyncTask will download an image from an given URL and assign it to a existing ImageView.


package com.example;

import java.io.InputStream;
import java.lang.ref.WeakReference;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

/**
 * AsyncTask to download an image from an URL and attach it to an ImageView.
 * 
 * @author Gerrit Schimpf
 * 
 */
public class ImageDownloadTask extends AsyncTask {

	/** The url from where to download the image. */
	private String url;

	/** Reference to the view which should receive the image */
	private final WeakReference imageRef;

	/**
	 * Constructor.
	 * 
	 * @param imageView
	 *            The ImageView which will receive the image.
	 */
	public ImageDownloadTask(ImageView imageView) {
		imageRef = new WeakReference(imageView);
	}

	/**
	 * This function will be executed to download the image in a background
	 * process.
	 * 
	 */
	@Override
	protected Bitmap doInBackground(String... params) {
		try {
			InputStream in = new java.net.URL(url).openStream();
			Bitmap bitmap = BitmapFactory.decodeStream(in);
			return bitmap;
		} catch (Exception e) {
			Log.e("ImageDownload", e.getMessage());
		}
		return null;
	}

	/**
	 * This function will be called after the image download and attaches
	 * the bitmap to the ImageView.
	 * 
	 */
	@Override
	protected void onPostExecute(Bitmap bitmap) {
		if (isCancelled()) {
			bitmap = null;
		}

		if (imageRef != null) {
			ImageView imageView = imageRef.get();
			if (imageView != null) {
				imageView.setImageBitmap(bitmap);
			}
		}
	}

}

Kill running process

Howto kill a process in Mysql

If you have a “hanging” process in MySQL and want to kill it, you use show processlist to identify the process you want to kill get get the id. Then a simple kill ID will do the job.

mysql> show processlist;

+-----+------+-----------+---------+---------+-------+-------+------------------+
| Id  | User | Host      | db      | Command | Time  | State | Info             |
+-----+------+-----------+---------+---------+-------+-------+------------------+
| 882 | user | localhost | test    | Sleep   | 27111 |       | NULL             |
| 893 | user | localhost | test    | Sleep   |   453 |       | NULL             |
| 901 | user | localhost | NULL    | Query   |     0 | NULL  | show processlist |
+-----+------+-----------+---------+---------+-------+-------+------------------+
3 rows in set (0.00 sec)

mysql> kill 882

The same can be done using mysqladmin form the command line:

    [root@host]# mysqladmin processlist
    +-----+------+-----------+---------+---------+------+-------+------------------+
    | Id  | User | Host      | db      | Command | Time | State | Info             |
    +-----+------+-----------+---------+---------+------+-------+------------------+
    | 882 | prog | localhost | test    | Sleep   | 2676 |       |                  |
    | 893 | prog | localhost |         | Sleep   | 1823 |       |                  |
    | 903 | root | localhost |         | Query   | 0    |       | show processlist |
    +-----+------+-----------+---------+---------+------+-------+------------------+
    [root@host]#

    [root@host]# mysqladmin kill 882

Link to the MySQL documentation

KILL Syntax
SHOW PROCESSLIST Syntax

Compare two MySQL databases

If you need to compare the structure or maybe even the content of two MySQL databases you will need a tool which will help you with this not too straight task. Here is an overview of some application which will help you succeeding the work.

Percona Toolkit 
Has several database comparison and syncing tools among other things.

Liquibase
Open source library for tracking, managing and applying database changes.

Toad
Can do both a “Schema Compare” as well as a “Data Compare”

MySQL Diff
Free command line tool. Does a good job comparing the table structures, but does not support all MySQL features.

SQLyog MySQL
It is not free but doing a very good job in comparing databases.

Connect to MySQL with Perl using DBI

Example of a connection to MySQL with Perl using DBI

 
#! /usr/bin/perl -w
#
#  Example code to connect to MySQL, create a table, fill it with some data and select it again.
#
#  To install DBI using cpan:
#
#  perl -MCPAN -e shell
#  cpan> install DBI
#  cpan> install DBD::mysql
#

use strict;
use DBI;

my $database = "test";
my $user = "user";
my $passwd = "secret";
my $sqlCreate = "CREATE TABLE IF NOT EXISTS test ( pkey int(11) NOT NULL auto_increment, a int, b int, c int, timeEnter timestamp(14), PRIMARY KEY  (pkey) ) ";

my $insert = "insert into test (a,b,c) values (1,2,3),(4,5,6),(7,8,9)"; 
my $select = "select a,b,c from test"; 
my $dsn = "DBI:mysql:host=localhost;database=${database}";
my $dbh = DBI->connect ($dsn, $user, $passwd) or die "Cannot connect to server\n";

# Execute the sql to create the table test
my $stmnt = $dbh->prepare($sqlCreate);
$stmnt->execute();

# Insert the testdata
$stmnt = $dbh->prepare($insert);
$stmnt->execute();

# Run a select on the table test
$stmnt = $dbh->prepare($stmntelect);
$stmnt->execute();

while(my @val = $stmnt->fetchrow_array())
{
	print " $val[0]  $val[1]  $val[2]\n";
}
$stmnt->finish();

# Close the connection to the database
$dbh->disconnect ( );
     

 

MySQL: Large VARCHAR vs TEXT?

If you have to store big texts in MySQL you have to choose in between using a big VARCHAR column and the TEXT type. So what are the differences between using for example a VARCHAR(2000) and TEXT?

The difference between TEXT and the VARCHAR type is how MySQL is storing the data. TEXT (and BLOB) data is stored off the table, leaving only a pointer to the actual storage.

So using VARCHAR is faster when the size of the data is reasonable. How big the performance difference is depends on the data and the used hardware.

Due the row length limit of 65,535 bytes the data you can store in the table itself is limited (Using utf8 2000 chars could use up to 6000 bytes).

Quick Status in MySQL

To get a briest status overview of your MySQL server, you can use the command \\n, it will give you a fast idea of the version you are running, the most important settings and an overview of the amount of running queries.

mysql> \s
--------------
mysql  Ver 14.14 Distrib 5.5.29, for debian-linux-gnu (i686) using readline 6.2

Connection id:		993822
Current database:	
Current user:		root@85.50.57.117
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server version:		5.1.66-0+squeeze1 (Debian)
Protocol version:	10
Connection:		h via TCP/IP
Server characterset:	latin1
Db     characterset:	latin1
Client characterset:	utf8
Conn.  characterset:	utf8
TCP port:		3306
Uptime:			23 days 21 hours 50 min 56 sec

Threads: 1  Questions: 12676338  Slow queries: 12  Opens: 21832  Flush tables: 1  Open tables: 64  Queries per second avg: 6.136
--------------

Getting XML and HTML output.

Many people use MySQL in the console to execute a simple command, but did you know that MySQL can format the result of the query directly to XML or html?

The option -X will output the query result as XML
-H can be used to generate a HTML table containing the data.

$ mysql -X -e "select * from test" test



  
	152710
  


Output as HTML

$ mysql -H -e "select * from test" test
test
152710