Using simple_list_item_2 with an ArrayAdapter (Android)

Today I wanted to display static a ListView of properties and their values. It’s Friday, so I really wanted to do this with as little work as possible. Android’s free layout simple_list_item_2 sounded like what I wanted, but it wasn’t immediately clear how to handle this. There are a lot of lazy ways we can list single values, but Googling around how to use simple_list_item_2 resulted in lots of questions with no real answer.

I found Mark Assad, who parsed the system layout files into raw XML. The led to the magic answer of TwoLineListItem widget. Finding this widget allowed me to write a simple ArrayAdapter of key/value pairs.

adapter = new ArrayAdapter<BasicNameValuePair>(this,android.R.layout.simple_list_item_2,list){

        @Override

        public View getView(int position, View convertView, ViewGroup parent){

            TwoLineListItem row;            

            if(convertView == null){

                LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                row = (TwoLineListItem)inflater.inflate(android.R.layout.simple_list_item_2, null);                    

            }else{

                row = (TwoLineListItem)convertView;

            }

            BasicNameValuePair data = list.get(position);

            row.getText1().setText(data.getName());

            row.getText2().setText(data.getValue());

            

            return row;

        }

    };

listView.setAdapter(adapter);

 

Hope this saves someone else some time, as I spent an embarrassing amount of time determined to use the simple_list_item_2 layout.

A Bit Scatterbrained…

Lately I find myself mixing my PascalCase with my camelCase, calling alloc init instead of new, using [ ] instead of (), and writing awfully verbose method names all over the place. I justify my errors with a glimpse at my average day here lately:

Not to scale. Some margin of error. I focus on my family all day. I promise!

The Value of Documentation

Having been reared as a developer in Microsoft’s cozy little .NET world, I didn’t really appreciate the value of quality documentation until I ventured out into the wild jungle.

I’ve been using Appcelerator’s Titanium Mobile SDK for the past few months. It’s kind of become my Shere Khan here in the jungle. Theoretically, using Titanium Mobile is easier and faster than writing native code. This might be true if I didn’t waste so much time deciphering their documentation.

I made a button to toggle my table view’s editable status. The object had a property called editable, so that seemed to be what I wanted. After testing, however, all this did was toggle whether or not swipe-to-delete worked. What I really wanted was the little red minus sign to appear, and have the contents of each row shifted to the right to make room. After 30 minutes of trial and error, looking through TableViewRow properties, and searching their Q&A section (because Appcelerator has no official forums) I found that TableView actually has two properties: editable and editing.

 

image

 

Even after discovering this other property, I still had to actually test each one to see what they did. Apparently, “editable” toggles the swipe-to-delete, whereas “editing” toggles the minus-button-on-the-left thing. The two are independent of each other.

Thanks for saving me time, web based application framework!

Signed,

Bitter in Bossier

Enterprise Library Sometimes Chops XML into 2033 Characters

This morning I began what I thought would be an uneventful task in .NET: connect to one database, download as XML some rows from a table that have changed since a given time, then pass that XML to a stored procedure in another database so that the changes can be merged. Just two tables: one relatively small, the other just a 2-column relationship table for the first table. Here’s a contrived snippet to serve the same purpose:

The SQL:

CREATE PROCEDURE dbo.GetXmlValue

AS

SELECT TOP 100
 *
 FROM sys.all_columns
 FOR XML AUTO, ROOT('Root')

The Code:

Database db = GetDatabase();

DataSet set;

using (DbCommand cmd = db.GetStoredProcCommand("dbo.GetXmlValue"))
 {
     set = db.ExecuteDataSet(cmd);
 }

In my application, it was this second table that tripped me a bit. The first only had a few changed rows, so the XML was only 500-1000 characters. The second table generated a much longer XML string – 3864 characters long. My initial plan was to return two tables, each 1 column and 1 row. When using Database.ExecuteDataSet to fetch the results, however, the second table yielded two rows. I backtracked, second guessed myself, and even grabbed a couple of guys in the hall to double check my code. No one could explain it. It seemed odd that this hasn’t come up before for someone here. I did a bit of Googling and only found a couple of results. This Microsoft Knowledgebase Article just says it’s “by design” and to use SQLCommand.ExecuteXmlReader.

The next question that came up was “Well, what does it do if I return a long XML value among other values in the same row?” I tested this out and everything worked as expected. All of the XML was in a single column value as it should be.

I still can’t exactly explain it. ExecuteScalar has a character limit of 2033 characters. I suspect that because each table in my result set is just a single column value, something somewhere is relying on ExecuteScalar.

My solution? In my stored procedure I just stored each of my table results as an XML typed variable, then returned the two together in the same row.

GTIN 12 UPC Check Digit Calculation in SQL Server 2008

I recently needed to generate the check digit for a GTIN-12 UPC code in SQL. The calculation method for the check digit varies depending on what kind of barcode you’re implementing, so I popped on over to Google to get the necessary algorithm. Naturally, and regardless of simplicity, I checked for any available code snippets. The only I found weren’t GTIN-12, and were in C or C++. So for anyone looking to do it (or something similar) in T-SQL, here’s a scalar function to do just that.

CREATE FUNCTION dbo.CalculateBarcodeGTIN12CheckDigit(@input CHAR(11))
RETURNS INT
AS
BEGIN
	DECLARE @evenDigitSum INT = 0
		,@oddDigitSum INT = 0
		,@i TINYINT = 0
		,@result INT;

	-- check if given Barcode is Numeric , if not return error status -1
	IF(ISNUMERIC(@input) = 0
		OR LEN(RTRIM(LTRIM(@input))) != 11)
		RETURN -1

	-- start the compute BarCode checksum algorithm
	SET @i = 1
	WHILE (@i <= 11)
		BEGIN
		 --Add odd and even digits separately;
		 IF((@i % 2) = 0)
			 SET @evenDigitSum += CONVERT(TINYINT, SUBSTRING(@input,@i,1))
		 ELSE
			 SET @oddDigitSum += CONVERT(TINYINT, SUBSTRING(@input,@i,1))
		 SET @i += 1
		END

	--As per: http://en.wikipedia.org/wiki/Universal_Product_Code
	--Multiply odd sum by 3, add to even sum, and mod 10.
	SET @result = ((@oddDigitSum * 3) + @evenDigitSum) % 10;
	IF(@result = 0)
		RETURN 0
	ELSE
		RETURN 10 - @result;

	RETURN -1
END
GO

Scalar functions are killer, but I’ll only ever be using it for a single record.

Hatcher William

20110520-104025.jpg

So. Awesome. :)

Why The New Guy Can’t Code

We’ve all lived the nightmare. A new developer shows up at work, and you try to be welcoming, but he1 can’t seem to get up to speed; the questions he asks reveal basic ignorance; and his work, when it finally emerges, is so kludgey that it ultimately must be rewritten from scratch by more competent people. And yet his interviewers—and/or the HR department, if your company has been infested by that bureaucratic parasite—swear that they only hire above-average/A-level/top-1% people.

It’s a big problem, especially now. There’s a boom on. I get harassing emails from recruiters every day. Everyone’s desperate to hire developers…but developers are not fungible. A great coder can easily be 50 times more productive than a mediocre one, while bad ones ultimately have negative productivity. Hiring one is a terrible mistake for any organization; for a startup, it can be a catastrophic company-killer. So how can it happen so often?

Like many of the hangovers that haunt modern software engineering, this is ultimately mostly Microsoft’s fault.2 Back when they were the evil empire where everyone secretly wanted to work, they were famous for their “brain-teaser” interview questions – Why are manhole covers round? – and, of course, they asked new university graduates about computer science theory; “Write me a binary search.”

Everyone wanted to be like Microsoft, even Google, until everyone wanted to be like Google (until recently); and so that interview meme persisted. Check out these two recent posts on the subject of interviewing, courtsey of Hacker News: one from a would-be employee, one from a Google interviewer. A couple of illuminating quotes from the latter: “I’m not even necessarily saying that this is a good metric” and “If it’s any consolation, at least we don’t ask gotcha riddle questions anymore. Those were especially offensive.”

It’s nice to see that Google have almost sort of realized that their recruiting algorithm is problematic. Too bad they haven’t fixed it. See also Jean Hsu’s “How Effective Are Technical Interviews?” The fundamental problem is that the skills required to pass today’s industry-standard software interview are not the skills required to be a good software developer. Oh, there’s some correlation, but it’s like the Oakland Raiders always drafting the fastest runners available, only to discover to their endless dismay that the NFL is not a foot race.

Actually it’s worse than that. At least wide receivers have to run, whereas I can guarantee you, without fear of contradiction, that no software engineer will ever have to write a binary search after they are hired. It’s like choosing a contractor because they know how to forge and cast steel using coal, iron, an oven and a bellows, when they actually need to know a) the address of the nearest Home Depot b) what to do with the steel once they buy it.

Joel Spolsky once correctly explained that you’re generally looking for two things in an employee: Smart and Gets Things Done. (Academia is teeming with people who are the former but not the latter.) First, though, you have to establish something else: Not Completely Inept. You’d be amazed how many totally incompetent people show up for technical interviews. Google’s binary search is presumably intended as their “FizzBuzz” – a low bar you have to hurdle just to get in the door. But a FizzBuzz should take all of five minutes, before the real interview begins.

So what should a real interview consist of? Let me offer a humble proposal: don’t interview anyone who hasn’t accomplished anything. Ever. Certificates and degrees are not accomplishments; I mean real-world projects with real-world users. There is no excuse for software developers who don’t have a site, app, or service they can point to and say, “I did this, all by myself!” in a world where Google App Engine and Amazon Web Services have free service tiers, and it costs all of $25 to register as an Android developer and publish an app on the Android Market.

The old system was based on limited information—all you knew about someone was their resume. But if you only interview people with accomplishments, then you have a much broader base to work from. Get the FizzBuzz out of the way, and then have the interviewee show and tell their code, and explain their design decisions and what they would do differently now. Have them implement a feature or two while you watch, so you can see how they actually work, and how they think while working. That’s what you want from a technical interview, not a measure of its subject’s grasp of some antiquated algorithm or data structure. The world has moved on.

1Yes, I am being deliberately sexist here, because in my experience those women who write code are consistently good at it.

2I don’t mind that Bill Gates is a megazillionaire; he’s done a lot of really interesting and innovative stuff. I do mind that a lot of unworthy people rode his coattails to minizillionaire status, eg the inventor of Hungarian notation, probably the dumbest widely-promulgated idea in the history of the field.


Tags: , , ,

categories Uncategorized

Send a Photo Postcard for $0.99 via Postagram [Photos]

Digital photo sharing is nice and everything, but nothing beats a printed memory delivered to your home. Postagram, from the makers of the popular photo sharing Instagram app, makes it easy to send photo postcards from your iPhone or the web. More »


Chrome 11 beta adds new experimental APIs for proxies, Web navigation

google chrome 11 proxy
Google Chrome 11 -- which just recently made the move to the browser's beta channel -- has received a minor update that gives developers access to two new APIs.

The first is a full-featured proxy API, which will, for example, allow users to set different proxy servers for normal browsing and Incognito mode. Proxy auto-config scripts are also supported by the API.

The second -- Web Navigation Extension -- is a bit more expansive. This API will allow devs to build everything from more powerful safe browsing extensions -- like Traffic Light -- to data analysis and reporting extensions.

Both APIs are currently experimental, so you'll need to enable them on the about:flags page to try out any relevant extensions. Apart from a proxy example built by Google and shipped with the Chromium source, we're not aware of any examples just yet, however. We'll let you know when we spot any slick, new extensions which do surface.

Chrome 11 beta adds new experimental APIs for proxies, Web navigation originally appeared on Download Squad on Tue, 05 Apr 2011 08:00:00 EST. Please see our terms for use of feeds.

Permalink | Email this | Comments

‘Friday’ Is Just a Beatles’ Rip Off

We've learned a very important lesson from this…

John Lennon was super into Fridays.

[via The Daily What]