|
||
|
![]() |
![]() |
Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android |
![]() |
|
Herramientas |
#1
|
||||
|
||||
Problema con listview
Saludos compañeros , tengo un problema con un listview el cual carag datos de una bd sqlite
el codigo para actualizar la lista lo tengo en on resume del activity y seria asi: Código:
LoadRecipes lore = new LoadRecipes(this); lore.execute(new RecetasSQLiteHelper(this,RecetasSQLiteHelper.TABLE_NAME, null, 1)); El error que me da ese este: Código:
06-12 18:45:49.418: E/AndroidRuntime(17768): FATAL EXCEPTION: main 06-12 18:45:49.418: E/AndroidRuntime(17768): java.lang.OutOfMemoryError 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:493) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:549) 06-12 18:45:49.418: E/AndroidRuntime(17768): at com.example.mychefexperiences.ListAdapter.getView(ListAdapter.java:75) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.AbsListView.obtainView(AbsListView.java:2466) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.ListView.makeAndAddView(ListView.java:1772) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.ListView.fillDown(ListView.java:672) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.ListView.fillFromTop(ListView.java:732) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.ListView.layoutChildren(ListView.java:1625) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.AbsListView.onLayout(AbsListView.java:2296) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.View.layout(View.java:11345) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.ViewGroup.layout(ViewGroup.java:4224) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.RelativeLayout.onLayout(RelativeLayout.java:980) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.View.layout(View.java:11345) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.ViewGroup.layout(ViewGroup.java:4224) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.FrameLayout.onLayout(FrameLayout.java:431) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.View.layout(View.java:11345) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.ViewGroup.layout(ViewGroup.java:4224) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1658) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1516) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.LinearLayout.onLayout(LinearLayout.java:1429) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.View.layout(View.java:11345) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.ViewGroup.layout(ViewGroup.java:4224) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.widget.FrameLayout.onLayout(FrameLayout.java:431) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.View.layout(View.java:11345) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.ViewGroup.layout(ViewGroup.java:4224) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1493) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2452) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.os.Handler.dispatchMessage(Handler.java:99) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.os.Looper.loop(Looper.java:137) 06-12 18:45:49.418: E/AndroidRuntime(17768): at android.app.ActivityThread.main(ActivityThread.java:4476) 06-12 18:45:49.418: E/AndroidRuntime(17768): at java.lang.reflect.Method.invokeNative(Native Method) 06-12 18:45:49.418: E/AndroidRuntime(17768): at java.lang.reflect.Method.invoke(Method.java:511) 06-12 18:45:49.418: E/AndroidRuntime(17768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:816) 06-12 18:45:49.418: E/AndroidRuntime(17768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:583) 06-12 18:45:49.418: E/AndroidRuntime(17768): at dalvik.system.NativeStart.main(Native Method) |
|
#2
|
||||
|
||||
__________________
El mejor Cuatro en Raya de Android (Hilo en HTCMania, Play Store) ¡Un millón de descargas!
|
#3
|
||||
|
||||
Bueno he visto que la solución esta en softreference , estoy iniciándome en java todavía no domino muchas de las clases de este , supongo que el softrefernce lo debo aplicar en el adapter del list que es donde tira error al cargar el bitmap , mi adaptaer es este:
Código:
public class ListAdapter extends BaseAdapter { Context context; ArrayList<Recipes> arr; static final Uri UriDefault = Uri.parse("android.resource://com.example.mychefexperiences/" + R.drawable.ic_default); public ListAdapter(Context context, ArrayList<Recipes> arr){ super(); this.context=context; this.arr=arr; } @Override public int getCount() { return arr.size(); } @Override public Object getItem(int position) { return arr.get(position); } @Override public long getItemId(int position) { return position; } private class ViewHolder { ImageView image; TextView nombre; TextView tag; TextView date; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); holder = new ViewHolder(); if (convertView == null) { convertView = mInflater.inflate(R.layout.item_list, null); holder.image=(ImageView)convertView.findViewById(R.id.imgEdit); holder.nombre = (TextView) convertView.findViewById(R.id.textView1); holder.tag=(TextView) convertView.findViewById(R.id.textView2); holder.date=(TextView) convertView.findViewById(R.id.textView3); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { Recipes rowItem = arr.get(position); holder.nombre.setText(rowItem.getnombre()); holder.tag.setText(rowItem.gettag()); holder.date.setText(rowItem.getdate()); //Uri imgUri= fileExists(Uri.parse(rowItem.getrutaimg()))?Uri.parse(rowItem.getrutaimg()):this.UriDefault; holder.image.setImageURI(Uri.parse(rowItem.getrutaimg())); }catch(Exception ex){ ex.printStackTrace(); } return convertView; } } yo por mi parte sigo informandome sobre ello en la documentación de java , gracias ;) Última edición por rafaxplayer Día 17/06/13 a las 11:27:28. |
#4
|
||||
|
||||
Creo que el problema te viene de que las imágenes que usas son demasiado grandes. Qué resolución tiene cada fichero de imagen y cuántas se muestran a la vez en pantalla?
__________________
El mejor Cuatro en Raya de Android (Hilo en HTCMania, Play Store) ¡Un millón de descargas!
|
#5
|
||||
|
||||
Pero como digo solo me falla al redibujar , osea al dar el botón de atrás o acceder al activity list pausado o cambiar de orientación del dispositivo. Última edición por rafaxplayer Día 17/06/13 a las 19:33:00. |
#6
|
||||
|
||||
El problema está aquí:
holder.image.setImageURI(Uri.parse(rowItem.getruta img())); Cada vez que un elemento se tiene que volver a dibujar vuelves a cargarlo desde su URI, lo que implica tenerlo que volver a descodificar y por tanto a ocupar memoria. Soluciones hay muchas, como por ejemplo: Guardar la relación de URI y Bitmap en un HashMap, así si ya la tienes cargada previamente no volverás a ocupar memoria. Si a esto además le añades que lo que almacenas en el HashMap sean SoftReferences o WeakReferences el sistema se encargará de liberarte la memoria cuando mejor le convenga, sin preocuparte de tener que hacerlo tú. Otra solución es usar el Universal Image Loader: https://github.com/nostra13/Android-...l-Image-Loader Realmente está pensado para cargar imágenes desde Internet y cachearlas (para eso la uso yo), pero también lo puedes usar para imágenes locales. Te hará toda la gestión de la memoria ella sola. Aunque es una librería un poco compleja de "inicializar", pero una vez que la conoces y dominas es casi imprescindible para tratar con imágenes en Android. |
#7
|
||||
|
||||
aja , hashmap otro concepto nuevo añadido al softrefence que debo estudiar ,los pondré en practica haber que saco en claro...
Algún ejemplo practico de uso parecido a mi proyecto? , con sqlite,listview y imageview? al final estos son los que me ayudan a comprender mas rápido y mejor el funcionamiento. Gracias por la respuesta ;) |
#8
|
||||
|
||||
Bueno ya puestos en materia he decidido usar el hasmap y softreference , antes yo para crear objeto usaba un setter ,getter llamado "Recipes" el cual era asi:
Código:
public class Recipes { private int ID; private String nombre; private String tag; private String date; private String Ingredientes; private String como; private String rutaimg; public void Setid(int id){ this.ID=id; } public int getId(){ return this.ID; } public void Setnombre(String nombre){ this.nombre=nombre; } public String getnombre(){ return this.nombre; } public void Settag(String tag){ this.tag=tag; } public String gettag(){ return this.tag; } public void Setdate(String date){ this.date=date; } public String getdate(){ return this.date; } public void SetIngredientes(String Ingredientes){ this.Ingredientes=Ingredientes; } public String getIngredientes(){ return this.Ingredientes; } public void Setcomo(String como){ this.como=como; } public String getcomo(){ return this.como; } public void Setrutaimg(String rutaimg){ this.rutaimg=rutaimg; } public String getrutaimg(){ return this.rutaimg; } } Y por otro lado no entiendo como hacer para que sea softreference , no lo acabo de entender ;) Última edición por rafaxplayer Día 19/06/13 a las 06:14:51. |
#9
|
||||
|
||||
Bueno al final he pasado todos los valores por un hashmap y no soluciona el problema de memoria al redibujar , ahora estoy con pasar el hash de la imagen por un softreference , pero no e funciona.. de la manera que lo hago no carga la imagen los demas valores del hash sin problemas , algo no he entendido bien todavia de este tema ;(
Codigo de carga: Código:
ArrayList<HashMap<String,Object>> arr = db.GetAllRecipes(); lt=(ListView)findViewById(R.id.listRecetas); String[] from={"NAME","TAG","DATE","IMG"}; int[] to={R.id.textView1,R.id.textView2,R.id.time, R.id.imgEdit}; adp = new SimpleAdapter(context, arr, R.layout.item_list, from, to); lt.setAdapter(adp); Código:
public ArrayList<HashMap<String,Object>> GetAllRecipes(){ ArrayList<HashMap<String,Object>> arr = new ArrayList<HashMap<String,Object>>(); arr.clear(); Cursor cur = this.getReadableDatabase().query(TABLE_NAME, new String[]{KEY_ID,KEY_NAME,KEY_TAG,KEY_DATE,KEY_INGREDIENTES,KEY_COMO,KEY_RUTAIMG}, null, null, null, null, null); cur.moveToFirst(); while(!cur.isAfterLast()){ try{ HashMap<String,Object> re = CursorToHashMap(cur); arr.add(re); cur.moveToNext(); }catch(Exception e){ e.printStackTrace();} } cur.close(); return arr; } public HashMap<String,Object> CursorToHashMap(Cursor cur) { HashMap<String,Object> re = new HashMap<String,Object>(); re.put("ID",String.valueOf(cur.getInt(cur.getColumnIndex(RecetasSQLiteHelper.KEY_ID)))); re.put("NAME",cur.getString(cur.getColumnIndex(RecetasSQLiteHelper.KEY_NAME))); re.put("TAG",cur.getString(cur.getColumnIndex(RecetasSQLiteHelper.KEY_TAG))); re.put("DATE",cur.getString(cur.getColumnIndex(RecetasSQLiteHelper.KEY_DATE))); re.put("IGREDIENTES",cur.getString(cur.getColumnIndex(RecetasSQLiteHelper.KEY_INGREDIENTES))); re.put("COMO",cur.getString(cur.getColumnIndex(RecetasSQLiteHelper.KEY_COMO))); //-9Uri uri = Uri.parse(cur.getString(cur.getColumnIndex(RecetasSQLiteHelper.KEY_RUTAIMG))); try{ //ContentResolver cr = con.getContentResolver(); //InputStream in = cr.openInputStream(uri); //Bitmap bm = BitmapFactory.decodeFile(uri.getPath()); re.put("IMG",new SoftReference<Uri>(Uri.parse(cur.getString(cur.getColumnIndex(RecetasSQLiteHelper.KEY_RUTAIMG))))); }catch(Exception e) { Log.e("error","no rula",e); } ret |