我想从我的资产目录中读取TXxt文件到RecyclerView中的TextView。我怎样才能做到这一点?我的资产目录中有一个txt文件。
public class BurdurData {
private int image;
private String name;
private String content;
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public static List<BurdurData> createList() {
BurdurData burdur = new BurdurData();
burdur.setImage(R.drawable.salda);
burdur.setName("Burdur Tarihi");
burdur.setContent("");
List<BurdurData> mBurdurList = new LinkedList<>();
mBurdurList.add(burdur);
return mBurdurList;
}
}
public class BurdurAdapter extends RecyclerView.Adapter<BurdurAdapter.BurdurHolder> {
private Context mContext;
List<BurdurData> mBurdurData;
public BurdurAdapter(List<BurdurData> mBurdurData) {
this.mBurdurData = mBurdurData;
}
@Override
public BurdurHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_card_view_layout, parent, false);
return new BurdurHolder(rootView);
}
@Override
public void onBindViewHolder(BurdurHolder holder, int position) {
BurdurData burdurData = mBurdurData.get(position);
holder.imageField.setImageResource(burdurData.getImage());
holder.nameField.setText(burdurData.getName());
**holder.contentField.setText(readTxt());**
}
@Override
public int getItemCount() {
return mBurdurData.size();
}
public class BurdurHolder extends RecyclerView.ViewHolder {
ImageView imageField;
TextView nameField, contentField;
public BurdurHolder(View itemView) {
super(itemView);
imageField = (ImageView) itemView.findViewById(R.id.imageField);
nameField = (TextView) itemView.findViewById(R.id.nameField);
contentField = (TextView) itemView.findViewById(R.id.contentField);
}
}
private String readTxt() {
InputStream inputStream = null;
try {
inputStream = mContext.getAssets().open("texts/burdur_tarihi.txt");
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}
readTxt()方法返回NullPointerException错误。我该如何解决? 提前致谢