title: Create new activity from ImageButton in ListView
body: <p>Im beginner and try to work on an app. I want to create a new page/activity when the <code>imageButton</code> on the <code>listView</code> is clicked. (The image is grab from url). Any help is appreciated. </p>
  
  <p>Here is the<code>main.java</code></p>
  
  <pre><code>public class IngredientCategoryMain extends Activity {
  
  ListView list;
  String[] title;
  CategoryImageAdapter adapter;
  
  
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_ingredient_category_main);
  
      list=(ListView)findViewById(R.id.listView);
      title = getResources().getStringArray(R.array.titles);
      adapter=new CategoryImageAdapter(this, mStrings, title);
      list.setAdapter(adapter);
  
  }
  
  @Override
  public void onDestroy() {
      list.setAdapter(null);
      super.onDestroy();
  }
  
  public View.OnClickListener listener=new View.OnClickListener() {
      @Override
      public void onClick(View arg0) {
          adapter.imageLoader.clearCache();
          adapter.notifyDataSetChanged();
  
  
      }
  };
  
  public void onItemClick(int mPosition) {
      String tempValues = title[mPosition];
      Toast.makeText(IngredientCategoryMain.this, "You have clicked "+tempValues, Toast.LENGTH_LONG).show();
  }
  
  private String[] mStrings={
          "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Ic_cake_48px.svg/2000px-Ic_cake_48px.svg.png",
          "https://pixabay.com/static/uploads/photo/2013/04/01/21/30/can-99137_960_720.png",
          "http://publicdomainvectors.org/photos/Gerald_G_Fast_Food_Drinks_(FF_Menu)_9.png",
          "https://pixabay.com/static/uploads/photo/2014/03/25/16/59/apple-297775_960_720.png",
          "https://pixabay.com/static/uploads/photo/2012/04/16/11/14/mortar-35544_960_720.png",
          "https://pixabay.com/static/uploads/photo/2013/07/13/10/05/cattle-156498_960_720.png",
          "https://pixabay.com/static/uploads/photo/2013/07/12/15/39/acorn-150258_960_720.png",
          "http://publicdomainvectors.org/photos/johnny_automatic_bread_with_knife.png",
          "https://pixabay.com/static/uploads/photo/2015/09/13/00/12/chicken-937584_960_720.jpg",
          "http://publicdomainvectors.org/photos/bowl-of-steaming-soup-01.png",
          "https://pixabay.com/static/uploads/photo/2014/04/02/10/38/fish-304097_960_720.png",
          "http://publicdomainvectors.org/photos/Erbsen-lineart.png"
  };
  
  }
  </code></pre>
  
  <p>Adapter</p>
  
  <pre><code>public class CategoryImageAdapter extends BaseAdapter implements OnClickListener {
  
  private Activity activity;
  private String[] data;
  private String[] title;
  
  
  private static LayoutInflater inflater = null;
  public ImageLoader imageLoader;
  
  
  public CategoryImageAdapter(Activity a, String[] d, String[] t) {
      activity = a;
      title = t;
      data = d;
      inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      imageLoader = new ImageLoader(activity.getApplicationContext());
  
  
  }
  
  
  @Override
  public int getCount() {
      return title.length;
  }
  
  @Override
  public Object getItem(int position) {
      return position;
  }
  
  @Override
  public long getItemId(int position) {
      return position;
  }
  
  @Override
  public void onClick(View v) {
  
  }
  
  
  public static class ViewHolder {
  
      public ImageButton imageButton;
      public TextView textView;
  }
  
  
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
  
  
      View vi = convertView;
      ViewHolder holder;
      if (convertView == null) {
          vi = inflater.inflate(R.layout.ingcategoryrow, null);
          holder = new ViewHolder();
          holder.textView = (TextView) vi.findViewById(R.id.textView2);
          holder.imageButton = (ImageButton) vi.findViewById(R.id.imageButton2);
          vi.setTag(holder);
      } else
          holder = (ViewHolder) vi.getTag();
  
  
      holder.textView.setText(title[position]);
      ImageButton imageButton = holder.imageButton;
      imageLoader.DisplayImage(data[position], imageButton);
      vi.setOnClickListener(new OnItemClickListener(position));
      return vi;
  }
  
  
  
  private class OnItemClickListener implements OnClickListener{
      private int mPosition;
  
      OnItemClickListener(int position) {
          mPosition = position;
      }
  
  
      @Override
      public void onClick(View arg0) {
          IngredientCategoryMain sct = (IngredientCategoryMain)activity;
          sct.onItemClick(mPosition);
  
        }
      }
  </code></pre>
  
  <p>ImageLoader</p>
  
  <pre><code>public class ImageLoader {
  
  MemoryCache memoryCache = new MemoryCache();
  FileCache fileCache;
  private Map&lt;ImageButton, String&gt; imageButtons = Collections.synchronizedMap(new WeakHashMap&lt;ImageButton, String&gt;());
  ExecutorService executorService;
  Handler handler = new Handler();
  
  public ImageLoader(Context context) {
      fileCache = new FileCache(context);
      executorService= Executors.newFixedThreadPool(5);
  
  }
  
  final int stub_id=R.drawable.bakingood;
  
  public void DisplayImage(String url, ImageButton imageButton) {
      imageButtons.put(imageButton, url);
  
      Bitmap bitmap = memoryCache.get(url);
  
      if(bitmap!=null) {
          imageButton.setImageBitmap(bitmap);
      } else {
          queuePhoto(url, imageButton);
          imageButton.setImageResource(stub_id);
      }
  }
  
  private void queuePhoto(String url, ImageButton imageButton){
      PhotoToLoad p = new PhotoToLoad(url, imageButton);
      executorService.submit(new PhotosLoader(p));
  
  }
  
  private class PhotoToLoad {
      public String url;
      public ImageButton imageButton;
  
      public PhotoToLoad(String u, ImageButton i) {
          url=u;
          imageButton=i;
  
      }
  }
  
  class PhotosLoader implements Runnable {
      PhotoToLoad photoToLoad;
  
      PhotosLoader(PhotoToLoad photoToLoad) {
  
          this.photoToLoad=photoToLoad;
      }
  
      @Override
      public void run() {
          try{
              if(imageButtonReused(photoToLoad))
                  return;
  
              Bitmap bmp = getBitmap(photoToLoad.url);
              memoryCache.put(photoToLoad.url, bmp);
              if(imageButtonReused(photoToLoad))
                  return;
  
              BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
              handler.post(bd);
  
          } catch (Throwable th) {
              th.printStackTrace();
          }
        }
      }
  
  private  Bitmap getBitmap(String url) {
      File f=fileCache.getFile(url);
      Bitmap b= decodeFile(f);
      if(b!=null)
          return  b;
  
      try {
          Bitmap bitmap=null;
          URL imageUrl = new URL(url);
          HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
          conn.setConnectTimeout(30000);
          conn.setReadTimeout(30000);
          conn.setInstanceFollowRedirects(true);
          InputStream is=conn.getInputStream();
          OutputStream os = new FileOutputStream(f);
          Utils.CopyStream(is, os);
          os.close();
          conn.disconnect();
          bitmap = decodeFile(f);
  
          return bitmap;
  
      } catch (Throwable ex) {
          ex.printStackTrace();
          if(ex instanceof  OutOfMemoryError)
              memoryCache.clear();
          return null;
        }
  
      }
  
  
  private Bitmap decodeFile(File f) {
      try {
  
          //Decode image size
          BitmapFactory.Options o = new BitmapFactory.Options();
          o.inJustDecodeBounds = true;
          FileInputStream stream1=new FileInputStream(f);
          BitmapFactory.decodeStream(stream1,null,o);
          stream1.close();
  
          //Find the correct scale value. It should be the power of 2.
  
          // Set width/height of recreated image
          final int REQUIRED_SIZE=85;
  
          int width_tmp=o.outWidth, height_tmp=o.outHeight;
          int scale=1;
          while(true){
              if(width_tmp/2 &lt; REQUIRED_SIZE || height_tmp/2 &lt; REQUIRED_SIZE)
                  break;
              width_tmp/=2;
              height_tmp/=2;
              scale*=2;
          }
  
          //decode with current scale values
          BitmapFactory.Options o2 = new BitmapFactory.Options();
          o2.inSampleSize=scale;
          FileInputStream stream2=new FileInputStream(f);
          Bitmap bitmap= BitmapFactory.decodeStream(stream2, null, o2);
          stream2.close();
          return bitmap;
  
      } catch (FileNotFoundException e) {
      }
      catch (IOException e) {
          e.printStackTrace();
      }
      return null;
  }
  
  boolean imageButtonReused(PhotoToLoad photoToLoad){
      String tag=imageButtons.get(photoToLoad.imageButton);
      if (tag==null || !tag.equals(photoToLoad.url))
          return true;
      return false;
  }
  
  class BitmapDisplayer implements Runnable {
      Bitmap bitmap;
      PhotoToLoad photoToLoad;
  
      public BitmapDisplayer(Bitmap b, PhotoToLoad p) {bitmap = b;photoToLoad = p;}
  
      public void run() {
          if (imageButtonReused(photoToLoad))
              return;
          if (bitmap!=null)
              photoToLoad.imageButton.setImageBitmap(bitmap);
          else
              photoToLoad.imageButton.setImageResource(stub_id);
      }
  }
  
  public void clearCache() {
      memoryCache.clear();
      fileCache.clear();
    }
  }
  </code></pre>
  
  <p>MemoryCache</p>
  
  <pre><code>public class MemoryCache {
  
  private static final String TAG = "MemoryCache";
  
  private Map&lt;String, Bitmap&gt; cache = Collections.synchronizedMap(
          new LinkedHashMap&lt;String, Bitmap&gt;(10,1.5f, true));
  
  private long size=0;
  private long limit=1000000;
  
  public MemoryCache () {
      setLimit(Runtime.getRuntime().maxMemory() / 4);
  }
  
  public void setLimit(long limit) {
      this.limit = limit;
      Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
  
  }
  
  public Bitmap get(String id) {
      try {
          if (!cache.containsKey(id))
              return null;
          return cache.get(id);
      } catch (NullPointerException ex) {
          ex.printStackTrace();
          return null;
        }
      }
  
  public void put(String id, Bitmap bitmap) {
      try{
          if(cache.containsKey(id))
              size-=getSizeInBytes(cache.get(id));
          cache.put(id, bitmap);
          size+=getSizeInBytes(bitmap);
          checkSize();
      }catch (Throwable th) {
          th.printStackTrace();
        }
      }
  
  private void checkSize() {
      Log.i(TAG, "cache size="+size+" length="+cache.size());
      if(size&gt;limit) {
          Iterator&lt;Map.Entry&lt;String, Bitmap&gt;&gt; iter=cache.entrySet().iterator();
  
          while (iter.hasNext()) {
              Map.Entry&lt;String, Bitmap&gt; entry=iter.next();
              size-=getSizeInBytes(entry.getValue());
              iter.remove();
              if(size&lt;=limit)
                  break;
              }
              Log.i(TAG, "Clean cache.New size "+cache.size());
          }
      }
  
  public void clear() {
      try{
          cache.clear();
          size=0;
      }catch (NullPointerException ex) {
  
        }
      }
  
  private long getSizeInBytes(Bitmap bitmap) {
      if (bitmap==null)
          return 0;
      return bitmap.getRowBytes()*bitmap.getHeight();
    }
  
  }
  </code></pre>
  
  <p>FileCache</p>
  
  <pre><code>public class FileCache {
  private File cacheDir;
  public FileCache(Context context) {
      if (android.os.Environment.getExternalStorageState().equals(
              android.os.Environment.MEDIA_MOUNTED))
      {
          //if SDCARD is mounted (SDCARD is present on device and mounted)
          cacheDir = new File(
                  android.os.Environment.getExternalStorageDirectory(),"LazyList");
      }
      else
      {
          // if checking on simulator the create cache dir in your application context
          cacheDir=context.getCacheDir();
      }
  
      if(!cacheDir.exists()){
          // create cache dir in your application context
          cacheDir.mkdirs();
        }
      }
  
  
  public void clear() {
      File[] files=cacheDir.listFiles();
      if(files==null)
          return;
      for (File f:files)
          f.delete();
      }
  
  public File getFile(String url) {
      //Identify images by hashcode or encode by URLEncoder.encode.
      String filename=String.valueOf(url.hashCode());
  
      File f = new File(cacheDir, filename);
      return f;
    }
  }
  </code></pre>
  
  <p>Utils</p>
  
  <pre><code>public class Utils {
  public static void CopyStream(InputStream is, OutputStream os)
  {
      final int buffer_size=1024;
      try {
          byte[] bytes=new byte[buffer_size];
          for(;;) {
              int count = is.read(bytes, 0, buffer_size);
              if (count == -1)
                  break;
              os.write(bytes, 0, count);
          }
  
      }
      catch (IOException e) {
          e.printStackTrace();
      }
    }
  }
  </code></pre>