HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Android widget code

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
codewidgetandroid

Problem

Anyone have any comments? Just trying to better my code if can be done.

public class SacWidget extends AppWidgetProvider {
    String roseUrl;
    AQuery aq;

    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {
            int appWidgetId = appWidgetIds[i];
            Intent intent = new Intent(context, DangerRose.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                    intent, 0);
            RemoteViews views = new RemoteViews(context.getPackageName(),
                    R.layout.widget_layout);
            views.setImageViewBitmap(R.id.ivdangerrose, getRose());
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }

    private Bitmap getRose() {
        Bitmap bitmap = null;
        File f = new File("/storage/emulated/0/acr/sac/dangerrose.png");
        try {
            bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return bitmap;
    }
}

Solution

I'm not too familiar with Android, so the following is just some generic Java notes:

-
Fields roseUrl and aq seem unused as well as the pendingIntent local variable. You might remove them.

-
You could use a foreach loop:

for (final int appWidgetId: appWidgetIds) ...


-
It isn't the best idea to use printStackTrace() in Android exceptions.

-
The getRose() method creates a stream (new FileInputStream(f)). I'm not sure whether BitmapFactory.decodeStream closes it before it returns or not. If not, you should close it.

Notes for the edit:

-
You should close the stream in a finally block. If BitmapFactory.decodeStream throws an exception it won't be closed. See Guideline 1-2: Release resources in all cases in Secure Coding Guidelines for the Java Programming Language

-
The following two lines are duplicated:

File ext = Environment.getExternalStorageDirectory();
File file = new File(ext,"acr/sac/dangerrose.png");


You could extract them out to a method.

Code Snippets

for (final int appWidgetId: appWidgetIds) ...
File ext = Environment.getExternalStorageDirectory();
File file = new File(ext,"acr/sac/dangerrose.png");

Context

StackExchange Code Review Q#21131, answer score: 3

Revisions (0)

No revisions yet.