5 Useful Android Code Snippets

January 12th, 2013 Leave a comment
Like the article?
5 useful android code snippets

Sometimes it’s hard to make Android programs without trying to reinvent the wheel: often there are simple tasks that aren’t obvious at the start, and it can be more trouble than it’s worth writing them from scratch. To help make your code writing process easier, here are 5 Android code snippets for some common tasks that may not be obvious!

1. Reading a Text File from A Device SD Card

This one is a snippet that’s often used simply because it’s a common use case- the way to do it, however, isn’t always obvious. Here’s a snippet to help you read a text file from a device’s SD card!

try {
  File sdcardfile = new File(Environment.getExternalStorageDirectory() + "/example.txt");
  fileIS = new FileInputStream(sdcardfile);

  BufferedReader buffer1 = new BufferedReader(new InputStreamReader(fileIS));
  String stringRead = new String();

  while ((stringRead = buffer1.readLine()) != null) {
    Log.d("line: ", stringRead);
  }
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

2. Start A New Activity On-Click In List View

As with the above example, you’ll often need to start a new activity in a list view but it’s not always obvious how to do so. Here’s the quick workaround you need to start a new activity on-click in a list view!

lv1 = (ListView) findViewById(R.id.lv1);
ArrayAdapter<CharSequence> arrayadapter = ArrayAdapter.createFromResource(this, R.array.items, android.R.layout.simple_list_item_1);
arrayadapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
lv1.setAdapter(arrayadapter);
        
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {        
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    if (position == 1) {
      Intent intent = new Intent(getApplicationContext(), Activity2.class);
      startActivity(intent);
    }
  }
});

3. Send Emails From Within Your App

Users often like the ability to get in touch with developers from within the app. Use this snippet to start up the email activity with pre-inputted strings!

final Intent email_intent = new Intent(android.content.Intent.ACTION_SEND);
email_intent.setType("plain/text");
email_intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"to@example.com"});
email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sample Subject Here");
email_intent.putExtra(android.content.Intent.EXTRA_TEXT, "Put Your Text Here");

context.startActivity(Intent.createChooser(email_intent, "Send An Email"));

4. Get The Size And Orientation Of Your Display

It can be extremely useful in any app to know the size / orientation of your display- here’s a code snippet to grab it and figure that out.

Display d1 = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();

int w = d1.getWidth();
int h = d1.getHeight();
int o = d1.getOrientation();

5. Check For Network Connectivity

This one is also a fairly common need in Android devices, and you’d think there would be an easier way to do it. The actual code is a bit long, however – here it is in all its glory!

ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo info = manager.getActiveNetworkInfo();

if (info != null) {
  if (info.isConnected()) {
    // put your code here
  } else {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Connectivity");
    alert.setMessage("No Connectivity");
    alert.setNeutralButton("Ok", okClickListener);
    alert.show();
  }
}

Keep these five snippets handy in your Android toolchest and I’m sure you’ll use them from time to time instead of doing redundant Google searches!

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
If you liked this article, consider enrolling in one of these related courses:
Don't miss another post! Receive updates via email!

Comment