Android: Save and load settings

Its always good when an application remembers the last settings you've used. To add that functionality within your app, just add this class to your project.

/**
* This class is responsible for storing and loading the last used settings for the application.
*
* @author twig
*/
public class Settings {
public boolean music = true;
public boolean sfx = true;
public int games_played = 0;
public int high_score = 0;

public Settings() {
this.loadSettings();
}

public void loadSettings() {
SharedPreferences settings = G.activity.getPreferences(Activity.MODE_PRIVATE);

this.music = settings.getBoolean("music", this.music);
this.sfx = settings.getBoolean("sfx", this.sfx);
this.games_played = settings.getInt("games_played", this.games_played);
this.high_score = settings.getInt("high_score", this.high_score);
}

public void saveSettings() {
SharedPreferences settings = G.activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();

editor.putBoolean("music", this.music);
editor.putBoolean("sfx", this.sfx);
editor.putInt("games_played", this.games_played);
editor.putInt("high_score", this.high_score);

editor.commit();
}
}

When you create an instance of it, it'll automatically load up the old settings and the set defaults if it can't find it.

Remember, you'll still have to save when the application exits!

/**
* Activity is stopped by Android OS.
*/
@Override
protected void onStop(){
super.onStop();

G.savePreferences();
}

Android: Center a button or view horizontally but have a margin offset from the top of the layout

For the title screen, I wanted something that used the layout system without hard-coding pixel values.

Ideally, it'd look like this.

image

I needed this to work using the code rather than layout editor, as the editor only allowed me to enter in fixed pixel values for the margin offset.

The red area had to be approximately 45% of the screen, and the rest would be dedicated to the buttons.

The blue areas are just spacing, evenly distributed between the buttons which have a width which is content wrapped.

Using the linear layout, I was able to get this working via the code.

private void addButtons() {
LayoutParams lp; // Instance of LinearLayout.LayoutParams

lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
lp.topMargin = (int) (G.screenH * 0.45);
this.addView(btnPlay, lp); // This uses its own one to be displayed half-screen

lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
lp.topMargin = 5;
this.addView(btnSettings, lp);
this.addView(btnScores, lp);
this.addView(btnAbout, lp);
this.addView(btnExit, lp);
}

The first button needs its own layout parameter, as it has a different offset to the others. The other buttons are separated by a 5 pixel gap.

It'd be a good idea to make that gap a density independant pixel size by converting it first.

Android: Convert pixel (dip) to density dependent pixel (ddp) size

For Android, one of the biggest problems is the wide variety of screen resolutions. What's worse is that the resolution is only one of three possible problems with positioning.

There is also screen size (the physical screen size such as 4.3") and pixel density (the number of pixels in a physical measurement such as CM or inches).

Starting from Android 1.6, this was simplified a great deal. The official documentation for supporting multiple screens can explain this MUCH better than I ever can here, so have a read of it.

Using this snippet, you can convert a hard-coded pixel value to something that is more relevant on the screen.

/**
* Converts the density independant pixel size to a density dependant pixel size.
*
* @param dip The intended pixel size.
* @return int The converted density dependant pixel size.
*/
public static int convertDensityPixel(int dip) {
return (int) (dip * yourActivity.getResources().getDisplayMetrics().density);
}

[ Source ]

Android: Remove titlebar and make your app completely fullscreen

If you're not entirely fond of the WYSIWIG layout creator and prefer to do things with code, use the following snippet to make the app full screen.

public class SlowPokeActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Make it completely full screen
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}

Android: Animate between views

One of the strengths of the iPhone user interface is that things gel together very well. If you click into something, it'll slide or move about to give you an idea of what the app is doing.

Android can do it too, so don't let your app be thought of as an inferior product because of something like that.

To animate between views, you'll need to be using a layout on your Activity. This layout will remain on your activity as the base on which every other view will sit upon.

public class YourActivity extends Activity {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Animation animation;
View viewLoading = new NowLoadingView();

// Set up the view animator
m_viewAnimator = new ViewAnimator(this);
m_viewAnimator.setAnimateFirstView(true);

animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(2000);
m_viewAnimator.setInAnimation(animation);

animation = new AlphaAnimation(1.0f, 0.0f);
animation.setDuration(2000);
m_viewAnimator.setOutAnimation(animation);

this.setContentView(m_viewAnimator);

m_viewAnimator.removeAllViews();
m_viewAnimator.addView(viewLoading);

This will now fade in your "loading" view. When its time to change the view, simply remove everything and then add the next one. This will automatically fade out the old and fade in the new.

m_viewAnimator.removeAllViews();
m_viewAnimator.addView(new TitleScreenView());

You can use any transition you wish, just take a look through the docs for animations which suit your use case.

An example of using the TranslateAnimation to slide in from the right is below:

Animation animation;

animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f
);

animation.setDuration(400);

Have fun!

Android: Capture the BACK button keypress and display a confirmation dialog

An often useful feature to have is the "Are you sure you wish to exit?" confirmation as someone may accidently touch the back button and exit your application.

To add that, we need to first override onKeyDown() in the application and detect the BACK button keypress.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Are you sure you want to leave?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which){
// Exit the activity
YourActivity.this.finish();
}
})
.show();

// Say that we've consumed the event
return true;
}

return super.onKeyDown(keyCode, event);
}

A word of warning, in Android 2.0 there is a handler purely for the back button called onBackPressed().

[ Source, Docs, onBackPressed() ]

Android: How to stop and exit your application

Normally the "back" button will exit your application, but if you wanted to put that functionality into an "exit" button, then you'll need to call YourActivity.finish().

*update 21/02/2011*
Just keep in mind that this will mark an activity as "ready to be cleaned up" by the OS.
It will not immediately clean it up, so don't worry when you see the activity reside in the emulator for a bit longer.

django: Dump model instances to fixtures

Fixtures are handy when setting up a new copy of your site, but writing them by hand is an absolute pain!

Luckily, the folks at django have saved us yet again.

This little command allows us to select exactly which objects to export, but also how to format it.

from django.core import serializers
from yourapp.models import YourModel

data = serializers.serialize("json", YourModel.objects.all(), indent = 4)

file = open("initial_data.json", 'w')
file.write(data)
file.close()

This will run through and serialise the objects you pass. Just write "data" into the JSON file of your choice!

*update 20/01/2011* Added 3 lines to write the data to a file

[ Source ]

django: custom Feed takes exactly 1 argument (0 given)

It's one of those silly brain fart moments which takes a while to figure out.

I kept getting this error and kept fiddling with argument variables, trying to get it working.

Luckily, I didn't mess up too much before I realised that I was declaring the feed incorrectly.

I noticed that I had it set as a function using "def", rather than a "class" which it should be.

image

Windows: Disable video thumbnails for specific filetypes without losing media summary tab or tooltips

I got sick of video files being locked when I was moving stuff around. The reason they were being locked is that Windows Explorer would open up the file to create a thumbnail while I was browsing without releasing the handle properly.

Normally I'd use Process Explorer to unlock it, but this was happening far too often in a day to put up with.

If you want to disable thumbnails for videos, many sites will tell you to use this command:

regsvr32 /u shmedia.dll

Well that works fine, but you also give up the ability to view ID3 tags on MP3 files and other audio/video formats.

I wanted to keep this functionality, so I had to use another method.

  • Open up RegEdit
  • Navigate to "HKEY_CLASSES_ROOT\.avi\ShellEx"
  • Expand the path and check the default value.

Now for the tricky bit. If the default value is "{c5a40261-cd64-4ccf-84cb-c394da41d590}", then feel free to change it to an empty string (by deleting the text and clicking OK).

Otherwise, copy the value and go to "HKEY_CLASSES_ROOT\CLSID\{your-key-value}\InProcServer32". For me, it was "HKEY_CLASSES_ROOT\CLSID\{c5a40261-cd64-4ccf-84cb-c394da41d590}\InProcServer32".

If the default value has "shmedia.dll" in it, then feel free to go back to the .avi key and delete your key from the default value.

Now, no more thumbnails for just AVI files. You can perform this for other filetypes and the method would remain the same.

Songbird: Stop files from syncing into root folder

Songbird has been a great piece of software for syncing music onto multiple devices.

However, it shits me to no end when I put in a new device and it syncs the files into the root folder, making an absolute mess and mixing all the (potentially) system folders up with lots of music folders.

If this has happened to you already, I'm sorry but you'll just have to manually dig through and move them yourself.

To prevent it from misbehaving like that, simply make a folder called "Music" in the root folder before syncing.

This will be used instead of the root folder.

Sources

Removing "Security Tools" virus/trojan/malware

image

Don't believe anything this trojan says. It's a dirty, filthy little piece of scamware and every threat its reporting is a lie. Security Tools should just report itself and get it over and done with.

It will block most applications from running, so you'll need to somehow get Task Manager up and running before it starts.

Some people use safe mode, others have reported that "CTRL + ALT + DEL" works and can open up the Task Manager without it complaining. If not, try "CTRL + SHIFT + ESC", which does the same thing.

If that doesn't work, you'll have to create a shortcut to "taskmgr.exe" and move it into your "Start Menu > Startup" folder by dragging it with the mouse. Reboot your computer to get access to Task Manager.

Once you have Task Manager up and running, look under "Processes" and close off any program which has all numbers for the filename.

After killing off the pesky little bugger, we're now able to run new programs without any problems.

Run "services.msc" from "Start > Run". Find the following services and then stop and disable each one:

  • Browser Defender Update Service
  • PC Tools Auxiliary Service
  • PC Tools Security Service

Download MalwareBytes Anti-Malware to scan, unlock the files in use and remove the Security Tool Virus. While it scans, we can do some manual removal.

Now go to "Start > Run" again to load up "msconfig". Go to "Startup" tab and disable anything that is within the "Spyware Doctor" folder (or anything that looks suspicious). For me it was "ISTray".

Now open up the following folders and move as much junk out of there as you can. Skip the files that are locked.

  • C:\Program Files\Spyware Doctor
  • C:\Program Files\Common Files\PC Tools
  • C:\ProgramData\PC Tools

Open up "Start > Run" and fire up "regedit". Go to and delete the following registry keys:

  • HKEY_CURRENT_USER\Software\Security Tool
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Browser Defender_is1
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Spyware Doctor

Now the easier part. Search through the registry for anything containing "Spyware Doctor". I've made a list of the items I've found but they may vary from computer to computer.

Best bet is to just do the scan manually.

  • HKEY_CLASSES_ROOT\CLSID\{472734EA-242A-422B-ADF8-83D1E48CC825}
  • HKEY_CLASSES_ROOT\CLSID\{70F8E90E-353A-47AB-B297-C576345EE693}
  • (there was another one here that I forgot to copy before deleting)
  • HKEY_CLASSES_ROOT\CLSID\{F94D9C45-A227-4173-8AC3-6D276B288D9A}
  • HKEY_CLASSES_ROOT\TypeLib\{175B7885-28AB-4D18-8773-7A13A99980A4}
  • HKEY_LOCAL_MACHINE\SOFTWARE\PCTools
  • HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Browser Defender Update Service
  • HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\sdAuxService
  • HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\sdCoreService
  • HKEY_LOCAL_MACHINE\SYSTEM\ControlSet003\Services\Browser Defender Update Service
  • HKEY_LOCAL_MACHINE\SYSTEM\ControlSet003\Services\sdAuxService
  • HKEY_LOCAL_MACHINE\SYSTEM\ControlSet003\Services\sdCoreService

Now hopefully you've learnt your lesson and started to use a proper antivirus.

Every infected machine I look at is running one of the following 3 security suites; McAfee, Norton or Sophos. Goes to show (again) that they're fucking shit and not worth paying for.

Django: Capture blocks of template data and apply filters

The ability for Django to spit data out to the template so easily using tags and filters is really one of its strengths.

However, if you need to alter the output of some tags and they don't support an option to store the data as a context variable, things might get a little hairy.

Luckily, there is an easy way to apply filters to that data and its even built into the framework.

Use the "filter" tag to apply one or more filters to the data.

<a href="/do/something/here?url={% filter urlencode %}
{% url video-feed '' %}pubid;{{ article.source_publication.pubid }};id;{{ article.id }}
{% endfilter %}&ampid=42" target="_blank">hello</a>

This will apply the urlencode filter to the output URL only, and the rest of the URL will remain untouched.

You can also chain the filters as you do normally, so there isn't a need to nest the filter tags.

{% filter force_escape|lower %}

If you're looking for a way to capture the actual template output to a variable, then use the captureas template tag.

What information does Google have about me?

After signing into my Google account on my Android phone, I quickly realised how much information Google had stored on my activities online and how much it actually sync'd into my phone.

For example; Google Talk, Gmail, Picasa albums, calendar, Google Docs, AdSense, Analytics, blogspot, YouTube, Google Map locations, Google Buzz, Google Reader, Feed Burner and whatever else linked to my Google account.

Feeling a little creeped out, I stumbled upon Google Dashboard, which lets you see all the data they have on you and your digital life.

Android: Disable internet/3G connection to save battery

It's nice to be connected all the time, but when it comes to portable devices I'm quite a frugal user because of battery life. I also don't have any quota allowance on my plan.

So one of the first things I noticed was the 3G symbol was always showing (and annoying me).

The App

Luckily, there was a very handy app on the Android market called "APN on/off Widget". Once installed, edit your dashboard and add the new widget.

image

It'll give you access to a new widget on your dashboard which will enable and disable your internet connectivity. The widget itself will update to reflect the current state of your connection.

This makes it so much easier to turn it on when you need it and then back off once you're done.

The Settings

Apparently this is an Android code, so give it a shot and see if it works.

  • In the phone dialer, enter *#*#4636#*#*
  • It should take you to a new screen
  • Select "Phone Information"
  • Press Menu
  • Press More
  • Select "Disable data on boot" to stop it from automatically connecting when you start your phone.

I'm not sure if this option is permanent, but used in conjunction with the widget its a sure way of keeping in control of your battery life.

You can also use this menu to disable your connectivity, but its alot easier to just use the widget.

Sources

Samsung Galaxy S GT i9000: How to Flash firmware and remove crappy Optus apps

When I purchased an unlocked nice new Android-powered Samsung Galaxy S phone from eBay, one thing I didn't expect to find was vendor bloatware.

Optus (or Vodafone, Virgin, AT&T, Verizon, Sprint, etc) will bundle crappy apps into your phone leave their dirty brand all over it. I hate it and since I'm not even using their services, I don't need it. It's wasting my space and probably my battery too!

So, to get rid of all that crap you have one of two options; to flash or to root. Both of which sound incredibly rude :)

image image

Flashing the firmware means to completely replace it (much like formatting your computer).

To root means to gain super-user access (much like an Administrator level access) to your phone and to delete the applications manually.

I chose to flash, as it would override ANY changes made to the original Samsung firmware which may have introduced bugs. This process however does carry a higher risk of messing up your phone, so please follow instructions precisely.

IMPORTANT!

I (stupidly) forgot to back up my photos but luckily that was still on the phone after the firmware flash! Please remember to back up ALL your important data before performing this. You will lose your apps, settings, contacts, etc.

Look online for some tutorials on how to back up stuff.

Another thing to back up is your APN settings. Go to "Settings > Wireless and network > Mobile Networks > Access Point Names" and write all that information down somewhere.

Once you're ready, lets get cracking!

Hardware

  • Samsung Galaxy S GT i9000 (duh!)
  • USB cable for phone
  • A computer

Downloads

First we'll need 3 main files:

  • Odin3 v1.0 (There is v1.3 and higher, but most tutorials were using 1.0 so I went with that)
  • The selected firmware version for your region
  • The appropriate Samsung Galaxy S .pit file (when selecting your firmware file, it'll tell you which pit file to use)

All of which can be downloaded from samfirmware.com

If you have not installed "Samsung Kies" (or you just don't want to use that crap), then you'll need to get the USB drivers for the SGS so Windows can detect it properly.

Find the Kies setup (disc 1 of 2) that should of come with your phone and open up Windows Explorer. Using WinRAR or 7-zip, extract the contents of "CDROM:\Kies\CabFile\USB Driver\SAMSUNG_USB_Driver_for_Mobile_Phones.exe.cab".

When you've extracted "SAMSUNG_USB_Driver_for_Mobile_Phones.exe" extracted, run and install it. Test that your phone detects correctly by connecting it to the computer via USB.

Preparation

Once downloaded, extract Odin3 and save the pit file into the same folder.

The firmware file can stay in the .tar format after extraction.

Flashing

After backing up your current (and working) firmware, you can start the flashing process.

  • Enable USB debugging mode on your phone.
    To do that, go to Settings > Applications > Development > and tick "USB debugging".
  • Look at your phone, now back to me.
  • Turn off your phone.
  • Run Odin3 and find the:
    • .pit file by clicking on "PIT"
    • firmware .tar file by clicking on "PDA" (do not choose phone, that's for something else!)
    • Everything else can stay default
  • Now start up the phone in download mode by holding "Volume Down + Home + Power" at the same time. (If this doesn't work, see below!)

image

  • Once the phone is in download mode, Odin3 should detect it in the first available COM port slot.
  • Click "Start" to begin the flashing process.
  • The whole process of updating should take about 1 minute. Pray for that minute that your computer doesn't reboot or the power doesn't cut out.
  • The phone will restart once and initialise itself.
  • After the phone restarts and loads up properly again, you should see "All threads completed".
  • When you see your phone home screen again, it is safe to unplug the phone.
  • Now admire your own accomplishment you magnificent bastard.

image

Final steps

Lost 3G and MMS?

If you've suddenly realised that you no longer have 3G or MMS, then that means you forgot to back up the APN settings.

For Australians, you can find your APN settings for most telcos at AusDroid's APN page.

Troubles?

Stuck on "File analysis"

If you've clicked on "Start" in Odin3 and it gets stuck on "File analysis", you probably didn't put the .pit file in the same folder as Odin3.

Don't worry, it's fine to just pull the plug because it hasn't started flashing yet.

Can't get into download mode!

I thought my phone was blocked from firmware updates when I noticed this wouldn't work.

image

If your phone does not show the download mode screen, don't fret! This is merely a small obstacle in the path to victory!

It is not that your phone can't get into download mode, it's just that the "Volume Down, Home, Power" combination just won't work for certain devices.

Instead, you'll need to install the Android SDK (which is a fairly large download). Download and install. When ready, open up a Command Prompt window and type:

adb devices

This will give you a list of connected Android devices (hence why USB debugging should be enabled in step 1).

When the right device shows up in the list, type:

adb reboot download

That should restart the phone into download mode.

1283776863038

The information from Spiz in in AndroidForums.com saved me! Kudos to you Mr Internet!

Now you can continue the flashing process.

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog