Android displaying images dynamically - android

I've been having lots of troubles using adapter to display my images properly into my imageView. So basically I have a JSON string and I am parsing through it to get the url of each image. Then I want to display the each image with its title in a list view fashion.
I found this code online where it works perfectly when only one image needs to be displayed, but it doesn't work when I have to do this dynamically. Anyone has some good suggestions on how to get it to work? I attached parts of my codes for references.
Thank you!!!
//results => JSON string
ArrayList<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
for(int i = 0; i < results.length(); i++){
JSONObject c = results.getJSONObject(i);
// Storing each json item in variable
cover = c.getString(TAG_COVER);
String title = c.getString(TAG_TITLE);
try {
URL urlS = new URL(cover);
new MyDownloadTask().execute(urlS);
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_COVER, cover);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
resultList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, resultList,
R.layout.list_item,
new String[] {TAG_TITLE}, new int[] {
R.id.title});
setListAdapter(adapter);
And here is the image downloaded codes I found :
private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> {
#Override
protected Bitmap doInBackground(URL... params) {
URL url = params[0];
Bitmap bitmap = null;
try {
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
//is.close(); THIS IS THE BROKEN LINE
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView myImage = (ImageView) findViewById(R.id.list_image);
myImage.setImageBitmap(bitmap);
} else {
Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
}
}
}

There is pretty good library calling AQuery. YOu can use it and simple get all this stuff by writting only 2 line of code, plus it will cache all images for you and it's very good especcially if you are using them in ListView
AQuery aq = new AQuery(activity);
aq.id(R.id.image).image(url, false, true);
Also i think it will be better to use CustomAdapter. I'm not sure it's possible to handle this situation using SimpleAdapter.
Hope this will help you.

Related

How to get Images from Internet and past it in a ListView?

I'm doing my BlogApp. It gets all data from the Internet. I added three TextViews, but I have problem with getting images from JSON. I've tryed different ways but I still don't understand how exactly do this. Here is a part of my code:
private void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if (mBlogData==null){
updateDisplayForError();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (int i=0; i<jsonPosts.length(); i++){
JSONObject posts = jsonPosts.getJSONObject(i);
String title = posts.getString(KEY_TITLE); //"title"
title = Html.fromHtml(title).toString();
String author = posts.getString(KEY_AUTHOR); //"author"
author = Html.fromHtml(author).toString();
String time = posts.getString((KEY_TIME)); //"time"
time = Html.fromHtml(time).toString();
String icon = posts.getString(KEY_ICON); //"icon" (icons url)
icon = Html.fromHtml(icon).toString();
I stoped here, and don't know what to do next! Probably I should add an Adapter for my Images to convert it?
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_AUTHOR, author);
blogPost.put(KEY_TIME, time);
blogPosts.add(blogPost);
}
String[] keys = {KEY_TITLE, KEY_AUTHOR, KEY_TIME};
int[] ids = {R.id.textView1, R.id.textView2, R.id.textView3};
SimpleAdapter adapter = new SimpleAdapter(this, blogPosts, R.layout.row_layout,
keys, ids);
setListAdapter(adapter);
} catch (JSONException e) {
Log.e(TAG, "Exception caught" + e);
}
}
}
Thanks for waching this!
Volley Library makes this work quite easy and handles all other related tasks itself. You can use ImageLoader or NetworkImageView.Follow the link for how to acheive it: https://developer.android.com/training/volley/request.html
First of all download image from url then set it into your imageView.
public class LoadImageFromURL extends AsyncTask{
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("image-url");
InputStream is = url.openConnection().getInputStream();
Bitmap bitMap = BitmapFactory.decodeStream(is);
return bitMap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
yourImageview.setImageBitmap(result);
}
}
I Hope it will help you..!

how can i resolve my rejected execution execption in android gridview?

public class TopMovie extends Activity
{
GridView lv;
Vibrator vibrator;
Dialog dialog;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Log.i("Category", MainActivity.movie_Category);`enter code here`
setContentView(R.layout.new_movie);
setProgressBarIndeterminateVisibility(true);
setProgressBarIndeterminateVisibility(false);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
lv = (GridView) findViewById(R.id.grid_view);
// URL to the JSON data
String strUrl = "http://vaibhavtech.com/work/android/movie_list.php?category="
+ MainActivity.movie_Category + "&sub_category=other";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// // TODO Auto-generated method stub
vibrator.vibrate(40);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
MainActivity.movie_Id = ((TextView) arg1
.findViewById(R.id.tv_girdview_content_id)).getText()
.toString();
Log.i("Name is", MainActivity.movie_Id);
startActivity(new Intent(TopMovie.this, MovieDescription.class));
}
});
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return data;
}
protected void onPreExecute() {
// SHOW THE SPINNER WHILE LOADING FEEDS
// linlaHeaderProgress.setVisibility(View.VISIBLE);
//super.onPreExecute();
dialog=dialog=ProgressDialog.show(TopMovie.this,"", "Loading...", true);
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends
AsyncTask<String, Void, SimpleAdapter> {
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
MovieParser countryJsonParser = new MovieParser();
countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("JSON Exception1", e.toString());
}
// Instantiating json parser class
MovieParser countryJsonParser = new MovieParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try {
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
// Keys used in Hashmap
String[] from = { "image", "id", "year", "duration", "name" };
// Ids of views in listview_layout
// int[] to = {
// R.id.iv_radio_data_image,R.id.tv_radio_data_id,R.id.tv_radio_data_like,R.id.tv_radio_data_rating,R.id.tv_radio_data_listner,R.id.tv_radio_data_radio_url,R.id.tv_radio_data_name};
int[] to = { R.id.iv_girdview_content_image,
R.id.tv_girdview_content_id, R.id.tv_girdview_content_like,
R.id.tv_girdview_content_listner,
R.id.tv_girdview_content_name };
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
countries, R.layout.grid_view_content, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
lv.setAdapter(adapter);
// Setting adapter for the listview
if(dialog!=null)
dialog.dismiss();
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path", imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in
// the listview
imageLoaderTask.execute(hm);
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends
AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
#Override
protected HashMap<String, Object> doInBackground(
HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position
// in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("image", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path and
// position
return hmBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("image");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter) lv.getAdapter();
// Getting the hashmap object at the specified position of the
// listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter
.getItem(position);
// Overwriting the existing path in the adapter
hm.put("image", path);
adapter.notifyDataSetChanged();
}
}
}}
i have a gridview in which items coming from json..,sometime my applications runs but sometime gives REJECTED EXECUTION EXECPTION at " imageLoaderTask.execute(hm);",i am unable to understand how to resolve this problem.i have tried all examples and condiotions.i have used asynchtask ,custom adapetr in my code ,but no solution and answer is ocured in my code.,how can i resolve my error.please help me...:(
First you have to understand what RejectedExecutionException means. Then decide how do you want to handle it.
AsyncTask runs its tasks in an Executor. This executor uses a queue where the tasks are stored until the executor is free to pay attention to them. The default executor with a default task can handle 10 tasks at the same time and store 10 additional tasks to perform once the running ones complete. Once the spot for all these 20 tasks (10+10) it can't take any more tasks, and it lets you know by raising a RejectedExecutionException.
How can you deal with this? Depends on what you need. You can catch that exception and try again later to see if the queue has room later, or you could use a differently configured executor that (a) can perform more tasks at the same time or (b) that has a queue with more space for tasks. Some already existing executor classes can be configured with parameters more appropriate for your needs (see the documentation for Executor) or you can write your own. One such executor is ThreadPoolExecutor that you can tell what kind of queue to use (this is the executor that is used in some of the Android versions, you don't specify which version you're working with). In the documentation there's discussion about what kinds of queues there are.
Again, the decision on how to configure the executor and queue is up to you and your needs. Such as if you want to allow for unbounded creation of threads, or have a limit. Want to have a long queue of tasks or short, or even unbound.
Try this..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
imageLoaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, hm);
else
imageLoaderTask.execute(hm);
For all AsyncTask

ANDROID - How to set bitmap to simpleadapter (CLOSED)

I am working on my android application. I have been researching and trying all different ways of method on how to retrieve images from my server url and display it to my listview using SimpleAdapter.
DOWNLOAD IMAGE CODE
public Bitmap download(final String image)
{
URL myFileUrl = null;
try {
myFileUrl = new URL("http://SERVER URL/images/"+image);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
// imageLoadedHandler.sendEmptyMessage(FAILED);
} catch (IOException e) {
// imageLoadedHandler.sendEmptyMessage(FAILED);
}
return bmImg;
}
PUT DOWNLOADED IMAGE TO HASHMAP
// IMAGE HASHMAP
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TAG_PHOTO, download(c.getString(TAG_PHOTO)));
applicantsList.add(map);
Updating parsed JSON data into ListView
adapter = new SimpleAdapter(
SignUpApplicantActivity.this, applicantsList,
R.layout.list_applicant, new String[] {
TAG_UID, TAG_NAME, TAG_OVERALL,
TAG_APPLY_DATETIME, TAG_PHOTO},
new int[] { R.id.applicantUid,
R.id.applicantName,
R.id.applicantOverall,
R.id.apply_datetime, R.id.list_image});
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,String textRepresentation)
{
if((view instanceof ImageView) & (data instanceof Bitmap))
{
ImageView iv = (ImageView) view;
Bitmap bm = (Bitmap) data;
iv.setImageBitmap(bm);
return true;
}
return false;
}
});
// updating listView
setListAdapter(adapter);
After trying the above method(which i think is the closest answer from my research), the image is still not display in my application. I need some help! thanks in advance!

Make application load faster with ViewHolder class

I've made gridview application that get path of image from json. it work find but when it load it's so slow. and i try to find solution and they recommended me to use ViewHolder but I don't know how to use in my gridview application.
How can I use ViewHolder in my application? how I speed up my application?
This code work find but it load so slow.
public class MainActivity extends Activity {
String strUrl = "http://192.168.10.104/adchara1/";
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
gridView = (GridView) findViewById(R.id.lv_countries);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int positon,
long id) {
HashMap<String, Object> hm = (HashMap<String, Object>) gridView.getAdapter().getItem(positon);
String imgPath = (String) hm.get("photo"); //get downloaded image path
Intent i = new Intent(MainActivity.this, DisplayActivity.class); //start new Intent to another Activity.
i.putExtra("ClickedImagePath", imgPath ); //put image link in intent.
startActivity(i);
}
});
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(strUrl);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
iStream = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sb = new StringBuilder();
String line = "";
while((line = br.readLine()) != null){
sb.append(line + "\n");
}
iStream.close();
data = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
GridViewLoaderTask gridViewLoaderTask = new GridViewLoaderTask();
// Start parsing xml data
gridViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class GridViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
CountryJSONParser countryJsonParser = new CountryJSONParser();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
CountryJSONParser countryJsonParser = new CountryJSONParser();
// A list object to store the parsed countries list
List<HashMap<String, Object>> countries = null;
try{
// Getting the parsed data as a List construct
countries = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "frame","photo"};
// Ids of views in listview_layout
int[] to = { R.id.iv_frame,R.id.iv_photo};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
gridView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String frameUrl = (String) hm.get("frame_path");
String imgUrl = (String) hm.get("photo_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("frame_path", frameUrl);
hm.put("photo_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl;
String frameUrl;
imgUrl = (String) hm[0].get("photo_path");
frameUrl = (String) hm[0].get("frame_path");
int position = (Integer) hm[0].get("position");
URL url;
URL urlFrame;
try {
url = new URL(imgUrl);
urlFrame = new URL(frameUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+ position + ".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("photo", tmpFile.getPath());
hmBitmap.put("frame", tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position", position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
} catch (MalformedURLException e) {
return null;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("photo");
String framePath = (String) result.get("frame");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) gridView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("photo",path);
hm.put("frame", framePath);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
you should read the slide here to improve the performance.it's contain an example of using ViewHolder.
Take a look at our Google Guys at Google I/O 2010 . They had a session hosted by Google Software Engineer in Android Team, talking about ListView and related stuffs, including how to optimize listview-usage with ViewHolder class.
I think you can learn something from that.
Here is the link Google I/O 2010 - ListView Session

using drawable in simpleadapter

I am working on an Android application. In my app I have to use a adapter. So I used simple adapter.
int[] flags = new int[]{
R.drawable.img1,
R.drawable.img2,
};
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<number.size();i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", number.get(i));
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
String[] from = { "flag","txt"};
// Ids of views in listview_layout
int[] send = { R.id.flag,R.id.txt};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.autocomplete_layout, from, send);
Now I want to use my own drawable arraylist instead of drawable from resourse.
Drawable d="some downloaded image from server"
Now I want to use the above d in hashmap.
hm.put("flag", d.toString() );
The above stamenet is not working.I know its beacause earlier i send image ids. Now I am converting image to string.
So I have to put my image to hashmap hm. But how can I put if I use my downloaded drawable image?.
// this may helps you
[1] First of all You need
HashMap<String, Object> hm= new HashMap<String, Object>();
Bitmap bmImg;
[2] For Online Image need 1 Function to get it with Bitmap object
public void downloadFile(final String fileUrl)
{
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
// imageLoadedHandler.sendEmptyMessage(FAILED);
} catch (IOException e) {
// imageLoadedHandler.sendEmptyMessage(FAILED);
}
}
// for put online image in hasmap with thread and require data fill here
for(int i=0;i<number.size();i++){
HashMap<String, Object> hm= new HashMap<String, Object>();
new Thread() {
public void run()
{
downloadFile(smtLink[ii]);
hm.put("image", bmImg);
};
}.start();
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
// and need viewbinder class
class MyViewBinder implements ViewBinder
{
#Override
public boolean setViewValue(View view, Object data,String textRepresentation)
{
if((view instanceof ImageView) & (data instanceof Bitmap))
{
ImageView iv = (ImageView) view;
Bitmap bm = (Bitmap) data;
iv.setImageBitmap(bm);
return true;
}
return false;
}
}
// now set this data with simple adapter like below, Here change as per your requirement with your adpter
adapater1 = new SimpleAdapter(News.this, list, R.layout.homrow, new String[] { "im", "Titel", "Sourcetag", "Date1","im1" },
new int[] { R.id.homerowmain,R.id.homerowtitle, R.id.homerowsourcetag,R.id.homerowdate, R.id.homerowimgaerrow });
adapater1.setViewBinder(new MyViewBinder());
itemlist.setAdapter(adapater1);
Try this
Integer[] flags = {
R.drawable.Yourimg1, R.drawable.Yourimg2,
R.drawable.Yourimg3, R.drawable.Yourimg4,
};
Make sure that in your import you don't have android.R ...And add your own R file :)

Categories

Resources