java - 如何使用android中的recyclerview和数据库将位置明智的对象数据从一个 Activity 传递到另一个 Activity

标签 java android database listview android-recyclerview

我已经创建了 recycerview,当我按下 + 按钮更改按钮图像时,此 recycerview 显示人物图像、人名和 + 按钮。在 recycerview 底部一个按钮之后,此按钮单击所有数据显示下一个 Activity 。 .

我的适配器

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();
    }
}

Activity

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) {

}

最佳答案

首先你应该在你的 Build 模型类中实现 Serializable 接口(interface),如下所示:-

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);
            }
        });

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

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

关于java - 如何使用android中的recyclerview和数据库将位置明智的对象数据从一个 Activity 传递到另一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39746341/

相关文章:

javascript - ajax setInterval效率

java - 如何在android中制作文件的副本?

java - 简单的if语句问题

java - 获取开始菜单的截图

android - 在 android 中,config.xml 中的描述用于

java - 如何在 fragment 中使用 onClickListener 方法?

sql - 在默认文件组以外的文件组上创建表

java - Netbeans:如何从 "design"GUI 生成器向 JTable 添加 valueChanged 监听器?

android - 带有自定义 ArrayAdapter 的 AutocompleteTextView

mysql - 选择并显示属于特定 ID 的所有行