Problem when displaying Data in ListView Android

1

To show the data from the database I use a do-while loop that runs through the whole table but when adding the data to the vector I do not know what happens that are not added well and in the listView only a group is shown and if I add another one it is not shown and if I delete the one that is being shown it is not deleted from listView until I restart the app. It does not give any error or anything. If I put the data manually in the vector if they are shown in listView

I leave the code:

Database:

package com.app.a2.studio.android.aprendiendo.appmanejarcuentas.DataBase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class BaseDeDatos extends SQLiteOpenHelper {

    public static final String DB_NAME = "AppCuentas.db";

    public static final String TABLE_FOLDERS = "Folders";

    public static final String TF_COLOM_ID = "_ID";
    public static final String TF_COLOM_NUMBER_USERS = "NumberUsers";
    public static final String TF_COLOM_NAME = "Nombre";

    public static final String TABLE_USUARIOS = "Usuarios";
    public static final String TU_COLOM_PRIMARY_ID = "_ID";
    public static final String TU_COLOM_FOLDER = "Folder";
    public static final String TU_COLOM_NAME = "Nombre";
    public static final String TU_COLOM_DESCRIPTION = "Descripcion";
    public static final String TU_COLOM_PAGOS = "Pagos";


    public BaseDeDatos(Context context) {
        super(context, DB_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_FOLDERS
                + " (" + TF_COLOM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + TF_COLOM_NAME + " TEXT, "
                + TF_COLOM_NUMBER_USERS + " INTEGER) ");

        sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_USUARIOS
                + " (" + TU_COLOM_PRIMARY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + TU_COLOM_FOLDER + " TEXT, "
                + TU_COLOM_NAME + " TEXT, "
                + TU_COLOM_DESCRIPTION + " TEXT, "
                + TU_COLOM_PAGOS + " INTEGER) ");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXIST" + TABLE_FOLDERS);
        sqLiteDatabase.execSQL("DROP TABLE IF EXIST" + TABLE_USUARIOS);
        onCreate(sqLiteDatabase);

    }

    public boolean addData(String name, int numberUsers){
        SQLiteDatabase db = getWritableDatabase();

        ContentValues valuesFolders = new ContentValues();

        valuesFolders.put(TF_COLOM_NAME, name);
        valuesFolders.put(TF_COLOM_NUMBER_USERS, numberUsers);

        long resultFolders = db.insert(TABLE_FOLDERS, null, valuesFolders);

        if(resultFolders == -1){
            return false;
        }
        else {
            return true;
        }
    }

    public boolean addData(int folder, String name, String description, float pagos){
        SQLiteDatabase db = getWritableDatabase();

        ContentValues valuesUsuarios = new ContentValues();

        valuesUsuarios.put(TU_COLOM_FOLDER, folder);
        valuesUsuarios.put(TU_COLOM_NAME, name);
        valuesUsuarios.put(TU_COLOM_DESCRIPTION, description);
        valuesUsuarios.put(TU_COLOM_PAGOS, pagos);

        long resultUsuarios = db.insert(TABLE_USUARIOS, null, valuesUsuarios);

        if(resultUsuarios == -1){
            return false;
        }
        else {
            return true;
        }
    }

    public Cursor getAllFoldersData(){
        String folderColoms[] = {TF_COLOM_ID, TF_COLOM_NAME, TF_COLOM_NUMBER_USERS};
        Cursor c = this.getReadableDatabase().query(TABLE_FOLDERS, folderColoms, null, null, null, null, null);
        return c;
    }

    public Integer deleteFolder(String folderID){
        SQLiteDatabase db = this.getWritableDatabase();

        //Integer usuers = db.delete(TABLE_USUARIOS, "Folder = ?", new String[] { folderID });
        Integer folders = db.delete(TABLE_FOLDERS, "_ID = ?", new String[] { folderID });

        if(folders > 0){
            return 1;
        }
        else {
            return -1;
        }
        /*
        if(usuers > 0){
            if(folders > 0){
                return 1;
            }
            else {
                return -1;
            }
        }
        else {
            return -1;
        }
        */

    }
}

The adapter:

package com.app.a2.studio.android.aprendiendo.appmanejarcuentas.DataBase;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.a2.studio.android.aprendiendo.appmanejarcuentas.R;


public class FolderAdapter extends ArrayAdapter<FolderDatos> {

    private Context context;
    private int layoutResourceID;
    private FolderDatos[] folderDatos = null;

    public FolderAdapter(Context context, int layoutResourceID, FolderDatos[] folderDatos){
        super(context, layoutResourceID, folderDatos);

        this.context = context;
        this.layoutResourceID = layoutResourceID;
        this.folderDatos = folderDatos;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        View row = convertView;
        FolderDatosHolder holder = null;

        if(row == null){
            LayoutInflater folderInflate = ((Activity)context).getLayoutInflater();

            row = folderInflate.inflate(layoutResourceID, parent, false);

            holder = new FolderDatosHolder();
            holder.groupIcon = (ImageView) row.findViewById(R.id.iv_lvd1_GroupImage);
            holder.groupName = (TextView) row.findViewById(R.id.tv_lvd1_GroupTitle);
            holder.numberUsers = (TextView) row.findViewById(R.id.tv_lvd1_numberUsers);
            holder.ID = (TextView) row.findViewById(R.id.tv_lvd1_ID);

            row.setTag(holder);
        }

        else {
            holder = (FolderDatosHolder) row.getTag();
        }

        FolderDatos folderDatos = this.folderDatos[position];

        holder.groupIcon.setImageResource(folderDatos.icon);
        holder.groupName.setText(folderDatos.title);
        holder.numberUsers.setText("Miembros: " + String.valueOf(folderDatos.numberUsers));
        holder.ID.setText(String.valueOf(folderDatos.ID));

        return (row);
    }

    private static class FolderDatosHolder{
        ImageView groupIcon;
        TextView groupName;
        TextView numberUsers;
        TextView ID;
    }
}

The FolderData class:

package com.app.a2.studio.android.aprendiendo.appmanejarcuentas.DataBase;



public class FolderDatos {

    public int icon;
    public String title;
    public int ID;
    public int numberUsers;

    public FolderDatos(int icon, String title, int numberUsers, int ID){
        this.icon = icon;
        this.title = title;
        this.numberUsers = numberUsers;
        this.ID = ID;
    }
}

The complete main activity:

     package com.app.a2.studio.android.aprendiendo.appmanejarcuentas.Screens;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.app.a2.studio.android.aprendiendo.appmanejarcuentas.DataBase.BaseDeDatos;
import com.app.a2.studio.android.aprendiendo.appmanejarcuentas.DataBase.FolderAdapter;
import com.app.a2.studio.android.aprendiendo.appmanejarcuentas.DataBase.FolderDatos;
import com.app.a2.studio.android.aprendiendo.appmanejarcuentas.R;

import java.util.ArrayList;
import java.util.List;


public class MainScreen extends AppCompatActivity {

    private BaseDeDatos db;
    private Toolbar toolbar;
    private String bitMapImage;
    private ListView listview;

    private String APP_DIRECTORY = "MajearCuentasApp/";
    private String MEDIA_DIRECTORY = APP_DIRECTORY + "media";
    private String TEMPORAL_PICTURE_NAME = "temporalPicture.png";

    private final int PHOTO_CODE = 100;
    private final int SELECT_PICTURE = 200;

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

        variableCastings();
        createListView();
        createToolBar();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_toolbar, menu);
        return true;
    }

    private void variableCastings(){
        toolbar = (Toolbar) findViewById(R.id.tb_ams_ToolbarMain);
        listview = (ListView) findViewById(R.id.lv_ams_ListView);
    }

    private void createListView() {
        db = new BaseDeDatos(this);
        Cursor cursor = db.getAllFoldersData();
        FolderDatos[] folderDatos = new FolderDatos[cursor.getCount()];
        FolderAdapter folderAdapter;

        int ID, numberUsers, counter = 0;
        String nombre;

        if(cursor.moveToFirst()){
            do {
                ID = cursor.getInt(0);
                numberUsers = cursor.getInt(2);
                nombre = cursor.getString(1);

                folderDatos[counter] = new FolderDatos(R.drawable.ic_group, nombre, numberUsers, ID);
                counter++;
            }while (cursor.moveToNext());
        }

            folderAdapter = new FolderAdapter(this, R.layout.listview_design1, folderDatos);

        folderAdapter.notifyDataSetChanged();
        listview.setAdapter(folderAdapter);

        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView tv_ID = (TextView) view.findViewById(R.id.tv_lvd1_ID);
                createOptionsAlertDialog(tv_ID.getText().toString());
                return true;
            }
        });
    }


    private void createOptionsAlertDialog(final String ID){
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainScreen.this);
        final AlertDialog dialog = alertDialogBuilder.create();
        LayoutInflater inflater = getLayoutInflater();

        View v = inflater.inflate(R.layout.options_menu_items, null);

        dialog.setView(v);

        dialog.show();

        Button btnEliminar = (Button) v.findViewById(R.id.btn_omi_btnDelete);
        Button bntEditar = (Button) v.findViewById(R.id.btn_omi_btnEditar);
        Button bntCancel = (Button) v.findViewById(R.id.btn_omi_btnCancel);

        btnEliminar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Integer isDeleted = db.deleteFolder(ID);

                if(isDeleted > 0){
                    Toast.makeText(getApplicationContext(), "Borrado", Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(getApplicationContext(), "Error al borrar", Toast.LENGTH_SHORT).show();
                }

                dialog.cancel();
            }
        });
    }

    private void createToolBar(){
        //setSupportActionBar(toolbar);
        toolbar.setTitle("AppWIP");
        toolbar.inflateMenu(R.menu.menu_toolbar);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case (R.id.item_addFolder):
                        createFolderAletrDialog();
                        return true;

                    case (R.id.item_addIndividual):

                        return true;

                    default:
                        return false;
                }
            }
        });
    }

    private void createFolderAletrDialog(){
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainScreen.this);
        final AlertDialog dialog = alertDialogBuilder.create();
        LayoutInflater inflater = getLayoutInflater();

        View v = inflater.inflate(R.layout.create_folder_design, null);

        dialog.setView(v);

        dialog.show();

        final EditText etGroupName = (EditText) v.findViewById(R.id.et_cfd_FolderName);
        final ImageView ivGroupIcon = (ImageView) v.findViewById(R.id.iv_cfd_GroupImage);
        Button btnAddImage = (Button) v.findViewById(R.id.btn_cfd_AddPhoto);
        Button btnCrear = (Button) v.findViewById(R.id.btn_cfd_ADCrear);
        Button btnCancel = (Button) v.findViewById(R.id.btn_cfd_ADCancel);

        /*
        btnAddImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent galeryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                galeryIntent.setType("image/*");
                startActivityForResult(galeryIntent.createChooser(galeryIntent, "Sececiona Imagen"), SELECT_PICTURE);
            }
        });
        */

        btnCrear.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                if (etGroupName.getText().toString().isEmpty()){
                    Toast.makeText(getApplicationContext(), "No puedes crear un grupo sin nombre", Toast.LENGTH_SHORT).show();
                }
                else {
                    addDataToFolderTable(etGroupName.getText().toString(), 0);
                    dialog.cancel();
                }
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                dialog.cancel();
            }
        });
    }

    private void addDataToFolderTable(String name, int numberUsers) {
        boolean isInserted = db.addData(name, numberUsers);
        if(isInserted){
            Toast.makeText(getApplicationContext(), "Guardado", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "Error al guardad", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case (SELECT_PICTURE):
                if(requestCode == RESULT_OK){
                    // Tengo la imagen
                    Uri path = data.getData();
                    //Toast.makeText(getApplicationContext(), "ha llegado", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

}
    
asked by ProRiderZ115 02.02.2017 в 15:38
source

2 answers

0

If what you want is to add the data you have two details that prevent this task, first the array FolderDatos[] is not properly sized, only accept a record:

 FolderDatos[] folderDatos = new FolderDatos[0];

You can dimesionarlo with the amount of elements contained in the cursor:

 FolderDatos[] folderDatos = new FolderDatos[cursor.getCount()];

Secondly, you should not create another instance of the FolderDatos[] array in each loop,

  folderDatos = new FolderDatos[]{new FolderDatos(R.drawable.ic_group, nombre, numberUsers, ID)};

You must add each new element to the array:

 int counter = 0;
 if(cursor.moveToFirst()){
            do {
                ID = cursor.getInt(0);
                numberUsers = cursor.getInt(2);
                nombre = cursor.getString(1);

              // folderDatos = new FolderDatos[]{new FolderDatos(R.drawable.ic_group, nombre, numberUsers, ID)};
              folderDatos[counter] = new FolderDatos(R.drawable.ic_group, nombre, numberUsers, ID);
            counter++;
            }while (cursor.moveToNext());
        }

with this at the end you will get an array folderDatos[] containing all the data, not just one.

To update the Adapter data visually, perform it using notifyDataSetChanged () :

folderAdapter.notifyDataSetChanged();
    
answered by 02.02.2017 / 19:27
source
0

After updating the list inside the adapter, you must call notifyDataSetChanged () to update the list.

listview.setAdapter(folderAdapter);
folderAdapter.notifyDataSetChanged();

The way you prepare the data is not correct either. Why is this code wrong? I already answered it. here .

    
answered by 02.02.2017 в 16:19