How to Fix Android CalledFromWrongThreadException
So you’re just cruising along writing the next big Android App dreaming of making it big and getting rich and then BAM! User after user is kicking you in the balls because that great Android application of yours just crashed and it’s complaining about a CalledFromWrongThreadException. Okay, so what happened and how to we fix it?
Well, basically when an Android application starts your process is given a thread that is your “main” thread, or alternately, your “UI” thread. Anytime you want to access or modify any user interface elements you must do so from this thread. The simple reason for this is that the UI components (or Android UI Toolkit as Google calls it) is not thread safe. In other words, bad things happen if multiple threads touch the same control at the same time. It won’t be the end of the world but it will be the end of your application. The end of your application comes via a CalledFromWrongThreadException which is just a type of runtime exception used by Android.
Time for an example. Consider the following Java code:
(in all examples I’ve added a single TextView control within the app resources called textTest)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class TestActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTimer = new Timer(); mTimer.schedule(new OnTimer(), 1000); } class OnTimer extends TimerTask { public void run() { TextView v = (TextView)TestActivity.this.findViewById(R.id.textTest); v.setText(Integer.toString(mValue)); mValue++; mTimer.schedule(new OnTimer(), 1000); } } private int mValue = 0; Timer mTimer; } |
According to that code, about once every second a counter will be incremented and the content of a TextView control will be updated with the value of the counter. Unfortunalty, when you run it you will see a message similar to this:
Read the rest of this post »
September 19, 2011
·
crow ·
No Comments
Tags: Android, Java, Threading, UI · Posted in: Android, Java, Programming
List of Top Open Source Games
Lately I’ve been compiling a list of the best open source games out on the Internet, partly just for new games to play and partly because I was thinking of contributing to one of the games. It’s amazing how many good quality open source games are available now days. I am Impressed. Anyway, I figured I would share my list so far with all of you. If you know of any other fun and interesting open source games be sure to let me know. So, without further ado, my top ten open source games:
Read the rest of this post »
September 15, 2011
·
crow ·
2 Comments
Tags: Games, Open Source · Posted in: General
What is game programming
What is game programming
What is game programming? Well, I suppose game programming is a little bit of everything in the computer science world. Programming games is one part science, one part art, and one part fun (most of the time!). Programming games is much different than “normal” programming. Traditional business apps today are largely event-driven programs. In a game, you don’t wait for events. The game has to continually update the screen, check the network, respond to user input, run game logic, play audio, and many more things some 30 to 60 times a second. It’s quite a challenge, especially considering some games run on devices with constrained resources like a smart phone.
If you are really interested in game programming, be warned, it’s a lot of work. It’s hard. But, it’s also very rewarding. There is something unique about watching your users “play” your software as opposed to watching your users “use” your program, so to speak. Anyway, I’ve provided an outline below if your interested in getting started with game programming.
Getting Started
The first thing you need to do is learn a programming language. A game can be programmed in just about any programming language. Some of the more popular ones are:
C/C++ – This is the traditional language (actually they are two distinct languages) used to program high performance games. Most of the AAA commercial games on PC, PS3, XBox, etc are programmed in C++ or C. Many people starting out consider these hard languages to learn and they are also considered the most costly to develop a game with. Check the links below for more information.
en.wikipedia.org/wiki/C_(programming_language)
www.cplusplus.com
en.wikibooks.org/wiki/C++_Programming
Java – Java is a bit easier to learn when compared with C++ but you don’t generally get the same level of performance. I don’t know of a lot of commercial/successful games written in Java, although that may change soon with the proliferation of Android devices. If you are going to write a game on Android your most likely going to be using Java. If you know of any great Java games for the PC let me know! See the following links for more information about Java.
http://java.sun.com/docs/books/jls/
http://www.javabeginner.com/
The list goes on: ActionScript for programming Flash games, python, C# (which you can use with the XNA Framework to create games for the XBox 360). Have a look at all of these languages and pick the one that makes the most since to you to start learning.
August 27, 2011
·
crow ·
One Comment
Tags: Game Programming, Programming · Posted in: Game Programming, General
SDL & OpenGL Game with C++ – Part II
Parts in the Series
Rendering a Quad with OpenGL and SDL
Ok, so if we are going to program a video game then we need to draw something with OpenGL.
That being said, last time we left off with a basic framework for creating a game with SDL. If you haven’t read it then you should check out part 1 here because we’ll be building off of that. This time around the goal is simply to get something rendering on the screen with OpenGL. So with that in mind here is the road map for what I wanted to accomplish:
- Render a single quad
- Render a textured quad
As you can see I am going to keep it simple for now. I’ll throw in the ability to swap textures at runtime as well just to keep it interesting.
The game so far will look a little something like this:
![]()
Drawing a Square With SDL
First on the list is to render a single quad. But, before you do anything make sure you add the OpenGL libraries to your project. You can accomplish that by going into the linker section of the project settings and adding opengl32.lib and glu32.lib to the additional dependencies section, just as we did for the SDL libraries in Part I.
I am just going to start out showing you the new main function and then we will go through it step by step. So here ya go!
December 8, 2009
·
crow ·
3 Comments
Posted in: C/C++, Game Programming, Programming
SDL & OpenGL Game with C++ – Part I
Parts in the Series
Getting Started
I think I’ve spent too many late nights playing multiplayer Modern Warfare 2 and now I feel the need to build a small game of some kind. Game programming is fun, and although I’ve never done it professionally, I have dabbled with it as a hobby for many years. I’ll be documenting my progress here over time via a number of different postings. Maybe some of you will find it useful as a reference or small SDL tutorial or game programming tutorial. That being said, time to get to work!
I have no idea what type of game to build yet so the first thing to do is just get the basic framework setup. I’ll be using C++ for this game project. I thought about using C# and XNA but I need to dust off my C++. For the graphics system I decided to use OpenGL. This is mostly because I am familiar with it and didn’t want the extra overhead of boilerplate setup stuff associated with DirectX. I just want to get something going quickly. For the rest of the stuff needed (audio, input, etc) I am going to use SDL. SDL is a great tool to get things up and running fast and it easily interfaces with OpenGL. I am also thinking about putting in some UI stuff using CEGUI (Crazy Eddie’s GUI System).
SDL Setup Prerequisites
Before we get started you’ll want to make sure you have the SDL development libraries (I am using version 1.2.14). You can find them on the SDL website: http://www.libsdl.org. The ones I used specifically are:
- Runtime – http://www.libsdl.org/release/SDL-1.2.14-win32.zip
- Library (Visual Studio 2008) – http://www.libsdl.org/release/SDL-devel-1.2.14-VC8.zip
November 23, 2009
·
crow ·
2 Comments
Posted in: C/C++, Game Programming
Runtime Scripting in .Net
The ability to ship source code with your product that can be compiled or interpreted at runtime is a very valuable asset. Video games do this all the time with things like AI allowing the end-user to easily mod the game. In compiled languages like C++, this technique is highly advantageous as it allows you to avoid the costly compile-link cycle for every small change to a source file. This is also helpful in an environment where creating a new build, generating the installer, and deploying it is overkill or difficult to achieve. In this article we will examine how you can achieve this from .Net programs consuming a C# or VB.Net script. I’ll refer to this as “scripting”, even though an unambiguous definition of a “script” is somewhat difficult to nail down.
Using a C# or VB script from a .Net language is actually very simple. The basic idea is to read in a source file, which could come from the network or disk, and compile it into a temporary assembly on file or IL in memory. Then you can instantiate types from the script file and use them just as easily as any other types already defined. Normally the hard part in this process is locating and invoking the proper compiler. Luckily, we can compile IL code using a CodeDomProvider like CSharpCodeProvider. And, since these types are part of the .Net framework we know they are available on the end-user PC! Life is great eh?
Ok, so first make sure you have referenced the following namespaces:
using System.CodeDom.Compiler; using Microsoft.CSharp; using Microsoft.VisualBasic;
Next you need to setup the compiler parameters. These are simply the options given to the compiler such as whether to create the resulting assembly in memory or if debug information should be included in the generated code. You can do this with the CompilerParameters type. Here is an example for creating an in memory assembly with debug information:
CompilerParameters cparams = new CompilerParameters(); cparams.GenerateInMemory = false; cparams.IncludeDebugInformation = true; cparams.CompilerOptions += " /debug:pdbonly"; cparams.TreatWarningsAsErrors = false; cparams.GenerateExecutable = false;
You would also want to add any references that your code needs using CompilerParameters. ReferencedAssemblies. So, after you have the compiler options set you need to actually invoke the C# or Visual Basic compiler. You do this by creating a CodeDomCompiler of the appropriate type:
VBCodeProvider – for Visual Basic
CSharpCodeProvider – for C Sharp
Then you can use the provider to compile an assembly like so:
CodeDomProvider provider = CSharpCodeProvider(); CompilerResults result = provider.CompileAssemblyFromFile(cparams, script);
Where cparams are your compiler parameters and result is well, your results. Within results you will find out if the compilation was successful or generated warnings. It will also give you access to the resulting assembly. You can check for errors using results.Errors.HasErrors and reference the assembly with results.CompiledAssembly.
September 30, 2009
·
crow ·
4 Comments
Posted in: C#
Using Ini Files In C#
An Initialization, or Ini file, is a common text based file format commonly used on the Windows platform. Today its mostly been succeeded in favor of XML files for application configuration and persisting user data. Never the less, these files still exist and are in use by many applications. In this post, we will explore how to work with Ini files via C#.
The structure of an Ini file is very simple and straight forward. You have three primary types of information: sections, parameters, and values. They look like this:
[SectionA]
Parameter1=value1
Parameter2=value2
[SectionB]
Parameter1=value1
Below we will create a class to read this data from a file. Keep in mind as you look at this C# Ini file implementation that this is just one way to do it. You could for example, create a much more concise solution using regular expressions, etc.
Parsing the Data
The first thing we should do if figure out how to get the data from the Ini file. We could read in all the text and manually parse the file; however there is an easier approach. The Win32 API contains a function called GetPrivateProfileString that we can use specifically for this task. We can use it to directly obtain the sections, parameters, and values. For a more detailed description of the GetPrivateProfileString function, check out this link on MSDN.
To use GetPrivateProfileString in C#, we need only reference it using the DLLImport attribute with the correct function signature.
[DllImport("Kernel32.dll", EntryPoint = "GetPrivateProfileStringW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnString, int nSize, string lpFilename);
Reading from an Ini File
First, to make our job a little easier we will wrap the call to GetPrivateProfileString with our own method so that we can handle all of the details. Here is the wrapper:
private string[] GetPrivateProfileString(string appName, string keyName, string defaultName, string inifile) { // the file inifile should exist as it's validated in the class constructor, however GetPrivateProfileString does not lock the file hence it could be locked or deleted by // another process between calls to this method // used to tell if we successfully read all requested data from the file // from MSDN: // If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one. // If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two. int sizeReadOffset = (appName != null && keyName != null) ? 1 : 2; // try and read the entire amount of data from the ini file int sizeRead = Kernel32.GetPrivateProfileString(appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile); // if unable to read all of the data because the buffer is to small, increase the size and try again, but only allow memory to increase up to _readBufferMaxSize while ((sizeRead >= _readBufferSize - sizeReadOffset) && (_readBufferSize < _readBufferMaxSize)) { _readBufferSize += 512; _readBuffer = new char[_readBufferSize]; sizeRead = Kernel32.GetPrivateProfileString(appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile); } // if memory consumption exceeded _readBufferMaxSize then we have a problem if (_readBufferSize >= _readBufferMaxSize) throw new FileLoadException("ErrorBadIniLoad"); // the buffer returned from GetPrivateProfileString will be null terminated C-strings followed by a double null at the end - so split the strings on the nulls char[] sep = new char[1]; sep[0] = '\0'; string s = new string(_readBuffer, 0, sizeRead); string[] result = s.Split(sep, StringSplitOptions.RemoveEmptyEntries); return result; }
Here, the MSDN terminology refers to what I call a section as an appName and what I refer to as a paramter as a keyName.
This method has a lot going on but is very easy to use. To get an array of strings containing all of the section names you simply say:
Read the rest of this post »
July 16, 2009
·
crow ·
2 Comments
Posted in: C#
I’m Back
Hey guys, sorry I’ve been away for a bit. I’ll try and respond to your questions, especially those over on the C# dynamic web service page.
I’ll be adding a whole lot of new content as well. If anyone has any suggestions on a topic feel free to leave them for me.
See Ya!!
July 15, 2009
·
crow ·
2 Comments
Posted in: General
Accessing the System Task Bar in C#
In this post I’ll show you how to access the system taskbar and obtain information like its location, size, etc. You may find yourself needing to do something like this if you had a “popup” window for instance that is always supposed to “pop up” from the system tray. This is a common feature in many of today’s applications; however the task bar may be docked somewhere other than the bottom of the screen or maybe even on a different monitor in a multi-monitor setup.
The Taskbar is an APPBAR
First, the task bar is considered an appbar (or desktop application toolbar) albeit with some special restrictions. Being an appbar we can talk to it with the Win32 API function SHAppBarMessage. SHAppBarMessage allows us to send a message to the system to get or set information about a registered appbar. The necessary C# definitions to access the function are as follows:
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } [StructLayout(LayoutKind.Sequential)] private struct APPBARDATA { public Int32 cbSize; public IntPtr hWnd; public Int32 uCallbackMessage; public ABEdge uEdge; public RECT rc; public IntPtr lParam; } private enum ABMsg { ABM_NEW = 0, ABM_REMOVE = 1, ABM_QUERYPOS = 2, ABM_SETPOS = 3, ABM_GETSTATE = 4, ABM_GETTASKBARPOS = 5, ABM_ACTIVATE = 6, ABM_GETAUTOHIDEBAR = 7, ABM_SETAUTOHIDEBAR = 8, ABM_WINDOWPOSCHANGED = 9, ABM_SETSTATE = 10 } private enum ABEdge { ABE_LEFT = 0, ABE_TOP = 1, ABE_RIGHT = 2, ABE_BOTTOM = 3, } private enum ABState { ABS_MANUAL = 0, ABS_AUTOHIDE = 1, ABS_ALWAYSONTOP = 2, ABS_AUTOHIDEANDONTOP = 3 } [DllImport("shell32.dll")] private static extern IntPtr SHAppBarMessage(ABMsg dwMessage, [In, Out] ref APPBARDATA pData);
Using SHAppBarMessage
In order to use SHAppBarMessage we must first fill out the APPBAR struct with at least the cbSize and hWnd members. For hWnd we need to get the handle to the system taskbar window. It just so happens that you can use the FindWindow API function with a system class name of “Shell_TrayWnd” to get the required handle. Of course, to the best of my knowledge the class name “Shell_TrayWnd” is not a “documented” part of the Win32 system therefore it could change with any Windows release. However, I think it’s probably a safe bet to rely on it given the number of applications in the field that already do. Without further ado, some code to get the size of the task bar.
[DllImport("user32.dll")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); APPBARDATA appBar = new APPBARDATA(); appBar.hWnd = FindWindow("Shell_TrayWnd", ""); appBar.cbSize = Marshal.SizeOf(appBar); System.IntPtr ret = SHAppBarMessage(ABMsg.ABM_GETTASKBARPOS, ref appBar); Size s = new Size(appBar.rc.right - appBar.rc.left, appBar.rc.bottom - appBar.rc.top);
Simple right?
Modifying the Taskbar
Remember earlier I said the system taskbar is not quite like a normal appbar? Well it’s special in that you can’t really change any of its properties like its size or position. This makes sense as you wouldn’t just want any program you install to play with the users taskbar; it’s sort of like an invasion of privacy. I’ve seen claims around the Internet that this can be pulled off in application code, which may be true prior to Vista; however I’ve tried all kinds of tricks based on SHAppBarMessage and can’t change the taskbar properties under Vista. Do you know how this can be done or if it’s even possible? I have found that you can change the task bar state. That is, you can toggle between “autohide” mode and “always on top” mode.
Example Taskbar Code
So, here is a little class I’ve put together to wrap the SHAppBarMessage functionality. I really haven’t paid attention to error handling or anything with it so if you use this you would need to address that.
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Drawing; namespace TaskbarInfoExample { /// <summary> /// Provides methods for obtaining and modifying information for the system taskbar. /// </summary> class TaskBar { #region Native API // The native API functions/enums/structs needed to access taskbar info // consult MSDN for more detailed information about them [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } [StructLayout(LayoutKind.Sequential)] private struct APPBARDATA { public Int32 cbSize; public IntPtr hWnd; public Int32 uCallbackMessage; public ABEdge uEdge; public RECT rc; public IntPtr lParam; } private enum ABMsg { ABM_NEW = 0, ABM_REMOVE = 1, ABM_QUERYPOS = 2, ABM_SETPOS = 3, ABM_GETSTATE = 4, ABM_GETTASKBARPOS = 5, ABM_ACTIVATE = 6, ABM_GETAUTOHIDEBAR = 7, ABM_SETAUTOHIDEBAR = 8, ABM_WINDOWPOSCHANGED = 9, ABM_SETSTATE = 10 } private enum ABEdge { ABE_LEFT = 0, ABE_TOP = 1, ABE_RIGHT = 2, ABE_BOTTOM = 3, } private enum ABState { ABS_MANUAL = 0, ABS_AUTOHIDE = 1, ABS_ALWAYSONTOP = 2, ABS_AUTOHIDEANDONTOP = 3 } [DllImport("shell32.dll")] private static extern IntPtr SHAppBarMessage(ABMsg dwMessage, [In, Out] ref APPBARDATA pData); [DllImport("user32.dll")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); #endregion /// <summary> /// Represents the edge of the screen the task bar is docked to. /// </summary> public enum TaskBarEdge { Left = ABEdge.ABE_LEFT, Top = ABEdge.ABE_TOP, Right = ABEdge.ABE_RIGHT, Bottom = ABEdge.ABE_BOTTOM } /// <summary> /// The states the task bar can be in. /// </summary> [Flags] public enum TaskBarState { /// <summary> /// No autohide, not always top /// </summary> None = ABState.ABS_MANUAL, /// <summary> /// Hides task bar when mouse exits task bar region /// </summary> AutoHide = ABState.ABS_AUTOHIDE, /// <summary> /// Taskbar is always on top of other windows /// </summary> AlwaysTop = ABState.ABS_ALWAYSONTOP } /// <summary> /// Gets the location, in screen coordinates of the task bar. /// </summary> /// <returns>The taskbar location.</returns> public static Point GetTaskBarLocation() { APPBARDATA appBar = GetTaskBarData(); return new Point(appBar.rc.left, appBar.rc.top); } /// <summary> /// Gets the size, in pixels of the task bar. /// </summary> /// <returns>The taskbar size.</returns> public static Size GetTaskBarSize() { APPBARDATA appBar = GetTaskBarData(); return new Size(appBar.rc.right - appBar.rc.left, appBar.rc.bottom - appBar.rc.top); } /// <summary> /// Gets the edge of the screen that the task bar is docked to. /// </summary> /// <returns></returns> public static TaskBarEdge GetTaskBarEdge() { APPBARDATA appBar = GetTaskBarData(); return (TaskBarEdge)appBar.uEdge; } /// <summary> /// Gets the current state of the taskbar. /// </summary> /// <returns></returns> public static TaskBarState GetTaskBarState() { APPBARDATA appBar = CreateAppBarData(); return (TaskBarState)SHAppBarMessage(ABMsg.ABM_GETSTATE, ref appBar); } /// <summary> /// Sets the state of the task bar. /// </summary> /// <param name="state">The new state.</param> public static void SetTaskBarState(TaskBarState state) { APPBARDATA appBar = CreateAppBarData(); appBar.lParam = (IntPtr)state; SHAppBarMessage(ABMsg.ABM_SETSTATE, ref appBar); } /// <summary> /// Gets an APPBARDATA struct with valid location,size,and edge of the taskbar. /// </summary> /// <returns></returns> private static APPBARDATA GetTaskBarData() { APPBARDATA appBar = CreateAppBarData(); System.IntPtr ret = SHAppBarMessage(ABMsg.ABM_GETTASKBARPOS, ref appBar); return appBar; } /// <summary> /// Creats an APPBARDATA struct with its hWnd member set to the task bar window. /// </summary> /// <returns></returns> private static APPBARDATA CreateAppBarData() { APPBARDATA appBar = new APPBARDATA(); appBar.hWnd = FindWindow("Shell_TrayWnd", ""); appBar.cbSize = Marshal.SizeOf(appBar); return appBar; } } }
That’s All!
That’s all I’ve got for now. I have included a little demo app you can download to demonstrate the class. You can find that here Basically it just allows you to modify the task bar state and shows you all of its properties.
Hope you found this useful and saved yourself some time!
May 10, 2009
·
crow ·
6 Comments
Posted in: C#, Programming
Launching and Viewing Processes in C#
You can launch a new process from a C# application by using the Process class located in the System.Diagnostics namespace. The Process class also allows you to obtain a collection of all running processes on the system.
How to Launch a New Process
Starting a process is really easy.
Process.Start( "Notepad.exe" );
And that’s it. If Notepad.exe exists on your system then it will start. Make sure that if you do not specify a complete path then the name you do present is available in your environment path. You can wait for the newly created process to terminate as well.
Process p = Process.Start( "Notepad.exe"); p.WaitForExit();
Keep in mind that WaitForExit will block the calling thread. If you don’t want that behavior considering launching the new process on a thread of its own. You can also use the ProcessStartInfo class to pass information to the Start method. This example launches the new process on a thread from the thread pool via an anonymous method. Remember to include System.Threading.
// launch the program / process on a new thread from the thread pool ThreadPool.QueueUserWorkItem( (WaitCallback)delegate(object state) { ProcessStartInfo psi = new ProcessStartInfo("Notepad.exe", ""); Process p = Process.Start(psi); p.WaitForExit(); });
Passing Arguments to the New Process
You can also pass arguments to a new process. The next example will launch Notepad and tell it to open the file MyFile.txt.
ProcessStartInfo psi = new ProcessStartInfo("Notepad.exe", @"C:\My\Path\MyFile.txt"); Process p = Process.Start(psi);
Launching a Document and Setting the Verb
There are some other interesting things you can do with the Process class. For instance, instead of specifying a file name in Process.Start like we did above with Notepad.exe, we could specify a file or document. The method would then open that file with the registered default application for that type of file. You can also specify a verb that is associated with that file type. A verb represents an action that is associated with that file type. So, if I wanted to launch the default application for a .txt file and have that file printed I could do the following:
ProcessStartInfo psi = new ProcessStartInfo(@"C:\My\Path\MyFile.txt"); psi.Verb = "print"; Process p = Process.Start(psi); p.WaitForExit();
Listing All Running Processes
The last thing I want to show you is how easy it is to view a list of all processes running on the system with C#. Assuming you have a ListBox name listbox1, the following code fragment would add an entry to the ListBox with the name of each process running on the system.
Process[] processes = Process.GetProcesses(); foreach( Process process in processes ) listBox1.Items.Add( process.ProcessName );
Well, that’s it for today. Hope this information comes in handy for some of you!
April 15, 2009
·
crow ·
3 Comments
Posted in: C#, Programming
