如何使用recyclelerview和databse在android中将位置明智的对象数据传递给另一个

时间:2016-09-28 11:37:11

标签: java android database listview android-recyclerview

我创建了recycerview,这个rec​​ycerview显示了Person图像,人名和+按钮,当我按下+按钮更改按钮图像时为true.and recycerview bottom one button按钮点击所有数据显示下一个活动。

我的适配器

public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;


private ItemFilter mFilter = new ItemFilter();

public BuildCustomAdapter(List<People> buildList) {
    this.peopleList = buildList;
    this.peopleListCopy = new ArrayList<>();
    peopleListCopy.addAll(buildList);
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.build_list_row, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {

    People people = peopleList.get(position);

    byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

    holder.ivPeopleImage.setImageBitmap(decodedByte);
    holder.tvPersonName.setText(people.getPeopleName());

    holder.button.setSelected(people.isSelected());
    holder.button.setOnClickListener(new onSelectListener(position));
}

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

@Override
public Filter getFilter() {
    if (mFilter == null) {
        mFilter = new ItemFilter();
    }
    return mFilter;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    // public ImageView ivPeopleImage;
    public TextView tvPersonName;
    public Button button;
    public CircularImageView ivPeopleImage;

    public MyViewHolder(View itemView) {
        super(itemView);
        ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
        tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
        button = (Button) itemView.findViewById(R.id.addbn);
    }
}

private class ItemFilter extends Filter {

    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        if (constraint != null && constraint.length() > 0) {
            List<People> filterList = new ArrayList<>();


            for (int i = 0; i < peopleListCopy.size(); i++) {
                if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
                        .contains(constraint.toString().toUpperCase())) {

                    People peopleName = peopleListCopy.get(i);
                    filterList.add(peopleName);
                }
            }
            results.count = filterList.size();
            results.values = filterList;

        } else {
            results.count = peopleListCopy.size();
            results.values = peopleListCopy;
        }
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        peopleList = (List<People>) results.values;
        notifyDataSetChanged();
    }

}

private class onSelectListener implements View.OnClickListener {

    int mPosition;

    public onSelectListener(int position) {
        mPosition = position;
    }

    @Override
    public void onClick(View view) {
        view.setSelected(!view.isSelected());
        People people = peopleList.get(mPosition);
        people.setSelected(!people.isSelected());
        notifyDataSetChanged();
    }
}

活动

public class BulidActivity extends AppCompatActivity {


private List<People> peopleList = new ArrayList<>();
private List<People> peopleListCopy = new ArrayList<>();
private RecyclerView recyclerView;
private BuildCustomAdapter buildCustomAdapter;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bulid);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    BuildData();
    peopleListCopy.addAll(peopleList);

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    buildCustomAdapter = new BuildCustomAdapter(peopleList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(buildCustomAdapter);

    AddTxt();
    BtnBuildNow();
}

private void BtnBuildNow() {

    Button btnnuildnow = (Button) findViewById(R.id.btn_build_now);

    btnnuildnow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(BulidActivity.this, AlertList.class);
            startActivity(intent);

        }
    });

}

private void AddTxt() {
    EditText editTxt = (EditText) findViewById(R.id.etSearch);
    editTxt.setTextColor(Color.WHITE);

    editTxt.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.setFocusable(true);
            v.setFocusableInTouchMode(true);
            return false;
        }
    });

    editTxt.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (s.length() <= 0) {
                peopleList.clear();
                peopleList.addAll(peopleListCopy);
                recyclerView.setAdapter(null);
                buildCustomAdapter = new BuildCustomAdapter(peopleList);
                recyclerView.setAdapter(buildCustomAdapter);
            } else {
                buildCustomAdapter.getFilter().filter(s.toString());
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

private List<People> BuildData() {
    DataBaseHelper db = new DataBaseHelper(getApplicationContext());

    try {
        db.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    if (db.open()) {
        peopleList = db.getPeople();
    }
    return peopleList;

}

模型类

public class People  implements Serializable {
private String peopleImage;
private String peopleName;
private boolean selected;


public void setPeopleName(String peopleName) {
    this.peopleName = peopleName;
}

public String getPeopleName() {
    return peopleName;
}

public void setPeopleImage(String peopleImage) {
    this.peopleImage = peopleImage;
}

public String getPeopleImage() {
    return peopleImage;
}

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

DatabaseHelper.class

public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/databasename/databases/";
private static final String DB_NAME = "alertme.db";
private final String TABLE_PEOPLE = "people";
private final String TABLE_CATEGORY = "category";
private final String CATEGORY_NAME = "name";
private final String ID = "id";
private final String CATEGORY_ID = "category_id";
private final String PEOPLE_IMAGE = "image";
private final String PEOPLE_NAME = "name";
private SQLiteDatabase myDataBase;

private final Context myContext;

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

    this.myContext = context;
}

public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();
    if (dbExist) {
    } else {

        this.getReadableDatabase();

        try {
            copyDataBase();
        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }
}

private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {

    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException {

    InputStream myInput = myContext.getAssets().open(DB_NAME);

    String outFileName = DB_PATH + DB_NAME;

    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public boolean open() {
    try {
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        return true;
    } catch (SQLException sqle) {
        myDataBase = null;
        return false;
    }
}


public List<People> getPeople(String category_id) {
    List<People> peoples = new ArrayList<>();
    try {
        SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);

        Cursor cursor = db.rawQuery("select * from people where category_id = " + category_id, null);

        while (cursor.moveToNext()) {
            String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));
            String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));

            People people = new People();
            people.setPeopleName(peopleName);
            people.setPeopleImage(peopleImage);

            peoples.add(people);
        }

    } catch (Exception e) {
        Log.d("DB", e.getMessage());
    }
    return peoples;
}

public List<Category> getCategory() {
    List<Category> categoryList = new ArrayList<>();
    try {

        String query = " SELECT * FROM " + TABLE_CATEGORY;
        SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor = db.rawQuery(query, null);
        while (cursor.moveToNext()) {
            int categoryID = cursor.getInt(cursor.getColumnIndex(ID));
            String categoryName = cursor.getString(cursor.getColumnIndex(CATEGORY_NAME));

            Category category = new Category();
            category.setId(categoryID);
            category.setCategoryName(categoryName);

            categoryList.add(category);

        }

    } catch (Exception e) {
        Log.d("DB", e.getMessage());
    }

    return categoryList;
}

@Override
public synchronized void close() {

    if (myDataBase != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

3 个答案:

答案 0 :(得分:0)

在下面的方法

中添加意图
    holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                build.setSelected(!build.isSelected());
                if (build.isSelected()) {
                    holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
    Intent intent = new Intent(context, youractivity.class)
    intenet.putExtra("key","value");
    context.startActivity(intent);
                } else
                    holder.button.setBackgroundResource(R.drawable.add_button_icon);
            }
        });

答案 1 :(得分:0)

您注册ViewHolder上的点击事件的巨大错误!你将获得与实际不同的位置,因为当android使用notifyItemMoved时,不会调用viewBindHolder,而是你的位置错误。

并且在click侦听器实现中,您应该将Intent传递给您的数据

答案 2 :(得分:0)

首先,您应该在Serializable模型类中实现Build接口,如下所示: -

public class Build implements Serializable{
   //Content will be as it is
}

像这样更改clickListener: -

holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                build.setSelected(!build.isSelected());
                if (build.isSelected()) {
                    holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
    Intent intent = new Intent(context, youractivity.class)
    intenet.putExtra("build",build);
    context.startActivity(intent);
                } else
                    holder.button.setBackgroundResource(R.drawable.add_button_icon);
            }
        });

在接收活动的onCreate方法中写下: -

Build build = (Build) getIntent().getSerializableExtra("build");