This code below is outdated, it is for reference only
For more accurate code snippets and helpers I made a lib
Check it out here https://github.com/jrmgx/android

Helpers

// Parse colors
public static int parseColor (String colorString)

// Toast
CharSequence text = "Hello toast!";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();

Android has a ThumbnailUtils class to help create video and image thumbnail! check it out!

Shell and misc

adb shell then run-as com.*.* ls -la

Local loop is 10.0.2.2

Provide Alternative Bitmaps

Since Android runs in devices with a wide variety of screen densities, you should always provide your bitmap resources tailored to each of the generalized density buckets: low, medium, high and extra-high density. This will help you achieve good graphical quality and performance on all screen densities.

To generate these images, you should start with your raw resource in vector format and generate the images for each density using the following size scale:

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi and finally a 75x75 image for ldpi devices.

Query

return this.getReadableDatabase().query(
    DB_TABLENAME,
    new String[]{"*", "COUNT(*) AS " + FIELD_CALCUL_TOTAL},
    null,
    null,
    FIELD_USER_ID, // Group by
    null,
    null);

Method on cursor

Move in a cursor

if (cursor.moveToFirst()) {
    while (cursor.isAfterLast() == false) {
        //code
        cursor.moveToNext();
    }
}

Thread and delays

Please use AsyncTask

Start a method after a delay

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something after 100ms
    }
}, 100);

Open an URL

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(i);

Pass information from activity to fragment

From Activity you send data with intent as:

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

Pass information between activities

fist in the parent activity:

String EXTRA_USER_ID = "com.example.data/userId";
Intent i = new Intent(ListActivity.this, ShowActivity.class);
i.putExtra(EXTRA_USER_ID, userId);
startActivity(i);

then in the child activity:

int useId = getIntent().getExtras().getInt(EXTRA_USER_ID);  

Get information back from sub activity

first in the parent activity:

static final int REQUEST_CODE = 1;

public void buttonAction(View v) {
    startActivityForResult(new Intent(...), REQUEST_CODE);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == REQUEST_CODE) {
         if (resultCode == RESULT_OK) {
            data.getExtra(...);
         } else {
             // was canceled
         }
     }
 }

then in the child activity:

...
Intent result = new Intent();
result.putExtra(...);
setResult(Activity.RESULT_OK, result);
finish();

Intent for email

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
    "mailto","[email protected]", null
));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "EXTRA_SUBJECT");
startActivity(Intent.createChooser(emailIntent, "Send email..."));

Content observer for contact

Cursor cursor = getContentResolver().query(
    ContactsContract.Contacts.CONTENT_URI,
    new String[] { ContactsContract.Contacts.LOOKUP_KEY }, null, null, null
);

if (cursor.getCount() > 0) {
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        Uriuri = Uri.withAppendedPath(
            ContactsContract.Contacts.CONTENT_LOOKUP_URI,
            Cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY))
        );
        Handler handler = new Handler();
        Message msg = handler.obtainMessage(1, uri);
        handler.sendMessage(msg);
        getContentResolver().registerContentObserver(uri, false, new ContactObserver(handler));
        cursor.moveToNext();
    }
}

Files

Create a file to cache data

byte[] b = ...;
File f = new File(context.getCacheDir(), "file-name"");
BufferedOutputStream bos;
try {
    bos = new BufferedOutputStream(new FileOutputStream(f));
	bos.write(b);
    bos.flush();
	bos.close();
} catch (FileNotFoundException e) {
    Utils.err("FileNotFoundException while file attribution");
} catch (IOException e) {
    Utils.err("IOException while writing cache file");
}

Read file to byte

byte[] b = FileUtils.readFileToByteArray(new File(...));

Delete file

File file = new File(path);
file.delete();

Views

Density

Get root view from activity

((ViewGroup) findViewById(android.R.id.content)).getChildAt(0)

zindex

The last child of a FrameLayout or a RelativeLayout is on top
It is useful to make overlays

Remove a view from its parent

((ViewGroup) view.getParent()).removeView(view);

Spacing in ListView

<ListView android:id="@+id/MyListView"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="10.0dp"/>

Layout weighting

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/timeButton"
        android:layout_width="match_parent"
        android:layout_height="0sp"
        android:layout_weight="10"

        android:text="X seconds" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0sp"
        android:layout_weight="26" >

        ...

Rounded corner

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#FFFFFF"/>
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp"/>
</shape>

Get Drawables

Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
Drawable d = getResources().getDrawable(getResources().getIdentifier("image"+id, "drawable", getPackageName()));

Input text changed listener

 searchText.addTextChangedListener(new TextWatcher() {
      @Override
      public void afterTextChanged(Editable editable) {
           String value = editable.toString();
           if (value.length() > 0) {
                searchFor(value);
                editable.clear();
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                     imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);//InputMethodManager.HIDE_IMPLICIT_ONLY?
           }
      }

      public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
      public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
 });

Animations

Make an animation

ObjectAnimator anim1 = ObjectAnimator.ofFloat(mainView, "x", x, x + envergure);
anim1.setDuration(time);
anim1.start()

Execute animations in order

AnimatorSet bouncer = new AnimatorSet();
bouncer.play(anim1).with(anim2);
bouncer.play(show).after(anim1);
//bouncer.play(anim1b).with(anim2b);
//bouncer.play(anim1b).after(show);
bouncer.start();  

Execute something after an animation

ObjectAnimator anim = ObjectAnimator.ofFloat(view, "alpha", 0.0f);
anim.addListener(new AnimatorListener() {
    ...
    @Override
    public void onAnimationEnd(Animator animation) {
        animDrawable.stop()
    }
    ...
});
anim.setDuration(300).start();

Use a custom font

The font must be in assets/fonts

Typeface font = Typeface.createFromAsset(getAssets(), "fonts/bebas.ttf");
((TextView) findViewById(R.id.textPokeAFriend)).setTypeface(font);

note: It is not possible to use custom font in XML

edit this page