Friday 10 May 2013


5 Useful Android Code Snippets

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!
01try {
02  File sdcardfile = new File(Environment.getExternalStorageDirectory() +"/example.txt");
03  fileIS = new FileInputStream(sdcardfile);
04
05  BufferedReader buffer1 = new BufferedReader(newInputStreamReader(fileIS));
06  String stringRead = new String();
07
08  while ((stringRead = buffer1.readLine()) != null) {
09    Log.d("line: ", stringRead);
10  }
11catch (FileNotFoundException e) {
12  e.printStackTrace();
13catch (IOException e) {
14  e.printStackTrace();
15}

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!
01lv1 = (ListView) findViewById(R.id.lv1);
02ArrayAdapter<CharSequence> arrayadapter = ArrayAdapter.createFromResource(this, R.array.items, android.R.layout.simple_list_item_1);
03arrayadapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
04lv1.setAdapter(arrayadapter);
05         
06lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {       
07  @Override
08  public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
09    if (position == 1) {
10      Intent intent = new Intent(getApplicationContext(), Activity2.class);
11      startActivity(intent);
12    }
13  }
14});

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!
1final Intent email_intent = new Intent(android.content.Intent.ACTION_SEND);
2email_intent.setType("plain/text");
3email_intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"to@example.com"});
4email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sample Subject Here");
5email_intent.putExtra(android.content.Intent.EXTRA_TEXT, "Put Your Text Here");
6
7context.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.
1Display d1 = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
2
3int w = d1.getWidth();
4int h = d1.getHeight();
5int 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!
01ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
02
03NetworkInfo info = manager.getActiveNetworkInfo();
04
05if (info != null) {
06  if (info.isConnected()) {
07    // put your code here
08  else {
09    AlertDialog.Builder alert = new AlertDialog.Builder(this);
10    alert.setTitle("Connectivity");
11    alert.setMessage("No Connectivity");
12    alert.setNeutralButton("Ok", okClickListener);
13    alert.show();
14  }
15}
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!

No comments:

Post a Comment