How can I correctly display the view of an editable adapter?

65 Views Asked by At

I am making a list with editable options, everything marks well when I navigate down but, when I return to upload all my information is deleted, will it be that I am updated on my information model or how could I avoid this case?

public class AdapterAntefamiliares extends BaseAdapter {
    Context context;
    LayoutInflater inflater;
    private List<ModelAntfamiliares> listaObjetos = null;
    private ArrayList<ModelAntfamiliares> arrayList;

    public AdapterAntefamiliares(Context context, List<ModelAntfamiliares> listaObjetos) {
        this.context = context;
        this.inflater = inflater;
        this.listaObjetos = listaObjetos;
        this.arrayList = arrayList;
    }

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

    @Override
    public Object getItem(int position) {
        return listaObjetos.get (position);
    }

    @Override
    public long getItemId(int position) {
        return listaObjetos.get (position).getId();
    }

    private class Holder{
        CardView carName ;
        CardView tratamiento_diabetes;
        TextView tratamiento_txt;
        RadioGroup rbtn_tratamiento;
        RadioButton trata_si;
        RadioButton trata_no;
        TextView nameUserPat;
        ImageView delete_iv;
        TextView name;
        TextView cumpli_txt;
    }

    @Override
    public View getView(int i, View view, ViewGroup parent) {
        LayoutInflater inflate = LayoutInflater.from(context);

       Holder viewHolder;
        if(view==null) {
            viewHolder= new Holder();
            view=inflate.inflate(R.layout.row_sys_antfamiliares,null);
            viewHolder.carName=(CardView)view.findViewById(R.id.carName);
            viewHolder.tratamiento_diabetes=(CardView)view.findViewById(R.id.tratamiento_diabetes);
            viewHolder.tratamiento_txt=(TextView)view.findViewById(R.id.tratamiento_txt);
            viewHolder.rbtn_tratamiento=(RadioGroup)view.findViewById(R.id.rbtn_tratamiento);
            viewHolder.trata_si=(RadioButton)view.findViewById(R.id.trata_si);
            viewHolder.trata_no=(RadioButton)view.findViewById(R.id.trata_no);
            viewHolder.delete_iv=(ImageView)view.findViewById(R.id.delete_iv);
            viewHolder.nameUserPat=(TextView)view.findViewById(R.id.nameUserPat);
            viewHolder.name=(TextView)view.findViewById(R.id.name);
            viewHolder.cumpli_txt=(TextView)view.findViewById(R.id.cumpli_txt);
            view.setTag(viewHolder);
        }else{
            viewHolder=(Holder)view.getTag();
        }

        if (listaObjetos.get(i).getUser() == false){
            viewHolder.tratamiento_diabetes.setVisibility(View.VISIBLE);
            viewHolder.carName.setVisibility(View.GONE);
            viewHolder.tratamiento_txt.setText(listaObjetos.get(i).getNombre());
            viewHolder.name.setText(listaObjetos.get(i).getParentesco());
        }else{
            viewHolder.tratamiento_diabetes.setVisibility(View.GONE);
            viewHolder.carName.setVisibility(View.VISIBLE);
            viewHolder.nameUserPat.setText(listaObjetos.get(i).getComment());
        }

        // presente
        Boolean presente=listaObjetos.get(i).getPresente();

        if (listaObjetos.get(i).getUser() == false ) {
            Log.i("laura", "---NAME------ " + "posicion: " + i  + " ---- " + listaObjetos.get(i).getNombre());
        }
        if(presente==true){
            viewHolder.rbtn_tratamiento.check(R.id.trata_si);
            viewHolder.cumpli_txt.setVisibility(View.VISIBLE);
            viewHolder.name.setVisibility(View.VISIBLE);

        }else {
            viewHolder.rbtn_tratamiento.check(R.id.trata_no);
            viewHolder.cumpli_txt.setVisibility(View.GONE);
            viewHolder.name.setVisibility(View.GONE);
        }

        final SharedPreferences settings = context.getSharedPreferences("datos_usuario", 0);
        final SharedPreferences.Editor editor = settings.edit();
        String token = settings.getString("token", "noencontrado");

        //DELETE
        viewHolder.delete_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("onClick", "entra en borrar");
                if (listaObjetos.get(i).getId() != 0){
                    //llamado
                    Configuration configuration = new Configuration();
                    String url = configuration.getHost();
                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl(url)
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();

                    Services pService = retrofit.create(Services.class);
                    Call<JsonObject> response = pService.deleteFamilyBackground(String.valueOf(listaObjetos.get(i).getId()),token);
                    response.enqueue(new Callback<JsonObject>() {
                        @Override
                        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                            Log.i("LOGIN", response.toString());
                            Log.i("LOGIN", "EXITO!!!!!!!");
                            if (response.code() == 200) {
                                listaObjetos.remove(getItem(i));
                                notifyDataSetChanged();
                            } else {
                                Log.i("LOGIN", "**************** RESPONSE CODE " + response.code() + "****************");
                                if (response.code() == 500) {
                                    Toast.makeText(context, context.getString(R.string.error_server), Toast.LENGTH_LONG).show();
                                } else if (response.code() == 408) {
                                    Toast.makeText(context, context.getString(R.string.error_timeOut), Toast.LENGTH_LONG).show();
                                } else if(response.code() == 400) {
                                    Toast.makeText(context, context.getString(R.string.mensaje_error_solicitud), Toast.LENGTH_LONG).show();
                                } else if (response.code() == 401){
                                    Log.i("HOMEACTIVITY","se vencio el token");

                                    JsonObject jsonObject = Utilerias.JsonLogin(context);

                                    Configuration configuration = new Configuration();
                                    String url = configuration.getHost();
                                    Retrofit retrofit = new Retrofit.Builder()
                                            .baseUrl(url)
                                            .addConverterFactory(GsonConverterFactory.create())
                                            .build();

                                    Services pService = retrofit.create(Services.class);
                                    Call<JsonObject> responseLogin = pService.postLogin(jsonObject);
                                    responseLogin.enqueue(new Callback<JsonObject>() {
                                        @Override
                                        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                                            Log.i("LOGIN", response.toString());
                                            if (response.code() == 200) {
                                                Log.i("LOGIN", "EXITO!!!!!!!");
                                                JSONObject credenciales = null;
                                                try {
                                                    credenciales = new JSONObject(String.valueOf(response.body()));
                                                    SharedPreferences settings = context.getSharedPreferences("datos_usuario", 0);
                                                    SharedPreferences.Editor editor = settings.edit();
                                                    editor.putString("token",credenciales.getString("token"));
                                                    editor.putString("terminos",credenciales.getJSONObject("configuration").getString("terminoscondiciones"));
                                                    editor.commit();

                                                    Delete2(i,credenciales.getString("token"));

                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }

                                            } else {
                                                Log.i("LOGIN", "**************** RESPONSE CODE " + response.code() + "****************");
                                                if (response.code() == 500) {
                                                    Toast.makeText(context, context.getString(R.string.error_server), Toast.LENGTH_LONG).show();
                                                } else if (response.code() == 408) {
                                                    Toast.makeText(context, context.getString(R.string.error_timeOut), Toast.LENGTH_LONG).show();
                                                } else if(response.code() == 400) {
                                                    Toast.makeText(context, context.getString(R.string.mensaje_error_solicitud), Toast.LENGTH_LONG).show();
                                                } else if (response.code() == 401){
                                                    Toast.makeText(context, context.getString(R.string.error_autentificacion),Toast.LENGTH_LONG).show();
                                                }
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<JsonObject> call, Throwable t) {
                                            try {
                                                Log.i("LOGIN", "FALLL!!!!!!! [" + t.getCause().getLocalizedMessage() + "]");
                                                if (t.getCause().getLocalizedMessage().equals("android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)")) {
                                                    Log.i("LOGIN", "FALLL!!!!!!!" + "NO HAY CONEXIÓN A INTERNET");
                                                    Toast.makeText(context, context.getString(R.string.error_internet), Toast.LENGTH_LONG).show();
                                                }
                                                if (t.getCause().getLocalizedMessage().equals("Network is unreachable")) {
                                                    Log.i("LOGIN", "FALLL!!!!!!!" + "Network is unreachable");
                                                    Toast.makeText(context, context.getString(R.string.error_internet), Toast.LENGTH_LONG).show();
                                                }
                                            } catch (Exception e) {
                                                Toast.makeText(context, context.getString(R.string.error_internet), Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    });
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<JsonObject> call, Throwable t) {
                            try {
                                Log.i("LOGIN", "FALLL!!!!!!! [" + t.getCause().getLocalizedMessage() + "]");
                                if (t.getCause().getLocalizedMessage().equals("android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)")) {
                                    Log.i("LOGIN", "FALLL!!!!!!!" + "NO HAY CONEXIÓN A INTERNET");
                                    Toast.makeText(context, context.getString(R.string.error_internet), Toast.LENGTH_LONG).show();
                                }
                                if (t.getCause().getLocalizedMessage().equals("Network is unreachable")) {
                                    Log.i("LOGIN", "FALLL!!!!!!!" + "Network is unreachable");
                                    Toast.makeText(context, context.getString(R.string.error_internet), Toast.LENGTH_LONG).show();
                                }
                            } catch (Exception e) {
                                Toast.makeText(context, context.getString(R.string.error_internet), Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }else{
                    listaObjetos.remove(getItem(i));
                    notifyDataSetChanged();
                }

            }
        });

        viewHolder.trata_si.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listaObjetos.get(i).setPresente(true);
                viewHolder.cumpli_txt.setVisibility(View.VISIBLE);
                viewHolder.name.setVisibility(View.VISIBLE);
            }
        });

        viewHolder.trata_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listaObjetos.get(i).setPresente(false);
                viewHolder.cumpli_txt.setVisibility(View.GONE);
                viewHolder.name.setVisibility(View.GONE);
            }
        });

        viewHolder.name.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
            }
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                SpannableString contentText = new SpannableString(((TextView) viewHolder.name).getText());
                listaObjetos.get(i).setNombre(contentText.toString());
                //Log.i("------------------", "-----------------> "+ s);
                //Log.i("------------------", "--------get---------> "+ listaObjetos.get(i).getNombre());
            }
        });

        viewHolder.nameUserPat.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub
            }
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                SpannableString contentText = new SpannableString(((TextView) viewHolder.nameUserPat).getText());
                listaObjetos.get(i).setComment(contentText.toString());
                //Log.i("------------------", "-----------------> "+ s);
                //Log.i("------------------", "--------get---------> "+ listaObjetos.get(i).getComment());
            }
        });

        return view;
    }
}


//model
public class ModelAntfamiliares {

    private int id;
    private String nombre;
    private String parentesco;
    private Boolean presente;
    private Boolean isUser;
    private String comment;

    public ModelAntfamiliares(int id, String nombre, String parentesco, Boolean presente, Boolean isUser, String comment) {
        this.id = id;
        this.nombre = nombre;
        this.parentesco = parentesco;
        this.presente = presente;
        this.isUser = isUser;
        this.comment = comment;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Boolean getUser() {
        return isUser;
    }

    public void setUser(Boolean user) {
        isUser = user;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getParentesco() {
        return parentesco;
    }

    public void setParentesco(String parentesco) {
        this.parentesco = parentesco;
    }

    public Boolean getPresente() {
        return presente;
    }

    public void setPresente(Boolean presente) {
        this.presente = presente;
    }
}

//List  .java

 ArrayList list_familiares;
 list_familiares.add(new ModelAntfamiliares(0, "Artritis", "madre", "true", false,""));
  adapter = new AdapterAntefamiliares(getApplicationContext(), list_familiares);
 list.setAdapter(adapter);

//row_sys_antfamiliares

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:id="@+id/tratamiento_diabetes"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:layout_marginTop="@dimen/common_padding"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:cardCornerRadius="@dimen/common_padding">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tratamiento_txt"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/activity_horizontal_margin"
                android:layout_marginTop="@dimen/common_padding"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.0"
                android:textStyle="bold"
                android:textColor="@android:color/black"/>

            <View
                android:id="@+id/barra2"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginTop="5dp"
                android:background="@android:color/darker_gray"
                android:layout_marginEnd="@dimen/activity_horizontal_margin"
                android:layout_marginStart="@dimen/activity_horizontal_margin"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@id/tratamiento_txt" />

            <RadioGroup
                android:id="@+id/rbtn_tratamiento"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@id/barra2"
                android:orientation="horizontal"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent">

                <RadioButton
                    android:id="@+id/trata_si"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/txt_si" />

                <RadioButton android:id="@+id/trata_no"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/txt_no"/>

            </RadioGroup>

            <TextView
                android:id="@+id/cumpli_txt"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/activity_horizontal_margin"
                android:text="Comentarios"
                android:textStyle="bold"
                android:textColor="@android:color/black"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@id/rbtn_tratamiento"/>

            <EditText
                android:id="@+id/name"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginBottom="30dp"
                android:layout_weight="3"
                android:hint="Escribe el vinculo familiar"
                android:padding="5dp"
                android:paddingRight="10dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/cumpli_txt"
                tools:ignore="MissingConstraints" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        android:id="@+id/carName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:layout_marginTop="@dimen/common_padding"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tratamiento_diabetes"
        app:cardCornerRadius="@dimen/common_padding">

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

            <EditText
                android:padding="5dp"
                android:id="@+id/nameUserPat"
                android:hint="Comentarios"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:layout_height="match_parent">

            </EditText>

            <ImageView
                android:id="@+id/delete_iv"
                android:src="@drawable/delete"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content">

            </ImageView>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

        <View
            android:id="@+id/barra4"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="15dp"
            android:background="@android:color/darker_gray"
            android:layout_margin="@dimen/common_padding"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@id/carName" />



</androidx.constraintlayout.widget.ConstraintLayout>

try to make the code as understandable as possible,

I had never worked with a daptor that was editable, this logic always worked for me when I only had to show info, should it be done in some other way?

1

There are 1 best solutions below

4
Yura On

in your code, i don't see that you would update the adapter after changing the data for example call such methods notifyDataSetChanged(), notifyItemChanged(item_position) etc, so after scroll ListView the adapter will have old data. For example this code

viewHolder.trata_si.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    listaObjetos.get(i).setPresente(true);
                    viewHolder.cumpli_txt.setVisibility(View.VISIBLE);
                    viewHolder.name.setVisibility(View.VISIBLE);
                }
            });

Correct version

viewHolder.trata_si.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            listaObjetos.get(i).setPresente(true);
                            notifyItemChanged(i)
                        }
                    });

about these fields

 viewHolder.cumpli_txt.setVisibility(View.VISIBLE);
 viewHolder.name.setVisibility(View.VISIBLE);

their display should depend on the value that is in the model, so when you added listaObjetos.get(i).setPresente(true); and call notifyItemChanged(i) will be called getView() method and these fields will change depending on this condition

   @Override
    public View getView(int i, View view, ViewGroup parent) {
         .............
       // presente
    Boolean presente=listaObjetos.get(i).getPresente();

    if (listaObjetos.get(i).getUser() == false ) {
        Log.i("laura", "---NAME------ " + "posicion: " + i  + " ---- " + listaObjetos.get(i).getNombre());
    }
    if(presente==true){
        viewHolder.rbtn_tratamiento.check(R.id.trata_si);
        viewHolder.cumpli_txt.setVisibility(View.VISIBLE);
        viewHolder.name.setVisibility(View.VISIBLE);

    }else {
        viewHolder.rbtn_tratamiento.check(R.id.trata_no);
        viewHolder.cumpli_txt.setVisibility(View.GONE);
        viewHolder.name.setVisibility(View.GONE);
    }

also instead of BaseAdapter it is better to use RecyclerView with RecyclerView.Adapter. About saving information from fields, you use addTextChangedListener i think this is bad, because every time after tap you need to update the model.It's better to add handling to press DONE button on keyboard, so you need to update the model and adapter once.