当我编辑值时,我仅从位置0获得项目并将所有项目替换为相同的值

时间:2018-11-23 05:02:35

标签: android-recyclerview sql-update android-sqlite recycler-adapter

伙计们,我太绝望了。编辑创建的项目的值时,重新输入片段后,我只会从位置0获得该项目,并从位置0开始将所有项目替换为与我编辑的值相同的所有项目。然后,当我删除任何项目时,一旦我重新输入片段,它将全部删除。很明显,我编辑时所有项目都已替换为相同的ID。 在这里,我通过了代码。希望您能对我有所帮助,谢谢。

我的用户表

public class UserTable{

public static final String TABLE_NAME = "Usuarios";
public static final String ID = "Usuarios_id";
public static final String USUARIOS_NAME = "Usuario_name";
public static final String NUMERO_NAME = "numero_name";
public static final String CLASE_NAME = "clase_name";
public static final String[] PROJECTION =
        {ID, USUARIOS_NAME, NUMERO_NAME, CLASE_NAME};

public static final String CMD_CREATE_TABLE =
        "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ( "
                + ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "
                + USUARIOS_NAME + " TEXT , "
                + NUMERO_NAME + " TEXT , "
                + CLASE_NAME + " TEXT "
                + " );";
public static int id;
private SQLiteDatabase db;

public static ArrayList<UsuariosModel> getByArg(SQLiteDatabase db, String clase_name) {
    Cursor c = db.query(
            true,
            UserTable.TABLE_NAME,
            UserTable.PROJECTION,
            CLASE_NAME + " = ?",
            new String[]{clase_name},
            //null,
            //null,
            null,
            null,
            null, null
    );
    //BATCH_ID+" = ?"
    // new String[]{String.valueOf(id)}

    Log.i("DatabaseContentCount", c.getCount() + "");

    ArrayList<UsuariosModel> students = new ArrayList<>();
    while (c.moveToNext()) {
        students.add(
                new UsuariosModel(
                        c.getInt(c.getColumnIndexOrThrow(ID)),
                        c.getString(c.getColumnIndexOrThrow(USUARIOS_NAME)),
                        c.getString(c.getColumnIndexOrThrow(NUMERO_NAME)),
                        c.getString(c.getColumnIndexOrThrow(CLASE_NAME))
                )

        );
    }
    c.close();
    return students;

}

public static int deleteByBatchName(SQLiteDatabase db, String name) {
    /*
    We can just delete the parent expense row.
    The ON DELETE CASCADE clause, will make sure the
    refuel row is also deleted.
     */
    try {
        return db.delete(TABLE_NAME, CLASE_NAME + "= '" + name + "'", null);

       db.execSQL("UPDATE " + TABLE_NAME + " set " + ID + " = (student_id-1) WHERE " + BatchTable.ID + " > " + id);

       db.delete("SQLITE_SEQUENCE","NAME = ?",new String[]{TABLE_NAME});

    } catch (NullPointerException e) {
        e.printStackTrace();
        return 0;
    }
}

public static int deleteByStudentName(SQLiteDatabase db, String name) {
    /*
    We can just delete the parent expense row.
    The ON DELETE CASCADE clause, will make sure the
    refuel row is also deleted.
     */
    try {

        String query = "SELECT " + ID + " FROM " + TABLE_NAME + " WHERE " + USUARIOS_NAME + " = ?";

        Cursor cursor = db.rawQuery(query, new String[]{name});
        if (cursor != null) {
            cursor.moveToFirst();
            id = cursor.getInt(cursor.getColumnIndexOrThrow(ID));
        }

        int result = db.delete(TABLE_NAME, USUARIOS_NAME + "= ? ", new String[]{name});

        Log.i("FetchID", id + "");
        db.execSQL("UPDATE " + TABLE_NAME + " set " + ID + " = (Usuarios_id-1) WHERE " + ID + " > " + id);
        db.delete("SQLITE_SEQUENCE", "NAME = ?", new String[]{TABLE_NAME});

        return result;
    } catch (NullPointerException e) {
        e.printStackTrace();
        return 0;
    }
}
public static long save(SQLiteDatabase db, UsuariosModel usuarios) {

    ContentValues cv = new ContentValues();
    Log.i("StudentDetails", usuarios.getusuarios_name() + " " + usuarios.getnumero_name() + " " + usuarios.getclase_name());

    cv.put(USUARIOS_NAME, usuarios.getusuarios_name());
    cv.put(NUMERO_NAME, usuarios.getnumero_name());
    cv.put(CLASE_NAME, usuarios.getclase_name());

    //Log.i("himanshu", cv.size() + "");

    long result = db.insert(TABLE_NAME, ID, cv);

    Log.e("Result After Inserting", "" + result);
    return result;
}

public static long  updateItem(SQLiteDatabase db, UsuariosModel usuarios) {

   ContentValues contentValues = new ContentValues();
   contentValues.put("Usuario_name", usuarios.getusuarios_name());

    long  pepe = db.update( TABLE_NAME,  contentValues,   ID, null);

   return pepe;
}
}

我的模型类

public class UsuariosModel {

long id;
String usuarios_name;
String numero_name;
String clase_name;



public UsuariosModel(long id, String usuarios_name, String  numero_name, String clase_name)
{
    this.id=id;
    this.usuarios_name=usuarios_name;
    this. numero_name= numero_name;
    this.clase_name=clase_name;
}
public long getId() {
    return id;
}

public UsuariosModel(String usuarios_name, String  numero_name, String clase_name)
{

    this.usuarios_name=usuarios_name;
    this. numero_name= numero_name;
    this.clase_name=clase_name;
}

public String getusuarios_name() {
    return usuarios_name;
}

public void setusuarios_name(String usuarios_name) {
    this.usuarios_name = usuarios_name;
}

public String getnumero_name() {
    return numero_name;
}

public void setnumero_name(int numero_id) {
    this.numero_name = numero_name;
}

public String getclase_name() {
    return clase_name;
}

public void setclase_name(String clase_name) {
    this.clase_name = clase_name;
}


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

}

}

我的RecyclerAdapter

public class RecyclerUser extends 
RecyclerView.Adapter<RecyclerUser.RecyclerViewHolderz> {
Context context;
LayoutInflater inflater;
private List<String> users_names_list;
UsuariosModel usertModel;
String batch_name;
ArrayList<String> student_list;

public RecyclerUser(Context context, List<String> users_names_list) {
    this.context = context;
    inflater = LayoutInflater.from(context);
    this.users_names_list = users_names_list;
    student_list = new ArrayList<String>();
    this.notifyDataSetChanged();

   this. modifyItem();
   }

@Override
public RecyclerViewHolderz onCreateViewHolder(ViewGroup parent, int viewType) 
{
    View v = inflater.inflate(R.layout.item_list, parent, false);
    RecyclerUser.RecyclerViewHolderz viewHolders = new RecyclerUser.RecyclerViewHolderz(v);


    return viewHolders;
}

@Override
public void onBindViewHolder(final RecyclerUser.RecyclerViewHolderz holder,final int position) {

    holder.tv1.setTag(position);
    holder.tv1.setText((CharSequence) users_names_list.get(position));
    holder.tv1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {




            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("Add new Student and its UserId");

            LinearLayout layout = new LinearLayout(context);
            layout.setOrientation(LinearLayout.VERTICAL);
            // Set up the input
            final EditText user_name = new EditText(context);

            // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
            user_name.setInputType(InputType.TYPE_CLASS_TEXT);
            user_name.setHint("User Name");
            layout.addView(user_name);

            final EditText user_id = new EditText(context);

            // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
            user_id.setInputType(InputType.TYPE_CLASS_TEXT);
            user_id.setHint("User Id");
            layout.addView(user_id);

            builder.setView(layout);

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    String n = users_names_list.get(position);
                    // updating note text

                    // updating note in db
                    notifyItemChanged(position);

                    int position = holder.getAdapterPosition();

                    notifyDataSetChanged();
                    // refreshing the list
                    users_names_list.set(position, n);
                    getItemId(position);
                   usertModel = new UsuariosModel(0, user_name.getText().toString(), user_id.getText().toString(), batch_name);
                    final SQLiteDatabase db = MyDatabase.getInstance(context).getWritableDatabase();
                   UserTable.updateItem(db,usertModel);
                   users_names_list.set(position,user_name.getText().toString());

            }

            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            builder.show();
        }

    });

    holder.tv1.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
            builder.setTitle("Delete");
            builder.setMessage("Are you sure you want to delete it?");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                users_names_list.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, users_names_list.size());
                final SQLiteDatabase db = MyDatabase.getInstance(context).getWritableDatabase();
                UserTable.deleteByStudentName(db, holder.tv1.getText().toString());
            }

        });

            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
            builder.show();
            return true;
    }
    });

}

public void updateData(ArrayList<String> viewModels) {
    student_list.clear();
    student_list.addAll(viewModels);
    notifyDataSetChanged();
}

private String hola (int position) {

    return student_list.get(position);
}

View.OnClickListener clickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        RecyclerUser.RecyclerViewHolderz hola = (RecyclerUser.RecyclerViewHolderz) v.getTag();
        int position = hola.getPosition();

        Toast.makeText(context, "This is position " + position, Toast.LENGTH_LONG).show();

    }
};

@Override
public int getItemCount() {
    return users_names_list.size();
}





public String getIteId(int position) {
    return users_names_list.get(position);
}

public void modifyItem() {

    notifyDataSetChanged();
}

private void notifyDataSetChanged(int position) {

    notifyDataSetChanged();
}

public class RecyclerViewHolderz extends RecyclerView.ViewHolder {

    TextView tv1;
    ImageView imageView;

    public RecyclerViewHolderz(View itemView) {
        super(itemView);

        imageView = (ImageView) itemView.findViewById(R.id.list_avatar);
        tv1 = (TextView) itemView.findViewById(R.id.student_name_text_view);

    }
      }

     }

0 个答案:

没有答案