0

In the AsyncTask, I am getting a json with some of the values as images. Below is the sample of my json

{ 
  "text": "some text",
  "html1": "Hi, check out my fb profile picture at <img src = 'http:\/\/abc.com/image1.png'\/> ",
  "html2": "Hi, check out my whatsapp profile picture at <img src = 'http:\/\/abc.com\/image1.png'\/> ",
   .
   .
   .
}

In async task postExecute Method I have

( ( TextView ) findViewById( R.id.html1 ) ).setText( Html.fromHtml( ( String ) jsonObj.get( "html1" ), new ImageGetter()
{
    @Override
    public Drawable getDrawable( String source )
    {
        return loadImage( source );
    }
}, null ) );
 ( ( TextView ) findViewById( R.id.html2) ).setText( Html.fromHtml( ( String ) jsonObj.get( "html2" ), new ImageGetter()
    {
        @Override
        public Drawable getDrawable( String source )
        {
            return loadImage( source );
        }
    }, null ) );

and my loadImage method looks like below

private Drawable loadImage( String source )
    {
        Drawable drawable = null;
        URL sourceURL;
        try
        {
            sourceURL = new URL( source );
            URLConnection urlConnection = sourceURL.openConnection();
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream( inputStream );
            Bitmap bm = BitmapFactory.decodeStream( bufferedInputStream );

            // convert Bitmap to Drawable
            drawable = new BitmapDrawable( getResources(), bm );

            drawable.setBounds( 0, 0, bm.getWidth(), bm.getHeight() );

        }
        catch ( MalformedURLException e )
        {
            e.printStackTrace();
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
        return drawable;
    }

I think the code is suffice but I am getting android.os.NetworkOnMainThreadException

I have added the internet permission in manifest.xml

Abhijith Nagaraja
  • 3,370
  • 6
  • 27
  • 55

2 Answers2

0

it looks like that the json format for the url cause all the trouble

there is a great post on that issue: Decode Json urls

but it end up with dead links.. so.. a little bit of googling around and: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

you should unescape your url string with the unescapeJavaScript function to get a proper url

Community
  • 1
  • 1
ymz
  • 6,602
  • 1
  • 20
  • 39
0

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask

public class MainActivity extends Activity implements ImageGetter {
    private final static String TAG = "MainActivity";
    private TextView mTv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String source = <your source from json here>;

        Spanned spanned = Html.fromHtml(source, this, null);
        mTv = (TextView) findViewById(R.id.text);
        mTv.setText(spanned);
    }

    @Override
    public Drawable getDrawable(String source) {
        LevelListDrawable d = new LevelListDrawable();
        Drawable empty = getResources().getDrawable(R.drawable.ic_launcher);
        d.addLevel(0, 0, empty);
        d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());

        new LoadImage().execute(source, d);

        return d;
    }

    class LoadImage extends AsyncTask<Object, Void, Bitmap> {

        private LevelListDrawable mDrawable;

        @Override
        protected Bitmap doInBackground(Object... params) {
            String source = (String) params[0];
            mDrawable = (LevelListDrawable) params[1];
            Log.d(TAG, "doInBackground " + source);
            try {
                InputStream is = new URL(source).openStream();
                return BitmapFactory.decodeStream(is);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            Log.d(TAG, "onPostExecute drawable " + mDrawable);
            Log.d(TAG, "onPostExecute bitmap " + bitmap);
            if (bitmap != null) {
                BitmapDrawable d = new BitmapDrawable(bitmap);
                mDrawable.addLevel(1, 1, d);
                mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                mDrawable.setLevel(1);
                // i don't know yet a better way to refresh TextView
                // mTv.invalidate() doesn't work as expected
                CharSequence t = mTv.getText();
                mTv.setText(t);
            }
        }
    }
}

Or: Add StrictMode code in OnCreate under setContentView(...);

StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);

But adding StrictMode.ThreadPolicy is a bad practise