Загружать изображения в Html.fromHtml в textview (JSON String)
У меня проблема с загрузкой изображений с веб-сайта в TextView с использованием синтаксического анализа строки JSON. Я пытался загрузить изображения с помощью Html.ImageGetter и BitmapDrawable. Я видел эти ссылки Загрузите изображения в Html.fromHtml в textview (изображения http URL, изображения url Base64) и Android HTML ImageGetter как AsyncTask
Я не понимаю, почему у меня исключение нулевого указателя. Я пытаюсь загрузить строку "content" с http://techmasi.com/wp-json/posts этой ссылки JSON.
Вот мои коды
public class URLDrawable extends BitmapDrawable {
// the drawable that you need to set, you could set the initial drawing
// with the loading image if you need to
protected Drawable drawable;
@Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if(drawable != null) {
drawable.draw(canvas);
}
}}
Вот еще один класс:
public class URLImageParser implements Html.ImageGetter {
Context context;
TextView container;
public URLImageParser(TextView t, Context c) {
this.context = c;
this.container = t;
}
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
// get the actual source
ImageGetterAsyncTask asyncTask =
new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
// return reference to URLDrawable where I will change with actual image from
// the src tag
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
@Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
Log.d("height", "" + result.getIntrinsicHeight());
Log.d("width",""+result.getIntrinsicWidth());
urlDrawable.setBounds(0, 0, 0+result.getIntrinsicWidth(), 0+result.getIntrinsicHeight());
// change the reference of the current drawable to the result
// from the HTTP call
urlDrawable.drawable = result;
// redraw the image by invalidating the container
URLImageParser.this.container.invalidate();
// For ICS
URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
+ result.getIntrinsicHeight()));
// Pre ICS
URLImageParser.this.container.setEllipsize(null);
}
}
public Drawable fetchDrawable(String urlString) {
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
return drawable;
} catch (Exception e) {
return null;
}
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}}
Я получаю исключение Null Pointer в следующей строке:
urlDrawable.setBounds(0, 0, 0+result.getIntrinsicWidth(), 0+result.getIntrinsicHeight());
Выход Logcat:
java.lang.NullPointerException
at com.droiddigger.techmasi.URLImageParser$ImageGetterAsyncTask.onPostExecute(URLImageParser.java:64)
at com.droiddigger.techmasi.URLImageParser$ImageGetterAsyncTask.onPostExecute(URLImageParser.java:48)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Пожалуйста помоги. Заранее спасибо.
1 ответ
Я бы порекомендовал не использовать Drawable.createFromStream(). Это по сути не документировано и не делает то, что вам нужно. Бьюсь об заклад, он возвращает ноль.
Если вам нужно декодировать растровое изображение из InputStream, которое содержит PNG, JPG, GIF или другой поддерживаемый Android тип изображения, попробуйте BitmapFactory.decodeStream (), а затем создайте Drawable из этого растрового изображения.