ListView - No memory

0

I'm starting to make a dates app. But I start with the first problems. I create a listview (to add the birthdays) but when I close the APP all the stored information is deleted.

My code:

MainActivity:

public class MainActivity extends AppCompatActivity {
    private Context ctx;
    private List<personas> listaProducto;
    private EditText edNombre, edDescripcion;
    ArrayAdapter<personas> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ctx=this;
        addView();
    }

    private void addView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        edDescripcion =(EditText) findViewById(R.id.edDescripcionProducto);
        edNombre =(EditText) findViewById(R.id.edNombreProducto);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listaProducto.add(get(edNombre.getText().toString(), edDescripcion.getText().toString(), R.drawable.add_sinfoto));
                adapter.notifyDataSetChanged();
                edNombre.getText().clear();
                edDescripcion.getText().clear();
            }
        });

        // create an array of Strings, that will be put to our ListActivity
        ListView listaView=(ListView) findViewById(R.id.listView);
        adapter = new ListaAdapter(MainActivity.this, getListaProductos());
        listaView.setAdapter(adapter);
        listaView.refreshDrawableState();
    }

    private List<personas> getListaProductos(){
        listaProducto= new ArrayList<personas>();
        String [] titulos;
        String [] descripciones;
        titulos=  ctx.getResources().getStringArray(R.array.titulos);
        descripciones= ctx.getResources().getStringArray(R.array.descripciones);

        int [] imagenes= new int[]{
        };

        for (int i=0; i<imagenes.length; i++){
            listaProducto.add(get(titulos[i],descripciones[i],imagenes[i]));
        }
        //listaProducto.get(0).setSelected(true);
        return listaProducto;
    }

    private personas get(String titulo, String descripcion, int imagen ) {
        return new personas(titulo, descripcion, imagen);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id){
            case R.id.menu_borrar:
                for (int i=listaProducto.size()-1; i>=0; i--){
                    if(listaProducto.get(i).isSelected()){
                        listaProducto.remove(i);
                    }
                }
                adapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

ListAdapter.java

public class ListaAdapter extends ArrayAdapter<personas> {
    private final List<personas> list;
    private final Context context;

    public ListaAdapter(Context context, List<personas> list) {
        super(context, R.layout.list_fila, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {//Un miembro protegido es accesible dentro de su clase y por instancias de clases derivadas.
        protected ImageView imageview_alimento;
        protected TextView tvTitulo;
        protected TextView tvDescripcion;
        protected CheckBox checkbox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator =LayoutInflater.from(context);// Activity.getLayoutInflater();
            view = inflator.inflate(R.layout.list_fila, null);// java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.tvTitulo = (TextView) view.findViewById(R.id.tvTitulo);
            viewHolder.tvDescripcion = (TextView) view.findViewById(R.id.tvDescripcion);
            viewHolder.imageview_alimento = (ImageView) view.findViewById(R.id.ImagView_Producto);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);

            viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override                    //checkbox ,                activado:true-false
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    personas element = (personas) viewHolder.checkbox.getTag();
                    element.setSelected(buttonView.isChecked());
                }
            });

            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(list.get(position));
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.tvTitulo.setText(list.get(position).getTitulo());
        holder.tvDescripcion.setText(list.get(position).getDescripcion());
       holder.imageview_alimento.setImageResource(list.get(position).getId_imagen());

        holder.checkbox.setChecked(list.get(position).isSelected());
        return view;
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public personas getItem(int position) {
         return super.getItem(position);
    }
}

personas.java

public class personas {
     private String titulo;
     private String descripcion;
     private int id_imagen;
     private boolean selected;

     public personas(String titulo, String descripcion, int id_imagen) {
         this.titulo = titulo;
         this.descripcion = descripcion;
         this.id_imagen = id_imagen;
         this.selected = false;
     }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public int getId_imagen() {
        return id_imagen;
    }

    public void setId_imagen(int id_imagen) {
        this.id_imagen = id_imagen;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }
}

content_main.xml

    <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:ems="10"
    android:layout_marginTop="12dp"
    android:id="@+id/edNombreProducto"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true"
    android:layout_marginEnd="66dp"
    android:hint="Nombre" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:ems="10"
    android:id="@+id/edDescripcionProducto"
    android:hint="Fecha" />

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listView" />
</LinearLayout>

list_fila

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#3F51B5"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">


    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/ImagView_Producto"

            android:background="#3F51B5"
            android:layout_height="90dp"
            android:layout_width="90dp" />

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/tvTitulo"
                    android:layout_height="wrap_content"
                    android:text="Nombre"
                    android:textColor="@android:color/background_light"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:layout_gravity="center_horizontal"
                    android:layout_weight="1"
                    android:layout_width="255dp" />

                <CheckBox
                    android:id="@+id/check"
                    android:layout_alignParentRight="true"
                    android:layout_gravity="right"
                    android:layout_height="30dp"
                    android:layout_width="30dp"
                    android:layout_weight="1" />
            </LinearLayout>

            <TextView
                android:id="@+id/tvDescripcion"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="@android:color/background_light"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="16/09/1993"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1" />
        </LinearLayout>



    </LinearLayout>


</LinearLayout>

</RelativeLayout>

What am I doing wrong? Thanks!

EDITO2:

MainActivity.java: @sioesi

public class MainActivity extends AppCompatActivity {

private Context ctx;
private List<personas> listaProducto;
private EditText edNombre, edDescripcion;
ArrayAdapter<personas> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Set<Persona> set = prefs.getStringSet("personas", null);
    List<Persona> listaProductos =new ArrayList<Persona>(set);
    ctx=this;
    addView();


}



private void addView() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    edDescripcion =(EditText) findViewById(R.id.edDescripcionProducto);
    edNombre =(EditText) findViewById(R.id.edNombreProducto);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            listaProducto.add(get(edNombre.getText().toString(), edDescripcion.getText().toString(), R.drawable.add_sinfoto));
            adapter.notifyDataSetChanged();
            edNombre.getText().clear();
            edDescripcion.getText().clear();



        }
    });

    // create an array of Strings, that will be put to our ListActivity
    ListView listaView=(ListView) findViewById(R.id.listView);
    adapter = new ListaAdapter(MainActivity.this, getListaProductos());
    listaView.setAdapter(adapter);
    listaView.refreshDrawableState();

}


private List<personas> getListaProductos(){
    listaProducto= new ArrayList<personas>();
    String [] titulos;
    String [] descripciones;
    titulos=  ctx.getResources().getStringArray(R.array.titulos);
    descripciones= ctx.getResources().getStringArray(R.array.descripciones);




    int [] imagenes= new int[]{


    };



    for (int i=0; i<imagenes.length; i++){
        listaProducto.add(get(titulos[i],descripciones[i],imagenes[i]));

    }
    //listaProducto.get(0).setSelected(true);
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    Editor edit=prefs.edit();

    Set<Persona> set = new HashSet<Persona>();
    set.addAll(listaProducto);
    edit.putStringSet("personas", set);
    edit.commit();
    return listaProducto;
}


private personas get(String titulo, String descripcion, int imagen ) {
    return new personas(titulo, descripcion, imagen);
}





@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();


    switch (id){




        case R.id.menu_borrar:

            for (int i=listaProducto.size()-1; i>=0; i--){
                if(listaProducto.get(i).isSelected()){
                    listaProducto.remove(i);

                }
            }
            adapter.notifyDataSetChanged();




            break;
        default:
            break;

    }


    return super.onOptionsItemSelected(item);
}

}

    
asked by UserNameYo 26.12.2016 в 22:54
source

2 answers

1

Your code does not have data persistence, what you add in listView lives and dies within the instance of your app. There are two ways for this:

Create a database in your application and save the data there. Or save in sharedPreferences I leave an example of the latter.

To save it

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); 
Editor editor = sharedPrefs.edit(); 
Gson gson = new Gson(); 
String json = gson.toJson(listaProductos); 
editor.putString("personas", json); 
editor.commit();

To read it

SharedPreferences sharedPrefs = 
PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = sharedPrefs.getString("personas", null);
Type type = new TypeToken < ArrayList <personas>> () {}.getType();
listaProductos = gson.fromJson(json, type);

This will solve the problem that you can not keep the data, BUT it BETTER is that you persistently do what is with a database.

I leave a tutorial complete how to create a database on Android.

    
answered by 27.12.2016 / 01:18
source
1

It is not saving you permanently because you are not using a database to store your information to reuse in case you close the app. When you are using your app, everything is saved in memory, but when you close and reopen, everything is deleted. The only way to keep it is to save it in a database and then recover it.

Some time ago, make a post where it shows how a listview is saved in a database and how to recover it. In addition, it is more optimal and it does not take long to list. I hope it serves you for

    
answered by 27.12.2016 в 01:00