2
I’m trying to display images from the web in a ListView
, but they appear out of order, on the wrong lines and change position with each update of Activity.
Activity:
public class ListarProdutosActivity extends Activity {
DataBaseHandler db = new DataBaseHandler(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] from = new String[] {
DataBaseHandler.KEY_PRODUTOS_DESCRICAO, DataBaseHandler.KEY_PRODUTOS_VALOR, DataBaseHandler.KEY_PRODUTOS_IMAGE
};
int[] to = {
R.id.txtDescricao, R.id.txtValor, R.id.logo
};
Cursor cursor = db.listarProdutos();
@SuppressWarnings("deprecation")
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_produtos, cursor, from, to);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
/** Binds the Cursor column defined by the specified index to the specified view */
public boolean setViewValue(View view, final Cursor cursor, final int columnIndex) {
final ImageView imgView = (ImageView) view.findViewById(R.id.logo);
if (view.getId() == R.id.logo) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.v("aviso", "image");
Drawable image = getImagem(cursor.getString(columnIndex));
imgView.setImageDrawable(image);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
return true;
}
return false;
}
});
}
public Drawable getImagem(String image) throws Exception {
URL url = new URL(image);
InputStream is = (InputStream) getObjeto(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
}
private Object getObjeto(URL url) throws MalformedURLException, IOException {
Object content = url.getContent();
return content;
}
}
Or if anyone knows a better way to do that, I appreciate the suggestions.
Opa, follow this example: http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_example/index.php? view=article_discription&aid=112&aaid=134 Here it creates a Holder that saves the view state at that position, and still ensures the fluidity of the list.
– Italo Marcel