【问题标题】:how to pass Position wise object data one activity to another using recyclerview and databse in android如何在android中使用recyclerview和数据库将位置明智的对象数据一个活动传递给另一个活动
【发布时间】:2016-09-28 11:37:11
【问题描述】:

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

我的适配器

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

}

【问题讨论】:

    标签: java android database listview android-recyclerview


    【解决方案1】:

    首先你应该像这样在你的Build模型类中实现Serializable接口:-

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

    【讨论】:

    • 我已经尝试了你的代码,但是在这一行的适配器中出现了一些错误,例如 java.lang.NullPointerException Intent intent = new Intent(context, Temp.class);
    • context 可能为空。您是否制作了一个单独的 BuildCustomAdapter 文件,还是在您的 Activity 中?
    • 单独的 BuildCustomAdapter 文件。
    • BuildCustomAdapter 文件中传递上下文对象。像这样修改您的BuildCustomAdapter constructor:- public BuildCustomAdapter(List&lt;Build&gt; buildList, Context context) { this.context = context; this.buildList = buildList; this.buildListCopy = new ArrayList&lt;&gt;(); buildListCopy.addAll(buildList); } 在您的BuildCustomAdapter 类中创建一个context,如下所示:- 私有上下文上下文;
    • 在创建BuildCustomAdapter 的对象时也将代码修改为此:- BuildCustomAdapter buildCustomAdapter = new BuildCustomAdapter(buildList, YourActivityName.this);
    【解决方案2】:

    在下面的方法中添加 Intent,

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

    【讨论】:

    • 下一个activity如何获取模型数据?
    • 替换这些行:intenet.putExtra("key",build.getName());
    • 我已经替换了这一行,但是这个数据显示到这个活动中的下一个活动如何显示?
    • holder.imageView.setImageResource(build.getImages()); holder.name.setText(build.getName());
    • 你必须在哪里显示这些数据??在回收视图中??
    【解决方案3】:

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

    在点击监听器实现中,您应该将 Intent 与您的数据一起传递

    【讨论】:

    • 请解释一下我不知道,因为我在 android 上比较新鲜?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多