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;
}
}
2 Answers 2
I'm not too familiar with Android, so the following is just some generic Java notes:
Fields
roseUrl
andaq
seem unused as well as thependingIntent
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 whetherBitmapFactory.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. IfBitmapFactory.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 LanguageThe 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.
-
1\$\begingroup\$ Thanks for the answer, I really appreciate it. I cleaned up the code a bit. I cannot find a close for the IS in any of the documentation.... hmmmm.... \$\endgroup\$jasonflaherty– jasonflaherty2013年01月31日 22:26:27 +00:00Commented Jan 31, 2013 at 22:26
Bad variable names. Please do not use things like
N
,i
, andf
(and if you are, at least be consistent and make them all lowercase). Thataq
is questionable as well.Using
for (int appWidgetId : appWidgetIds)
would save you a couple lines, and get rid of that atrociousi
andN
variables as well.Personally I wouldn't bother declaring
N
asfinal
(or at all, since you could just as easily useappWidgetIds.length
in yourfor
loop condition even if you don't do #2) unless there is reason to. Like if you're going to refer to it from an anonymous class. Note that if you do #2 above,N
goes away completely.Close your
FileInputStream
. Instead of doingFile f = ...
doFileInputStream input = new FileInputStream(new File("/storage/..."));
and theninput.close();
when you are done with it.