Category Archives: ANDROID

(Android) Delay method call

This is how you could delay a method call for a given amount of time. I’ve used this to have an alert dialog pop up a few second after starting an activity.

This will fire myMethod() after 3000 miliseconds:

				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						myMethod();			
					}}, 3000);

(Android) Check if Google Play Store is installed on device

Here’s a quick way to check if Google Play Store is installed. I use this to keep activities that use in-app billing from crashing on devices that doesn’t have Google Play Store. Works fine in the emulator as well. If the method returns false, I’ll just give the user an alert telling them they need Google Play for in-app billing. If it returns true the in-app billing system gets set up.

Here, implemented in a static method. If you call this from an activity you go:

boolean myBoolean = googlePlayStoreInstalled(this);

and if you’re in a fragment or so just go

boolean myBoolean = googlePlayStoreInstalled(getActivity());

I keep this in a utility class.

 
	public static boolean googlePlayStoreInstalled(Activity activity) {

		PackageManager packageManager = activity.getApplication().getPackageManager();
		List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);

		for (PackageInfo packageInfo : packages)
			if (packageInfo.packageName.equals(GooglePlayStorePackageNameOld) || packageInfo.packageName.equals(GooglePlayStorePackageNameNew))
				return true;

		return false;
	}

(Android) Simple confirm dialog

	
private void confirmDialog() {		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
				
		builder
		.setMessage("Are you sure?")
		.setPositiveButton("Yes",  new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				// Yes-code
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();
			}
		})
		.show();
	}

(Android) Find physical screen size programatically

This method will find out if screen is a tablet size.

You could of course make this even more corner case-compliant by getting the units dpi (dot per inch) and use the Pythagorean theorem to find the actual inch size of the diagonal. But this will probably suffice for most case.

	private boolean isLargeScreen() {
		
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);	
		
		// Get the density of the screen (dp)
		float density = metrics.density;		
		
		// Find out if the smallest of x/y is largeer than 600 (7" tablet. For 10" use 720)
		return Math.min(metrics.widthPixels / density,  metrics.heightPixels / density) > 600;
	}

(Android) Custom view orientation change – restore state.

Here’s one pretty simple way to get your custom view to restore its current state after an orientation change:
You can of course put any values in there, for example if you need to restore fields.

(quickly plotted code. Haven’t run it, but it should work)

@Override
protected Parcelable onSaveInstanceState() {
	Bundle bundle = new Bundle();
	bundle.putParcelable("instanceState", super.onSaveInstanceState());
	bundle.putString("myString", myEditText.getText().toString());
	return bundle;
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
	if (state instanceof Bundle) {
		Bundle bundle = (Bundle) state;
		myEditText.setText(bundle.getString("myString"));
		state = bundle.getParcelable("instanceState");
	}
	super.onRestoreInstanceState(state);
}

(Android) Change background of a bitmap

  1. Create a new bitmap, with the size and config of the bitmap you wish to change.
  2. Create a Canvas and prepare it to paint to the new bitmap.
  3. Paint the new bitmap with your color using the canvas object.
  4. Draw the old bitmap to the new bitmap through the canvas object.
  5. Do what you want with the new bitmap
// Create new bitmap based on the size and config of the old
Bitmap newBitmap = Bitmap.createBitmap(oldBitmap.getWidth(), oldBitmap.getHeight(), oldBitmap.getConfig()); 

// Instantiate a canvas and prepare it to paint to the new bitmap
Canvas canvas = new Canvas(newBitmap);

// Paint it white (or whatever color you want)
canvas.drawColor(Color.WHITE);

// Draw the old bitmap ontop of the new white one
canvas.drawBitmap(oldBitmap, 0, 0, null);

(Android) Convert Density-independent Pixels to Pixels (dp 2 px)

 

A simple function to convert dp into pixels. Use when you have to pass pixels to a method and want to keep everything to scale.

private int dp2px(int dp) {
    float scale = getResources().getDisplayMetrics().density;
    int pixels = (int) (dp * scale + 0.5f);
    return pixels;
}

From Android Developer Center :

px
Pixels – Corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.

dp
Density-independent Pixels – An abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen’s dpi. Likewise, when on a lower density screen, the number of pixels used for 1dp is scaled down. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. In other words, it provides consistency for the real-world sizes of your UI elements across different devices.

 

 

(Android) NumberPicker with leading zero

Set your number picker to show leading zeros by applying a formatter to it.
Example is using an anonymous instance, but of course it doesn’t have to.

myNumberPicker.setFormatter(new NumberPicker.Formatter() {
			@Override
			public String format(int value) {
				return String.format("%02d", value);
			}
		});

For %02d this goes:

  • 0 for filling with zeros
  • 2 for length of 2