MyOptimizedSolution for challenge


#1

NOTE: IVE CHANGED SOMETHINGS IN THE DEFAULT CODE GIVEN IN THE TEXTBOOK

step 1. set the current page to 1. endure that you have a member variable in the flickerFetcher class that fetches the xml. Also create a flickerFetcher as a member variable in the PhotoGallery fragment.
step 2; update the page by incrementing the gridView page size with the size of the array adapter recieved from the AsynCTask.
Note ensure that you execute an instance of asyncTask . bcs you cant execute thesame instance more than once

see the code below. very simple to understand
public class PhotoGalleryFragment extends SingleRetainableFragment {
private GridView mGridView;
private String TAG=“PHOTO GALLERY”;
private String URL=“http://www.google.com”;
private List mPhotoGallery;
private int mGridViewSize;
private FlickrFetcher mFetcher;
private ArrayAdapter adapter;
private int mCurrentPage=1;
private ProgressBar progress;
@Override
protected int getShowView() {
return R.layout.fragment_photo_gallery;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFetcher= new FlickrFetcher();
progress= new ProgressBar(getActivity());

	 progress.setMax(100);
	 progress.setVisibility(View.VISIBLE);
	  
	 new mCTask().execute();
	
	
}
private class mCTask extends AsyncTask<String, Integer, List<GalleryItem>>{
	 
		@Override
		protected void onProgressUpdate(Integer... values) {
 			for(Integer val: values){
 				progress.setProgress(val);
 				/**/
 			}
		}
		
		@Override
		protected List<GalleryItem>  doInBackground(String... urls) {
			Integer[] progress={0,10,24,27,29,60,80,100};
			try {
				 publishProgress(progress);
				List<GalleryItem> items= mFetcher.getItems(mCurrentPage);
				
				 return items; 
				 
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		@Override
		protected void onPostExecute(List<GalleryItem> result) {
			mPhotoGallery=result;
			if(FlickrFetcher.getPAGE()==1){
				setUpAdapter();
				 progress.setVisibility(View.INVISIBLE);
			}else if(mGridView !=null && mPhotoGallery!=null){
				adapter.addAll(mPhotoGallery);
				adapter.notifyDataSetChanged();
			}
			 

		}
	 
 };
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	 View view= super.onCreateView(inflater, container, savedInstanceState);
	 mGridView=(GridView)view.findViewById(R.id.photoGridView);
 
	 return view;
}
 

private void setUpAdapter(){
	if(getActivity() ==null || mGridView ==null) return;
	if(mPhotoGallery !=null){
		adapter=new ArrayAdapter<GalleryItem>(getActivity(), android.R.layout.simple_list_item_1,mPhotoGallery);
		mGridView.setAdapter(adapter);
		//update or set the size of the gridview
		setGridViewSize(mGridView.getAdapter().getCount());
		mGridView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if(totalItemCount==0) return;
				int viewPageCovered=getGridViewSize();//check if the user has scrolled to the end
				if(viewPageCovered==totalItemCount){
					//then change the page
					
					mCurrentPage++;
					new mCTask().execute();
				}
				
			}
		});
		Toast.makeText(getActivity(), "items recieved", Toast.LENGTH_LONG).show();
	}else{
		mGridView.setAdapter(null);
		Toast.makeText(getActivity(), "no items recieved", Toast.LENGTH_LONG).show();

	}
}
 
 
public int getGridViewSize() {
	return mGridViewSize;
}
public void setGridViewSize(int gridViewSize) {
	mGridViewSize = getGridViewSize()+gridViewSize;
}

}

Also the flicker fetcher Xml parser class::

package com.example.photogallery;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.net.Uri;

public class FlickrFetcher {
private static final String ENDPOINT = “https://api.flickr.com/services/rest/”;
private static final String METHOD_GET_RECENT = “flickr.photos.getRecent”;
private static final String PARAM_EXTRAS = “extras”;
private static final String EXTRA_SMALL_URL = “url_s”;
private static final String API_KEY=“dc8b832c67b54e64c6be094afc1a056c”;
private static final String API_SECREAT=“d7bd04a48ec3f30d”;
private static final String PER_PAGE=“100”;
private static int PAGE=1;
private static final String XML_PHOTO = “photo”;

private byte[] getUrlBytes(String Url) throws IOException{
	URL url= new URL(Url);
	HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
	ByteArrayOutputStream buffer = null;
	BufferedInputStream inputStream=null;
	try {
		buffer= new ByteArrayOutputStream();
		 inputStream=new BufferedInputStream(urlConnection.getInputStream());
		if(urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) return null;
		int bytecount=0;
		byte[] inputByte= new byte[1024];
		while((bytecount=inputStream.read(inputByte))>0){
			buffer.write(inputByte, 0, bytecount);
			
		}
		buffer.close();
		return buffer.toByteArray();
	}  finally{
		inputStream.close();
		urlConnection.disconnect();
	}
	
	
	
	
}
public String getUrl(String urlSpec) throws IOException{
	return new String(getUrlBytes(urlSpec));
}

public List<GalleryItem> getItems(int page){
	FlickrFetcher.setPAGE(page);
	List<GalleryItem> items= new ArrayList<GalleryItem>();
	Uri  builder=Uri.parse(ENDPOINT).buildUpon()
	 .appendQueryParameter("method", METHOD_GET_RECENT)
	 .appendQueryParameter("api_key",API_KEY)
	 .appendQueryParameter(PARAM_EXTRAS, EXTRA_SMALL_URL)
	 .appendQueryParameter("per_page", PER_PAGE)
	 .appendQueryParameter("page", String.valueOf(PAGE))
	 .build();
	 
	String url=builder.toString();
	  
	try {
		String xmlString = new String(getUrlBytes(url));
		XmlPullParserFactory pullFactory;
		 
			pullFactory = XmlPullParserFactory.newInstance();
		
		XmlPullParser parser=pullFactory.newPullParser();
		parser.setInput(new StringReader(xmlString));
		parseItems((ArrayList<GalleryItem>) items, parser);
		 
	 
	} catch (XmlPullParserException e) {
		e.printStackTrace();
	}catch (IOException e) {
		e.printStackTrace();
	}
	return items;
	 
	
	
}

 
public static int getPAGE() {
	return PAGE;
}

private static void setPAGE(int pAGE) {
	PAGE = pAGE;
}

private void parseItems(ArrayList<GalleryItem> items, XmlPullParser parser) throws XmlPullParserException, IOException{
	int tagType=parser.next();//check for open tag type
	while(tagType !=XmlPullParser.END_DOCUMENT){
		if(tagType==XmlPullParser.START_TAG && XML_PHOTO.equals(parser.getName())){
			String id=parser.getAttributeValue(null, "id");
			String title=parser.getAttributeValue(null, "title");
			String url=parser.getAttributeValue(null, "url_s");
			/*String height=parser.getAttributeValue(null, "height");
			String width=parser.getAttributeValue(null, "width");*/
			items.add(new GalleryItem( id, title, url));
		}
		tagType=parser.next();//update the tag type to close 
	}
	 
}

}