Basic Android app functions


How to do some of the most basic things in android to start building an app that is useful

Updated June 13, 2017

Android is a departure from normal Java development. While some things are very similar, there are pitfalls that can be hard to get past. Here are a few helpers that will help you build a useful android application.

A Note on context:

Throughout these tips I use 'view.getContext()'. That was the form the the context was retrieved for the applications that the code below was take from. You will most likely need to replace this with the correct context.

Show a simple toast message

Toasts are really easy to create, so here's the code:

CharSequence text = "Toast message";
int duration = Toast.LENGTH_LONG;

Toast toast = Toast.makeText(view.getContext(), text, duration);
toast.show();

As you can see, creating a toast is pretty simple. The only hang up you might have is:

view.getContext()

In the case above, 'view' is an instance of the 'View' class. If you are creating a toast from the main activity, you should be able to replace 'view.getContext()' with 'this'. If you have further issues you should read up on 'context' as it pertains to an Android application. It will help you in the future to understand this.

Show a confirmation alert box

Confirmation alert boxes are pretty easy to make. Its easy to understand why you'd want to make one. You need to confirm before deleting something or before navigating away from something , right? Here's the code:

new AlertDialog.Builder(view.getContext())
        .setTitle("Delete Course")
        .setMessage("Do you really want to delete this course?")
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                 // do 'yes' actions here
              }})
          .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                 // do 'no' actions here
              }}).show();

You don't have to write it so ugly as I have above, but this is all you need. Note again, the 'view.getContext()'. You will need to most likely replace that with the correct context.

Open the camera and save a picture to local storage

This one is a bit more complicated. You need permissions for this. First open the AndroidManifest.xml and and the following inside '<manifest...>' :

<uses-feature android:name="android.hardware.camera"
    android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

next you need to place the following code in a file in your application res/xml/provider_paths.xml . If the 'xml' folder doesn't exist, create one.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Now you need to go back to your AndroidManifest.xml and create a provider reference inside the '<Application...>':

<provider android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

Now you need to actually build the function

static final int REQUEST_IMAGE_CAPTURE = 1;
Uri uriSavedImage= null;

private void dispatchTakePictureIntent(View view){
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(this.getActivity().getPackageManager()) != null) {
        try {
            uriSavedImage = FileProvider.getUriForFile(view.getContext(), view.getContext().getApplicationContext().getPackageName() + ".provider", createImageFile(view));
        } catch (IOException e) {
            e.printStackTrace();
        }
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
        startActivityForResult(takePictureIntent, 1);
    }
}

The above function will open the camera and allow you to take a picture. When you return to your app the image will be saved on your local storage at the uri location 'uriSavedImage'.

So what if you want to show the picture in the app after you've taken it? Use the following in the activity:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    if(resultCode != RESULT_CANCELED) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            //uriSavedImage
            imageView.setImageURI(uriSavedImage);
        }
    }
}

The above code will be run after a picture is taken and you've returned to the app. the 'imageView' is an Android instance of ImageView. Since the 'uriSavedImage' is storing the image uri at this point, now you can use that uri to display the image. If you plan on storing the image in a database for later use, you can simply save the uriSavedImage as a string. When you need the Uri later, you can use 'Uri.parse(..)' to get the reference to the image.

Create notifications

Its no surprise that creating notifications is easy. After all, every app you use probably pushes you some awful notification about something you marginally care about. That being said, here's how to make your own:

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(view.getContext())
                .setSmallIcon(R.drawable.ic_add_circle_outline_black_24dp)
                .setContentTitle("Course Due for completion")
                .setContentText("course is due to be completed today.");
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
        (NotificationManager) view.getContext().getSystemService(view.getContext().NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());

There are other features about creating background services that run so that you can push these notifications when your app isn't open, but the above is the basic approach.

Create a share button

Sharing stuff on Android is dead simple. Here's the code:

String shareBody = "text to be shared";  
Uri image_uri = ...; // replace with an actual image uri
final Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");

sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share subject here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, image_uri); // only use this line if you're sharing an image

Button shareNote = new Button(view.getContext());
shareNote.setText("Share Note");
shareNote.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v){
        startActivity(Intent.createChooser(sharingIntent, "Share via"));
    }
});

The above code will allow you to share with any app that has a sharing feature on your phone. Enjoy.


Topics