Search code examples
androidandroid-serviceandroid-fileandroid-networkingandroid-intentservice

Image download failed when try to download by using IntentService in Android


I am trying to download a image by using AsynckTask but it doesn't give an Image. My ProgressBar is showing a progress as long as i keep up the application but do not load the image.

This is the UI design of my application:

enter image description here

MainActivity:

Java

public class MainActivity extends AppCompatActivity {
    ImageView img;
    Button btn;
    EditText edt;
    ProgressBar prb;
    SampleResultReceiver sampleResultReceiver;
    String defalut_url="http://9xmobi.com/image/15580/size/128x128/KAJOL(12)%5B9xmobi.com%5D.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        img=(ImageView)findViewById(R.id.image_view);
        setContentView(R.layout.activity_main);
        edt=(EditText)findViewById(R.id.urlid);
        btn=(Button)findViewById(R.id.button);
        prb=(ProgressBar)findViewById(R.id.progress);
    }
    public void click(View view){
        Intent intent=new Intent(MainActivity.this,MyIntentServiceActivity.class);
        intent.putExtra("receiver",sampleResultReceiver);
        intent.putExtra("url", TextUtils.isEmpty(edt.getText())?defalut_url:edt.getText().toString());
        startService(intent);
        prb.setVisibility(View.VISIBLE);
        prb.setIndeterminate(true);
    }
    class SampleResultReceiver extends ResultReceiver {
        /**
         * Create a new ResultReceive to receive results.  Your
         * {@link #onReceiveResult} method will be called from the thread running
         * <var>handler</var> if given, or from an arbitrary thread if null.
         *
         * @param handler
         */
        public SampleResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            switch (resultCode){
                case MyIntentServiceActivity.DOWNLOAD_ERROR:
                    Toast.makeText(getApplicationContext(), "error in download",
                            Toast.LENGTH_SHORT).show();
                    prb.setVisibility(View.INVISIBLE);
                    break;
                case MyIntentServiceActivity.DOWNLOAD_SUCCESS:
                    String file_path=resultData.getString("file_path");
                    Bitmap bmp= BitmapFactory.decodeFile(file_path);
                if (img!=null&&bmp!=null){
                    img.setImageBitmap(bmp);
                    Toast.makeText(getApplicationContext(),
                            "image download via IntentService is done",
                            Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(getApplicationContext(),
                            "error in decoding downloaded file",
                            Toast.LENGTH_SHORT).show();
                }
                    prb.setIndeterminate(false);
                    prb.setVisibility(View.INVISIBLE);

                    break;

            }
            super.onReceiveResult(resultCode, resultData);
        }
    }
}

And My Service Class is...

Java

public class MyIntentServiceActivity extends IntentService {
    public static final int DOWNLOAD_ERROR=10;
    public static final int DOWNLOAD_SUCCESS=11;
    int byteCount=0;
    public MyIntentServiceActivity(){
        super(MyIntentServiceActivity.class.getName());

    }
    @Override
    protected void onHandleIntent(Intent intent) {
        String path=intent.getStringExtra("url");
        final ResultReceiver receiver=intent.getParcelableExtra("receiver");
        Bundle bundle=new Bundle();
        File internal_root= Environment.getExternalStorageDirectory();
        //File new_folder=new File("sdcard0/IntentService_Example");
        //if (!new_folder.exists()){
          //  new_folder.mkdir();
       // }
        File new_file=new File(internal_root,"download_image.jpg");
        try {
            URL url=new URL(path);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();
            int responseCode=connection.getResponseCode();
            if (responseCode!=200)
                throw new Exception("Error in connection");
            InputStream is=connection.getInputStream();
            OutputStream fos=new FileOutputStream(new_file);
           byte[] buffer=new byte[1024];
            int count=0;
            while ((count=is.read(buffer))>0){
                fos.write(buffer,0,count);
            }
            fos.close();
            String file_path=new_file.getPath();
            bundle.putString("file_path",file_path);
            receiver.send(DOWNLOAD_SUCCESS,bundle);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Where is my mistake here? please point me in the right direction.


Solution

  • When your sending the Sample Result Receiver instance to Your Service class,Your not sending an object of the sample result receiver class infact Your sending a null pointer to the service class.

    You must try doing this.

    public void click(View view){
    sampleResultReceiver = new SampleResultReceiver();
            Intent intent=new Intent(MainActivity.this,MyIntentServiceActivity.class);
            intent.putParceleableExtra("receiver",sampleResultReceiver);
            intent.putExtra("url", TextUtils.isEmpty(edt.getText())?defalut_url:edt.getText().toString());
            startService(intent);
            prb.setVisibility(View.VISIBLE);
            prb.setIndeterminate(true);
        }