Results 1 to 8 of 8
  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default AsyncTask problem

    Java Code:
    package com.example.concurrency;
    
    import java.io.InputStream;
    import java.net.URL;
    
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.widget.ImageView;
    
    public class UsingAsyncTask extends Activity {
    	ImageView imageView;
    	
    	@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.using_asynctask); 
            String spec="http://www.google.com/imgres?imgurl=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F7%2F7a%2FBasketball.png&imgrefurl=http%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ABasketball.png&h=340&w=340&tbnid=EJmjEDyJzrhAuM%3A&zoom=1&docid=C_hn8nOgsGmuwM&hl=en&ei=Q0o2U93LNcaIygH4mICQBQ&tbm=isch&ved=0CHwQhBwwBg&iact=rc&dur=3875&page=1&start=0&ndsp=14";
            try {URL params= new URL(spec);} catch(Exception e) {}
            //Bitmap result;
            new MyTask().execute(params);
            imageView= new ImageView(null);
    	}
    	
    	private class MyTask extends AsyncTask<URL, Void, Bitmap> {
    		
    		private Bitmap loadImageFromNetwork(String url){
                try {
                Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
                return bitmap;
                } catch (Exception e) {
                e.printStackTrace();
                }
                return null;
            }
    		
    		protected void onPreExecute() {
    			
    		}
    		
    		
    		protected Bitmap doInBackground(URL... params){
    			//if(isCancelled()) return;
    			String url=params[0].toString();
    			final Bitmap bitmap= loadImageFromNetwork(url);
    			return bitmap;
    		}
    
    		/*protected void onProgressUpdate(Progress progress){
    			setProgressPercent(progress[0]);
    		}*/
    		 
    		protected void onPostExecute(Bitmap result){
    			imageView.setImageBitmap(result);
    		}
    
    	}
    	
    }
    This is the first program I was writing to practice using an AsyncTask. I failed to resolve this error, I tried to do a few suggested fixes, but that brought errors in the previous line. So I'll be thankful if somebody can suggest me how to fix it.

    I just added this question to stackoverflow.com as well. It can be found here.

    Edit:-

    This question is resolved here. params was out of scope because it is inside a try statement. It can be corrected by:

    Java Code:
    URL params;
       try {
         params = new URL(spec);
       }
    Last edited by Zarah; 04-03-2014 at 06:58 AM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,086
    Rep Power
    20

    Default Re: AsyncTask problem

    Java Code:
    try {URL params= new URL(spec);} catch(Exception e) {}
    Even moving the params declaration out of the try/catch will not solve this issue, though. If there's an exception you will never know, since you aren't logging it. In addition I would argue that an exception thrown while trying to create the URL should signal your code to give up rather than plow on and then fail later on during the task execution.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: AsyncTask problem

    Quote Originally Posted by Tolls View Post
    If there's an exception you will never know, since you aren't logging it.
    Right! I logged it and now trying to deal with an exception. It is actually a ClassNotFoundException at line # 56.

    In addition I would argue that an exception thrown while trying to create the URL should signal your code to give up rather than plow on and then fail later on during the task execution.
    It is a MalformedURLException. According to this documentation, "This exception is thrown when a program attempts to create an URL from an incorrect specification."

    You are right but I had thought that it won't be thrown since the url is a valid one (and I was just concentrating on understanding the steps of AsyncTask's execution, and not on the URL for the moment).

    And it does not seem to be thrown. Please tell me if you think this exception might be thrown and somehow causing a ClassNotFoundException at line number 56.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,086
    Rep Power
    20

    Default Re: AsyncTask problem

    Well, a MalformedURL will mean your url object is null.
    And anything can happen from that point.
    So fix the URL.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: AsyncTask problem

    Well, a MalformedURL will mean your url object is null.
    And anything can happen from that point.
    So fix the URL.
    I'll be in a better state to fix it once I am really clear about the basics of exceptional handling and Log.something thingy. But following is the code which produces the excepted result. The MalformedURLException was not thrown, if it is thrown, it will need to be handled. So I admit this code needs it.

    Java Code:
    package com.example.concurrency;
    
    import java.io.InputStream;
    import java.net.URL;
    
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.widget.ImageView;
    
    public class UsingAsyncTask extends Activity {
    	ImageView imageView;
    	
    	@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.using_asynctask); 
            String spec="http://upload.wikimedia.org/wikipedia/commons/7/7a/Basketball.png";
            URL params = null;
            try {params= new URL(spec);} catch(Exception e) {}
            //Bitmap result;
            new MyTask().execute(params);
            imageView= (ImageView) findViewById(R.id.imageview);
    	}
    	
    	private class MyTask extends AsyncTask<URL, Void, Bitmap> {
    		
    		private Bitmap loadImageFromNetwork(String url){
                try {
                Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
                return bitmap;
                } catch (Exception e) {
                e.printStackTrace();
                }
                return null;
            }
    		
    		/*protected void onPreExecute() {
    			
    		}*/
    		
    		@Override 
    		protected Bitmap doInBackground(URL... params){
    			//if(isCancelled()) return;
    			String url=params[0].toString();
    			final Bitmap bitmap= loadImageFromNetwork(url);
    			return bitmap;
    		}
    
    		/*protected void onProgressUpdate(Progress progress){
    			setProgressPercent(progress[0]);
    		}*/
    		
    		@Override 
    		protected void onPostExecute(Bitmap result){
    			imageView.setImageBitmap(result);
    		}
    
    	}
    	
    }

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,086
    Rep Power
    20

    Default Re: AsyncTask problem

    Quote Originally Posted by Zarah View Post
    But following is the code which produces the excepted result. The MalformedURLException was not thrown, if it is thrown, it will need to be handled. So I admit this code needs it.
    How do you know it wasn't thrown?
    Because this line is going to eat any exception thrown when trying to create the URL object and you will never know about.

    Java Code:
            try {params= new URL(spec);} catch(Exception e) {}
    So, at the minimum, stick an "e.printStackTrace()" inside that catch block.

    But honestly, if there's an exception there then it is one your code cannot recover from so you really shouldn't be bothering to continue processing.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,079
    Rep Power
    6

    Default Re: AsyncTask problem

    Indeed, that is like driving a car when the breaks fail and then you just keep driving as if nothing is wrong. Eventually you are going to crash and burn.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: AsyncTask problem

    How do you know it wasn't thrown?
    At that time I was wrongly thinking that if an exception is thrown, it will terminate the program.

    But I still think it was not thrown in this particular program that it should have been there in the LogCat if it was thrown. But that did not produce any report of a MalformedURLException in the LogCat. Neither did any of the following.

    Java Code:
    try {params= new URL(spec);} catch(Exception e) {Log.i(TAG, "MalformedURL Exception; URL is Null!");}
    Please correct me if I am wrong again.

    I completely agree that it is mandatory to put something in the catch{} block, otherwise there is even no point of having a try-catch block. I did not put anything inside the catch at that time because I did not know what to write inside it.

Similar Threads

  1. Replies: 0
    Last Post: 11-07-2012, 12:44 PM
  2. AsyncTask and ProgressDialog
    By Glorfindel Arnatuile in forum Android
    Replies: 1
    Last Post: 04-10-2012, 03:22 AM
  3. Small problem with problem with Java, C++ parse program.
    By dragstang86 in forum New To Java
    Replies: 4
    Last Post: 10-30-2011, 03:43 AM
  4. Replies: 9
    Last Post: 09-21-2010, 04:15 PM
  5. simple line problem / for loop problem
    By helpisontheway in forum New To Java
    Replies: 1
    Last Post: 11-17-2009, 06:12 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •