I'm learning the ropes with Android development, so forgive me, and I'm struggling to do something pretty fundamental.
I'm trying to fetch an image from a remote URL and put it into an ImageView. The ImageView itself is within an app widget.
But the image never loads, and a ton of errors are returned.
I created the app widget code using Android Studio's context menu, so the building blocks are, I think, sound. I created an ImageView in the app widget's layout in place of the TextView that was there by default.
Here is all the relevant code:
layout/new_app_widget.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/widget_margin" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:contentDescription="@string/content" />
</RelativeLayout>
relevant bit from NewAppWidget.java:
public class NewAppWidget extends AppWidgetProvider {
...
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
String strURL = "http://example.com/YqLOSfr4.png";
try{
URL urlURL = new URL(strURL);
HttpURLConnection con = (HttpURLConnection)urlURL.openConnection();
InputStream is = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
views.setImageViewBitmap(R.id.imageView, bmp);
} catch(Exception e) {
e.printStackTrace();
}
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.widgetapptest" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:debuggable="true"
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".NewAppWidget" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/new_app_widget_info" />
</receiver>
</application>
</manifest>