Android Flickr Json Caching Images - android

I am hoping someine can help me figure out how to cache the Flickr Json images to cache for faster loading and offline use...the code below is from a tutorial and i have all that figured out but am lost with trying to read/use the Android developer resources and other example on the web...be very grateful for a solution and help making this work...I am new to programming and appreciate the knowledge here :)
package com.windmillagency;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidFlickrActivity extends BT_activity_base {
public String thisActivityName = "Flickr";
ProgressDialog progressDialog;
BackgroundThread backgroundThread;
public class FlickrImage {
String Id;
String Owner;
String Secret;
String Server;
String Farm;
String Title;
Bitmap FlickrBitmap;
FlickrImage(String _Id, String _Owner, String _Secret,
String _Server, String _Farm, String _Title){
Id = _Id;
Owner = _Owner;
Secret = _Secret;
Server = _Server;
Farm = _Farm;
Title = _Title;
FlickrBitmap = preloadBitmap();
}
private Bitmap preloadBitmap(){
Bitmap bm= null;
String FlickrPhotoPath =
"http://farm" + Farm + ".static.flickr.com/"
+ Server + "/" + Id + "_" + Secret + "_m.jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
public Bitmap getBitmap(){
return FlickrBitmap;
}
}
class FlickrAdapter extends BaseAdapter{
private Context context;
private FlickrImage[] FlickrAdapterImage;;
FlickrAdapter(Context c, FlickrImage[] fImage){
context = c;
FlickrAdapterImage = fImage;
}
public int getCount() {
// TODO Auto-generated method stub
return FlickrAdapterImage.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return FlickrAdapterImage[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image;
if (convertView == null) {
image = new ImageView(context);
image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setPadding(8, 8, 8, 8);
} else {
image = (ImageView) convertView;
}
image.setImageBitmap(FlickrAdapterImage[position].getBitmap());
return image;
}
}
FlickrImage[] myFlickrImage;
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://api.flickr.com/myflickrURL";
String FlickrQuery_per_page = "&per_page=10";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "xxxxxxxxxxxxxxxxxxx";
final String DEFAULT_SEARCH = "flickr";
EditText searchText;
Button searchButton;
Gallery photoBar;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activityName = "AndroidFlickrActivity";
BT_debugger.showIt(activityName + ":onCreate");
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
//setup background colors...
BT_viewUtilities.updateBackgroundColorsForScreen(this, this.screenData);
//setup background images..
if(backgroundImageWorkerThread == null){
backgroundImageWorkerThread = new BackgroundImageWorkerThread();
backgroundImageWorkerThread.start();
}
//setup navigation bar...
LinearLayout navBar = BT_viewUtilities.getNavBarForScreen(this, this.screenData);
if(navBar != null){
baseView.addView(navBar);
}
//inflate this screens layout file...
LayoutInflater vi = (LayoutInflater)thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View thisScreensView = vi.inflate(R.layout.flickr, null);
//add the view to the base view...
baseView.addView(thisScreensView);
searchText = (EditText)findViewById(R.id.searchtext);
searchText.setText(DEFAULT_SEARCH);
searchButton = (Button)findViewById(R.id.searchbutton);
photoBar = (Gallery)findViewById(R.id.photobar);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(AndroidFlickrActivity.this,
"Progress", "Wait!");
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
inputStream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private FlickrImage[] ParseJSON(String json){
FlickrImage[] flickrImage = null;
bmFlickr = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
flickrImage = new FlickrImage[JsonArray_photo.length()];
for (int i = 0; i < JsonArray_photo.length(); i++){
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(i);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
flickrImage[i] = new FlickrImage(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flickrImage;
}
public class BackgroundThread extends Thread{
volatile boolean running = false;
int cnt;
void setRunning(boolean b){
running = b;
cnt = 10;
}
#Override
public void run() {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
myFlickrImage = ParseJSON(searchResult);
handler.sendMessage(handler.obtainMessage());
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
progressDialog.dismiss();
photoBar.setAdapter(new FlickrAdapter(AndroidFlickrActivity.this, myFlickrImage));
Toast.makeText(AndroidFlickrActivity.this,
"Images Loaded", Toast.LENGTH_LONG).show();
}
};
}

I suggest you have a look at Universal Image Loader on github.
Universal Image Loader allows you to easily integrate asynchronous image loading, caching and rendering of images on Android in list, gallery and grid format. If you want to implement your own solution, reading the source for this project is a great way to start. It was written by Sergey Tarasevich and is licensed under the BSD 3-clause.

Related

list view just display in the second activity the last row

i a creating android application using json parser to get data from web and display it in listview.
after the user select a row the system display the details in a second activity using the intent.
the problem is that whatever the user select the system display the last row in the list view.
can anyone help me to fix this problem ?
JsonActivityHttpClient
package com.devleb.jsonparsingactivitydemo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ListActivity;
import android.content.Intent;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class JsonActivityHttpClient extends ListActivity {
// ***from JsonHandlerClass****//
JSONArray PostalCodes;
List<String> result;
JSONObject jsonObject;
JSONObject postalCode;
private static final String PLACE_NAME_TAG = "placeName";
private static final String LONGITUDE_TAG = "lng";
private static final String LATITUDE_TAG = "lat";
// private static final String ADMIN_NAME_TAG = "adminCode3";
private static final String POSTAL_CODE_TAG = "postalcode";
private static final String POSTALCODE = "postalcodes";
// ***from JsonHandlerClass****//
JSONParserHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new HTTPGetTask().execute();
}
private class HTTPGetTask extends AsyncTask<Void, Void, List<String>> {
private static final String USER_NAME = "devleb";
private static final String URL = "http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username="
+ USER_NAME;
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected List<String> doInBackground(Void... arg0) {
// TODO Auto-generated method stub
HttpGet request = new HttpGet(URL);
JSONParserHandler responseHandler = new JSONParserHandler();
try {
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
// TODO Auto-generated method stub
if (null != mClient) {
mClient.close();
setListAdapter(new ArrayAdapter<String>(
JsonActivityHttpClient.this, R.layout.list_item, result));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.json_activity_http_client, menu);
return true;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
try {
//String item = (String)l.getItemAtPosition(position);
// PostalCodes.get(position);
String PLACENAME = postalCode.get(PLACE_NAME_TAG).toString();
String LATITUDE = postalCode.get(LATITUDE_TAG).toString();
String LONGITUDE = postalCode.get(LONGITUDE_TAG).toString();
String POSTALCODE = postalCode.get(POSTAL_CODE_TAG).toString();
Log.e("position of the Item in the list", "you select the item number " + PostalCodes.getString(position));
Intent in = new Intent(getBaseContext(), Row_Item.class);
in.putExtra("placename", PLACENAME);
in.putExtra("lat", LATITUDE);
in.putExtra("lng", LONGITUDE);
in.putExtra("postaCode", POSTALCODE);
startActivity(in);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("Error in the onListItemClick",
"LOOK AT THE onListItemClick method");
}
}
// *************JSONParserHandler*******************************//
private class JSONParserHandler implements ResponseHandler<List<String>> {
/*
* private static final String PLACE_NAME_TAG = "placeName"; private
* static final String LONGITUDE_TAG = "lng"; private static final
* String LATITUDE_TAG = "lat"; private static final String
* ADMIN_NAME_TAG = "adminCode3"; private static final String
* POSTAL_CODE_TAG = "postalcode"; private static final String
* POSTALCODE = "postalcodes";
*/
#Override
public List<String> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
result = new ArrayList<String>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
jsonObject = (JSONObject) new JSONTokener(JSONResponse)
.nextValue();
PostalCodes = jsonObject.getJSONArray(POSTALCODE);
for (int i = 0; i < PostalCodes.length(); i++) {
postalCode = (JSONObject) PostalCodes.get(i);
result.add(postalCode.get(PLACE_NAME_TAG) + "\n"
+ POSTAL_CODE_TAG + ":"
+ postalCode.get(POSTAL_CODE_TAG) + LATITUDE_TAG
+ ":" + postalCode.get(LATITUDE_TAG) + "\n"
+ LONGITUDE_TAG + ":"
+ postalCode.get(LONGITUDE_TAG));
}
} catch (JSONException E) {
E.printStackTrace();
}
return result;
}
}
// *************JSONParserHandler*******************************//
}
i think the problem is in this method
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
try {
//String item = (String)l.getItemAtPosition(position);
// PostalCodes.get(position);
String PLACENAME = postalCode.get(PLACE_NAME_TAG).toString();
String LATITUDE = postalCode.get(LATITUDE_TAG).toString();
String LONGITUDE = postalCode.get(LONGITUDE_TAG).toString();
String POSTALCODE = postalCode.get(POSTAL_CODE_TAG).toString();
Log.e("position of the Item in the list", "you select the item number " + PostalCodes.getString(position));
Intent in = new Intent(getBaseContext(), Row_Item.class);
in.putExtra("placename", PLACENAME);
in.putExtra("lat", LATITUDE);
in.putExtra("lng", LONGITUDE);
in.putExtra("postaCode", POSTALCODE);
startActivity(in);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("Error in the onListItemClick",
"LOOK AT THE onListItemClick method");
}
Row_Item
package com.devleb.jsonparsingactivitydemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class Row_Item extends Activity {
TextView Place_Name, txtlat, txtlng, txtPostalCode;
String value1, value2, value3, value4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_row__item);
Place_Name = (TextView) findViewById(R.id.textView1);
txtlat = (TextView) findViewById(R.id.textLAT);
txtlng = (TextView) findViewById(R.id.textLNG);
txtPostalCode = (TextView) findViewById(R.id.textPSTC);
Intent i = getIntent();
if (null != i) {
value1 = i.getStringExtra("placename");
value2 = i.getStringExtra("lat");
value3 = i.getStringExtra("lng");
value4 = i.getStringExtra("postaCode");
}
Place_Name.setText(value1);
txtlat.setText(value2);
txtlng.setText(value3);
txtPostalCode.setText(value4);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.row__item, menu);
return true;
}
}
The problem I see is that you don't specify which of those objects to choose so it apparently chose the last. On the second look, when you parse the json document you left the last object in postalCode variable (method handleRespone() ). That's the cause. What you could do is to reparse the specified postal code or save all postal codes in an array and use them in OnListItemClick() method.

Invalid OAUTH_SIGNATURE error while using Fat secret API in Android

I am using the Fat secret API for developing an application in android. Right now I am working on a sample application; which just searches for a food item entered in the EditText. I have read their Rest API documentation here.
I am doing everything as per their requirements, but still, I am getting an Invalid OAUTH_SIGNATURE error. I have written the following code:
package com.example.foodsearch;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
HttpClient client;
EditText searchText;
Button searchButton;
String q="";
String encoder="";
String signatureString="";
String encodedSignString="";
String finalSignatureString="";
String key="";
String hmacKey="";
JSONObject json;
final static String URL="http://platform.fatsecret.com/rest/server.api";
final static String SIGN="a=foo&oauth_consumer_key=demo&oauth_nonce=abc&oauth_signature_method=HMAC-SHA1&oauth_timestamp=12345678&oauth_version=1.0&z=bar";
final static String OAUTH_CONSUMER_KEY="667d50884ae7446e8d08c283bdf3feff";
final static String OAUTH_ACCESS_SECRET="22dbde088c634f0f99d29fc468bf70c6";
final static String OAUTH_SIGNATURE_METHOD="HMAC-SHA1";
final static String OAUTH_VERSION="1.0";
final static String ENCODED_SIGN_STRING="a%3Dbar%26%26oauth_consumer_key%3Ddemo%26oauth_nonce%3Dabc%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D12345678%26oauth_version%3D1.0%26z%3Dbar";
static String OAUTH_TIMESTAMP="";
static String OAUTH_NOUNCE="shreyas";
final static String a="foo";
final static String z="bar";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
public void initialize() {
// TODO Auto-generated method stub
searchText=(EditText)findViewById(R.id.etSearch);
searchButton=(Button)findViewById(R.id.bSearch);
client=new DefaultHttpClient();
long timestamp=(System.currentTimeMillis() / 1000);
OAUTH_TIMESTAMP=timestamp+"";
OAUTH_NOUNCE += timestamp;
Log.d("TIMESTAMP:", OAUTH_TIMESTAMP);
try {
encoder=URLEncoder.encode(URL, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("URL ENCODED:", encoder);
Map<String, String> params=new HashMap<String, String>();
params.put("oauth_consumer_key", OAUTH_CONSUMER_KEY);
params.put("oauth_signature_method", OAUTH_SIGNATURE_METHOD);
params.put("oauth_timestamp", OAUTH_TIMESTAMP);
params.put("oauth_nounce", OAUTH_NOUNCE);
params.put("oauth_version", OAUTH_VERSION);
// params.put("a", a);
// params.put("z", z);
Map<String, String> sortedMap=new TreeMap<String, String>(params);
printMap(sortedMap);
String sigString=concatenate(sortedMap);
Log.d("CONCATENATED STRING:", sigString);
encodedSignString=encodeSignatureString(sigString);
Log.d("ORIGINAL ENCODED STRING:", ENCODED_SIGN_STRING);
Log.d("MY ENCODED STRING:", encodedSignString);
finalSignatureString="GET" + "&" + encoder + "&" + encodedSignString;
Log.d("FINAL SIGN STRING:", finalSignatureString);
key=OAUTH_CONSUMER_KEY + "&" + OAUTH_ACCESS_SECRET;
hmacKey=computeHmac("HmacSHA1",finalSignatureString,key);
// hmacKey=encodeBase(hmacKey);
try{
hmacKey=URLEncoder.encode(hmacKey, "UTF-8");
}
catch (Exception e) {
e.printStackTrace();
}
Log.d("HMAC KEY:", hmacKey);
Log.d("DONE:", "Done with initialisaton");
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
q=searchText.getText().toString();
searchFood(q);
}
});
}
private String encodeBase(String hmacKey2) {
// TODO Auto-generated method stub
byte[] data=null;
try {
data=hmacKey2.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
}
String base64=Base64.encodeToString(data, Base64.DEFAULT);
Log.d("Base 64", base64);
return base64;
}
private String computeHmac(String type, String value, String key) {
// TODO Auto-generated method stub
try{
Mac mac=Mac.getInstance(type);
SecretKeySpec secret=new SecretKeySpec(key.getBytes(), type);
mac.init(secret);
byte[] bytes = mac.doFinal(value.getBytes());
return new String(Base64.encode(bytes,0));
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "";
}
private String encodeSignatureString(String sigString) {
// TODO Auto-generated method stub
String encodedSignString="";
try {
encodedSignString=URLEncoder.encode(sigString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedSignString;
}
private String concatenate(Map<String, String> sortedMap) {
// TODO Auto-generated method stub
String signatureString="";
Set s=sortedMap.entrySet();
Iterator i=s.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
String key=(String)entry.getKey();
String val=(String)entry.getValue();
signatureString+=key + "=" + val +"&";
}
return signatureString.substring(0, (signatureString.length()-1));
}
private void printMap(Map<String, String> sortedMap) {
// TODO Auto-generated method stub
Set s=sortedMap.entrySet();
Iterator i=s.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
String key=(String)entry.getKey();
String val=(String)entry.getValue();
Log.d("SORTED :", key + "=" + val);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void searchFood(String q) {
final String searchKeyword=q;
AsyncTask<String, Integer, String> myAsyncTask = new AsyncTask<String, Integer, String>()
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
String requestString=URL + "?search_expression=" +searchKeyword + "&format=json" + "&" + "oauth_consumer_key="+OAUTH_CONSUMER_KEY + "&" + "oauth_signature_method="+OAUTH_SIGNATURE_METHOD + "&" + "oauth_timestamp="+Long.parseLong(OAUTH_TIMESTAMP) + "&" + "oauth_nonce="+OAUTH_NOUNCE + "&" + "oauth_version="+OAUTH_VERSION + "&" + "oauth_signature="+hmacKey + "&" + "method=foods.search";
java.net.URL url=new java.net.URL(requestString);
Log.d("FINAL REQUEST STRING:", requestString);
StringBuilder sb=new StringBuilder(requestString);
StringBuilder foodRequest=new StringBuilder();
HttpGet get=new HttpGet(url.toString());
HttpResponse r= client.execute(get);
Log.d("EXECUTED:", "Executed post successfully!");
int status=r.getStatusLine().getStatusCode();
Log.d("STATUS:", status+"");
if(status >= 200 && status < 300)
{
BufferedReader br=new BufferedReader(new InputStreamReader(r.getEntity().getContent()));
String t;
while((t = br.readLine())!=null)
{
foodRequest.append(t);
}
Log.d("", foodRequest.toString());
json=new JSONObject(foodRequest.toString());
Log.d("GOT:", "GOT JSON OBJECT");
}
}
catch (JSONException e) {
// TODO: handle exception
Log.e("ERROR:", "This is not a valid JSON request");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
};
myAsyncTask.execute();
}
}
Any help will be greatly appreciated..

Android save info on return to activity

very new to android and wondering how I can make this sample code return to where it left off instead of having to reload the pictures on returning to the screen. Right now when I exit the screen and return I have to start all over. I have read and trying to understand the Android documents but having trouble making this work or where to begin... thanks everyone!
package com.windmillagency;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidFlickrActivity extends BT_activity_base {
public String thisActivityName = "Flickr";
ProgressDialog progressDialog;
BackgroundThread backgroundThread;
public class FlickrImage {
String Id;
String Owner;
String Secret;
String Server;
String Farm;
String Title;
Bitmap FlickrBitmap;
FlickrImage(String _Id, String _Owner, String _Secret,
String _Server, String _Farm, String _Title){
Id = _Id;
Owner = _Owner;
Secret = _Secret;
Server = _Server;
Farm = _Farm;
Title = _Title;
FlickrBitmap = preloadBitmap();
}
private Bitmap preloadBitmap(){
Bitmap bm= null;
String FlickrPhotoPath =
"http://farm" + Farm + ".static.flickr.com/"
+ Server + "/" + Id + "_" + Secret + "_m.jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
public Bitmap getBitmap(){
return FlickrBitmap;
}
}
class FlickrAdapter extends BaseAdapter{
private Context context;
private FlickrImage[] FlickrAdapterImage;;
FlickrAdapter(Context c, FlickrImage[] fImage){
context = c;
FlickrAdapterImage = fImage;
}
public int getCount() {
// TODO Auto-generated method stub
return FlickrAdapterImage.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return FlickrAdapterImage[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image;
if (convertView == null) {
image = new ImageView(context);
image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setPadding(8, 8, 8, 8);
} else {
image = (ImageView) convertView;
}
image.setImageBitmap(FlickrAdapterImage[position].getBitmap());
return image;
}
}
FlickrImage[] myFlickrImage;
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=fdd73dc07613841fbe325b5103d673b7&user_id=65005067#N08&per_page=25&format=json";
String FlickrQuery_per_page = "&per_page=10";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "fdd73dc07613841fbe325b5103d673b7";
final String DEFAULT_SEARCH = "flickr";
EditText searchText;
Button searchButton;
Gallery photoBar;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activityName = "AndroidFlickrActivity";
BT_debugger.showIt(activityName + ":onCreate");
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
//setup background colors...
BT_viewUtilities.updateBackgroundColorsForScreen(this, this.screenData);
//setup background images..
if(backgroundImageWorkerThread == null){
backgroundImageWorkerThread = new BackgroundImageWorkerThread();
backgroundImageWorkerThread.start();
}
//setup navigation bar...
LinearLayout navBar = BT_viewUtilities.getNavBarForScreen(this, this.screenData);
if(navBar != null){
baseView.addView(navBar);
}
//inflate this screens layout file...
LayoutInflater vi = (LayoutInflater)thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View thisScreensView = vi.inflate(R.layout.flickr, null);
//add the view to the base view...
baseView.addView(thisScreensView);
searchText = (EditText)findViewById(R.id.searchtext);
searchText.setText(DEFAULT_SEARCH);
searchButton = (Button)findViewById(R.id.searchbutton);
photoBar = (Gallery)findViewById(R.id.photobar);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
///////////////////////////////////////////////////
//activity life-cycle overrides
//onResume
#Override
public void onResume() {
super.onResume();
//Log.i("ZZ", thisActivityName + ":onResume");
tToast("onResume");
}
private void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.show();
}
//onPause
#Override
public void onPause() {
//Log.i("ZZ", thisActivityName + ":onPause");
super.onPause();
tToast("onPause");
}
//activity life-cycle overrides
///////////////////////////////////////////////////
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(AndroidFlickrActivity.this,
"Progress", "Please Wait");
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
inputStream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private FlickrImage[] ParseJSON(String json){
FlickrImage[] flickrImage = null;
bmFlickr = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
flickrImage = new FlickrImage[JsonArray_photo.length()];
for (int i = 0; i < JsonArray_photo.length(); i++){
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(i);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
flickrImage[i] = new FlickrImage(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flickrImage;
}
public class BackgroundThread extends Thread{
volatile boolean running = false;
int cnt;
void setRunning(boolean b){
running = b;
cnt = 10;
}
#Override
public void run() {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
myFlickrImage = ParseJSON(searchResult);
handler.sendMessage(handler.obtainMessage());
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
progressDialog.dismiss();
photoBar.setAdapter(new FlickrAdapter(AndroidFlickrActivity.this, myFlickrImage));
Toast.makeText(AndroidFlickrActivity.this,
"Images Loaded", Toast.LENGTH_LONG).show();
}
};
}
Write your activity so that it is aware of its current state.
In your onPause() method, save that state in any manner that you like. SharedPrefs, storage to a database, to a flat file, etc.
In your onResume() method, read that state and restore it.

Android getSharedPreferences onPause help store images

Trying to store images in this Flickr gallery so when user leaves the activity and returns the images don't need to be loaded again... I have been reading about getSharedPreferences used in the onPause method to keep the images from being destroyed... only problem is I can't find any examples dealing with images only text fields and such...thanks for any help
package com.windmillagency;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidFlickrActivity extends BT_activity_base {
public String thisActivityName = "Flickr";
ProgressDialog progressDialog;
BackgroundThread backgroundThread;
public class FlickrImage {
String Id;
String Owner;
String Secret;
String Server;
String Farm;
String Title;
Bitmap FlickrBitmap;
FlickrImage(String _Id, String _Owner, String _Secret,
String _Server, String _Farm, String _Title){
Id = _Id;
Owner = _Owner;
Secret = _Secret;
Server = _Server;
Farm = _Farm;
Title = _Title;
FlickrBitmap = preloadBitmap();
}
private Bitmap preloadBitmap(){
Bitmap bm= null;
String FlickrPhotoPath =
"http://farm" + Farm + ".static.flickr.com/"
+ Server + "/" + Id + "_" + Secret + "_m.jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
public Bitmap getBitmap(){
return FlickrBitmap;
}
}
class FlickrAdapter extends BaseAdapter{
private Context context;
private FlickrImage[] FlickrAdapterImage;;
FlickrAdapter(Context c, FlickrImage[] fImage){
context = c;
FlickrAdapterImage = fImage;
}
public int getCount() {
// TODO Auto-generated method stub
return FlickrAdapterImage.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return FlickrAdapterImage[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image;
if (convertView == null) {
image = new ImageView(context);
image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setPadding(8, 8, 8, 8);
} else {
image = (ImageView) convertView;
}
image.setImageBitmap(FlickrAdapterImage[position].getBitmap());
return image;
}
}
FlickrImage[] myFlickrImage;
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=fdd73dc07613841fbe325b5103d673b7&user_id=65005067#N08&per_page=25&format=json";
String FlickrQuery_per_page = "&per_page=10";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "fdd73dc07613841fbe325b5103d673b7";
final String DEFAULT_SEARCH = "flickr";
EditText searchText;
Button searchButton;
Gallery photoBar;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activityName = "AndroidFlickrActivity";
BT_debugger.showIt(activityName + ":onCreate");
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
//setup background colors...
BT_viewUtilities.updateBackgroundColorsForScreen(this, this.screenData);
//setup background images..
if(backgroundImageWorkerThread == null){
backgroundImageWorkerThread = new BackgroundImageWorkerThread();
backgroundImageWorkerThread.start();
}
//setup navigation bar...
LinearLayout navBar = BT_viewUtilities.getNavBarForScreen(this, this.screenData);
if(navBar != null){
baseView.addView(navBar);
}
//inflate this screens layout file...
LayoutInflater vi = (LayoutInflater)thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View thisScreensView = vi.inflate(R.layout.flickr, null);
//add the view to the base view...
baseView.addView(thisScreensView);
searchText = (EditText)findViewById(R.id.searchtext);
searchText.setText(DEFAULT_SEARCH);
searchButton = (Button)findViewById(R.id.searchbutton);
photoBar = (Gallery)findViewById(R.id.photobar);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
///////////////////////////////////////////////////
//activity life-cycle overrides
//onResume
#Override
public void onResume() {
super.onResume();
//Log.i("ZZ", thisActivityName + ":onResume");
tToast("onResume");
}
private void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.show();
}
//onPause
#Override
public void onPause() {
//Log.i("ZZ", thisActivityName + ":onPause");
super.onPause();
tToast("onPause");
}
//activity life-cycle overrides
///////////////////////////////////////////////////
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(AndroidFlickrActivity.this,
"Progress", "Please Wait");
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
inputStream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private FlickrImage[] ParseJSON(String json){
FlickrImage[] flickrImage = null;
bmFlickr = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
flickrImage = new FlickrImage[JsonArray_photo.length()];
for (int i = 0; i < JsonArray_photo.length(); i++){
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(i);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
flickrImage[i] = new FlickrImage(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flickrImage;
}
public class BackgroundThread extends Thread{
volatile boolean running = false;
int cnt;
void setRunning(boolean b){
running = b;
cnt = 10;
}
#Override
public void run() {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
myFlickrImage = ParseJSON(searchResult);
handler.sendMessage(handler.obtainMessage());
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
progressDialog.dismiss();
photoBar.setAdapter(new FlickrAdapter(AndroidFlickrActivity.this, myFlickrImage));
Toast.makeText(AndroidFlickrActivity.this,
"Images Loaded", Toast.LENGTH_LONG).show();
}
};
}
I think what you need is image caching. Storing SharedPreferences comes with memory limitations. If the number of images is large, you can try this library for image caching:
Hope this helps !

set image in dynamic grid view

GridActivity.java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class GridActivity extends Activity
{
ArrayList<String> imageurl=new ArrayList<String>();
String albumId= ConstantData.album_id;
String userId = ConstantData.user_id;
int pageNo =1;
int limit = 20;
ArrayList<Object> result;
XmlParser parser;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photos_activity);
//Add required urls
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=photo_paging&userid="+ ConstantData.user_id +"&sessionid="+ ConstantData.session_id +"&tmpl=component&albumid="+ ConstantData.album_id +"&pageno=1&limit=20");
StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><pageno>" + pageNo +"</pageno><limit>"+ limit +"</limit></data>");
StringEntity strEntity = new StringEntity(strBuffer.toString());
post.setEntity(strEntity);
HttpResponse response = client.execute(post);
InputStream in = response.getEntity().getContent();
String strResponse = convertStreamToString(in);
parser = new XmlParser(in, new AddAlbumDetailBean());
result = parser.parse("data", "photo");
//Log.i("aBean Value", ""+aBean);
//System.out.println(strResponse);
String startCode = "<code>";
String endCode = "</code>";
String starPhotoCount = "<photocount>";
String endPhotoCount ="</photocount>";
String starPhotos = "<photos>";
String endPhotos ="</photos>";
String startPhoto = "<photo>";
String endPhoto = "</photo>";
String startId = "<Id>";
String endId = "</Id>";
String starTitle = "<title>";
String endTitle ="</title>";
String startThumb ="<thumb>";
String endThumb = "</thumb>";
String startUrl = "<url>";
String endUrl = "</url>";
if (startCode.equalsIgnoreCase("<code>") && endCode.equalsIgnoreCase("</code>"))
{
int startC = strResponse.indexOf(startCode);
int endC = strResponse.indexOf(endCode);
Log.i("startCode", ""+startC);
Log.i("endCode", ""+endC);
String OldCode = strResponse.substring(startC, endC);
int startCodeindex = OldCode.indexOf(">");
String code = OldCode.substring(startCodeindex + 1).trim();
Log.i("Code", ""+code);
}
if (starPhotoCount.equalsIgnoreCase("<photocount>") && endPhotoCount.equalsIgnoreCase("</photocount>"))
{
int startPC = strResponse.indexOf(starPhotoCount);
int endPC = strResponse.indexOf(endPhotoCount);
Log.i("starPhotoCount", ""+startPC);
Log.i("endPhotoCount", ""+endPC);
String OldPC = strResponse.substring(startPC, endPC);
int startPCindex = OldPC.indexOf(">");
String photocount = OldPC.substring(startPCindex + 1).trim();
Log.i("PhotoCount", ""+photocount);
}
if (starPhotos.equalsIgnoreCase("<photos>") && endPhotos.equalsIgnoreCase("</photos>"))
{
int startPs = strResponse.indexOf(starPhotos);
int endPs = strResponse.indexOf(endPhotos);
Log.i("starPhotos", ""+startPs);
Log.i("endPhotos", ""+endPs);
String OldPhotos = strResponse.substring(startPs, endPs);
int startPhotosindex = OldPhotos.indexOf(">");
String photos = OldPhotos.substring(startPhotosindex + 1).trim();
Log.i("Photos", ""+photos);
}
if (startPhoto.equalsIgnoreCase("<photo>") && endPhoto.equalsIgnoreCase("</photo>"))
{
int startP = strResponse.indexOf(startPhoto);
int endP = strResponse.indexOf(endPhoto);
Log.i("startPhoto", ""+startP);
Log.i("endPhoto", ""+endP);
String OldThumb = strResponse.substring(startP, endP);
int startUrlindex = OldThumb.indexOf(">");
String photo = OldThumb.substring(startUrlindex + 1).trim();
Log.i("Photo", ""+photo);
}
/*if (startId.equalsIgnoreCase("<id>") && endId.equalsIgnoreCase("</id>"))
{
int startI = strResponse.indexOf(startId);
int endI = strResponse.indexOf(endId);
Log.i("startId", ""+startI);
Log.i("endId", ""+endI);
String OldId = strResponse.substring(startI, endI);
int startIdindex = OldId.indexOf(">");
String id = OldId.substring(startIdindex + 1).trim();
Log.i("ID", ""+id);
}*/
if (starTitle.equalsIgnoreCase("<title>") && endTitle.equalsIgnoreCase("</title>"))
{
int startT = strResponse.indexOf(starTitle);
int endT = strResponse.indexOf(endTitle);
Log.i("startTitle", ""+startT);
Log.i("endTitle", ""+endT);
String OldTitle = strResponse.substring(startT, endT);
int startTitleindex = OldTitle.indexOf(">");
String title = OldTitle.substring(startTitleindex + 1).trim();
Log.i("Title", ""+title);
}
if (startThumb.equalsIgnoreCase("<thumb>") && endThumb.equalsIgnoreCase("</thumb>"))
{
int startTh = strResponse.indexOf(startThumb);
int endTh = strResponse.indexOf(endThumb);
Log.i("startThumb", ""+startTh);
Log.i("endThumb", ""+endTh);
String OldThumb = strResponse.substring(startTh, endTh);
int startthumbindex = OldThumb.indexOf(">");
String thumb = OldThumb.substring(startthumbindex + 1).trim();
Log.d("Thumb Url", thumb);
imageurl.add(thumb);
Log.i("Thu0mb", ""+thumb);
}
if (startUrl.equalsIgnoreCase("<url>") && endId.equalsIgnoreCase("</url>"))
{
int startU = strResponse.indexOf(startUrl);
int endU = strResponse.indexOf(endUrl);
Log.i("startUrl", ""+startU);
Log.i("endUrl", ""+endU);
String OldUrl = strResponse.substring(startU, endU);
int startUrlindex = OldUrl.indexOf(">");
String strUrl = OldUrl.substring(startUrlindex + 1).trim();
Log.i("Url", ""+strUrl);
}
}
catch (Exception e) {
e.printStackTrace();
}
/*imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");*/
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent,
View v, int position, long id)
{
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
public int getCount() {
Log.i("SiZE of ImageUrl", ""+imageurl.size());
return imageurl.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
/*AddAlbumDetailBean aBean = (AddAlbumDetailBean)result.get(position);
imageurl.add(aBean.thumb);*/
String strURL=imageurl.get(position);
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
URL url;
try {
url = new URL(strURL);
URLConnection conn = url.openConnection();
in=conn.getInputStream();
Bitmap bitmap1= BitmapFactory.decodeStream(in);
imageView.setImageBitmap(bitmap1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//imageView.setImageResource(imagen]);
return imageView;
}
}
public String convertStreamToString(InputStream in)
throws IOException {
if (in != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
// in.close();
}
return writer.toString();
} else {
return "";
}
}
}
XMLParser.java
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XmlParser extends DefaultHandler{
public String RootElement;
public String RecordElement;
public InputStream in;
public Object mainObj;
public Object newObj;
public boolean inProcess;
public String xmlURL;
public ArrayList<Object> Records = null;
private final String TAG = "XmlParser";
StringBuffer buffer = new StringBuffer();
String elementName;
String elementValue;
public XmlParser(InputStream is,Object tempObj)
{
in = is;
mainObj = tempObj;
Log.i("Object value", ""+mainObj);
inProcess = false;
}
public XmlParser(String strURL,Object tempObj)
{
xmlURL = strURL;
mainObj = tempObj;
inProcess = false;
}
public ArrayList<Object> ParseUrl(String rootElement ,String recordElement)
{
RootElement = rootElement;
Log.i("RootElement",RootElement);
RecordElement = recordElement;
Log.i("RecordElement", RecordElement);
try
{
URL sourceUrl = new URL(xmlURL);
Log.d("URl", xmlURL);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader reader = sp.getXMLReader();
reader.setContentHandler(this);
reader.parse(new InputSource(sourceUrl.openStream()));
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
return this.Records;
}
public ArrayList<Object> parse(String rootElement, String recordElement)
{
RootElement = rootElement;
RecordElement = recordElement;
Log.i("Root Element", ""+RootElement);
Log.i("Record Element", ""+RecordElement);
try{
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(in, this);
}catch(Exception e){
e.printStackTrace();
return null;
}
return this.Records;
}
#Override
public void startElement(String Uri, String localName,String qName,Attributes attributes) throws SAXException
{
Log.d("URl", xmlURL);
elementValue = "";
Log.i("IN STARTELEMENT", ""+elementValue);
if(localName.length() > 0)
{
Log.i("Local Name Length", ""+localName.length());
Log.i("LocalName", ""+localName);
if(localName.equalsIgnoreCase(RootElement))
{
Records = new ArrayList<Object>();
Log.i("Root element", ""+RootElement);
Log.i("Records", ""+Records);
}
else if(localName.equalsIgnoreCase(RecordElement))
{
newObj = ClassUtils.newObject(mainObj);
Log.i("Main Object", ""+mainObj);
Log.i("Record element", ""+RecordElement);
ClassUtils.objectMapping(newObj, localName, elementValue);
Log.i("Element Value", ""+elementValue);
inProcess = true;
}
}
}
#Override
public void characters(char[] ch,int start,int length) throws SAXException{
elementValue+= new String(ch,start,length).trim();
Log.i("CHARACTERS VALUE", ""+elementValue);
}
#Override
public void endElement(String Uri,String localName,String qName) throws SAXException
{
if(localName.equalsIgnoreCase(RecordElement)){
Records.add(newObj);
inProcess = false;
}
else if(inProcess){
ClassUtils.objectMapping(newObj, localName, elementValue);
}
}
}
AddAlbumDetailActivity.java
import android.util.Log;
public class AddAlbumDetailBean
{
public String data = null;
public String code = null;
public String photocount = null;
public String id = null;
public String title = null;
public String thumb = null;
public String url = null;
public AddAlbumDetailBean()
{
this("","","","","","","");
}
public AddAlbumDetailBean(String data,String code,String photocount,String id,String title,String thumb,String url)
{
this.data = data;
this.code = code;
this.photocount = photocount;
this.id = id;
this.title = title;
this.thumb = thumb;
this.url = url;
}
}
While using grid view it is not easy to Set the Image View. but you can do it by trick.
Take Button instead of the Image and set the Button Background for the Appropriate image.
After that u can able to set the Set the Button in grid view.
Thanks.

Categories

Resources