Android save info on return to activity - android

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.

Related

Graph Facebook won't retrieve data

I'm trying to retrieve data from Facebook using graph Facebook, like Profile Pic, Gender, Age, Name, ID & Link, I'm getting Facebook Profile Pic only successfully but other won't retrieved. Please help!
MainActivity.java
package com.example.facebookprofile;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.facebookprofile.pictureAsync.onImageDownloaded;
import com.example.facebookprofile.profileAsync.profileImplement;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements profileImplement, onImageDownloaded {
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view){
EditText enterUsername = (EditText) findViewById(R.id.enterUsername);
String s = "https://graph.facebook.com/" + enterUsername.getEditableText().toString();
pictureAsync picTask = new pictureAsync(this);
profileAsync task = new profileAsync(this);
picTask.execute(s + "/picture?type=large");
picTask.delegate = this;
task.delegate = this;
task.execute(s);
}
public static User parseJSON(String jsonString) throws JSONException{
JSONObject top = new JSONObject(jsonString);
String name = "NA";
if(top.has("name"))
name = top.getString("name");
String username = top.getString("username");
String id = "NA";
if(top.has("id"))
id = top.getString("id");
String gender = "NA";
if(top.has("gender"))
gender = top.getString("gender");
String link = "https://www.facebook.com/"+username;
if(top.has("link"))
link = top.getString("link");
User output = new User(name, username, id, gender, link);
return output;
}
#Override
public void update(User user) {
// TODO Auto-generated method stub
if(user == null){
Toast t = Toast.makeText(this, "Invalid username", Toast.LENGTH_SHORT);
t.show();
}
else{
TextView name = (TextView) findViewById(R.id.name);
TextView id = (TextView) findViewById(R.id.id);
TextView gender = (TextView) findViewById(R.id.gender);
TextView link = (TextView) findViewById(R.id.link);
name.setText(user.name);
id.setText(user.id);
gender.setText(user.gender);
link.setText(user.link);
}
}
#Override
public void setImage(Bitmap bitmap) {
// TODO Auto-generated method stub
if(bitmap != null){
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmap);
}
}
}
pictureAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class pictureAsync extends AsyncTask<String, Integer, Bitmap> {
Context context;
onImageDownloaded delegate;
public interface onImageDownloaded{
public void setImage(Bitmap bitmap);
}
public pictureAsync(Context context) {
this.context = context;
}
#Override
protected Bitmap doInBackground(String... params) {
String picUrl = params[0];
try {
URL url = new URL(picUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(delegate!=null)
delegate.setImage(result);
}
}
profileAsync.java
package com.example.facebookprofile;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class profileAsync extends AsyncTask<String, Integer, User> {
profileImplement delegate;
Context context;
ProgressDialog dialog;
public profileAsync(Context context) {
this.context = context;
}
#Override
public void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading...Please wait");
dialog.show();
}
public interface profileImplement{
public void update(User user);
}
#Override
protected User doInBackground(String... arg) {
String user = arg[0];
try {
URL url = new URL(user);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream input = connection.getInputStream();
if(input == null) return null;
Scanner networkScanner = new Scanner(input);
StringBuffer buffer = new StringBuffer();
int count = 0;
while(networkScanner.hasNext()){
String line = networkScanner.next();
count += line.length();
//publishProgress(count);
buffer.append(line);
}
networkScanner.close();
return MainActivity.parseJSON(buffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(User result) {
dialog.dismiss();
if(delegate != null)
delegate.update(result);
}
// protected void onProgressUpdate(Integer... values) {
// // TODO Auto-generated method stub
// super.onProgressUpdate(values);
// dialog.setMessage("downloaded: " + values[0]);
// }
}
User.java
package com.example.facebookprofile;
public class User {
String name;
String username;
String id;
String gender;
String link;
User(String name, String username , String id , String gender , String link){
this.name = name;
this.username = username;
this.id = id;
this.gender = gender;
this.link = link;
}
}
It is a feature gone deprecated.

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.

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 !

Android Flickr Json Caching Images

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.

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