您好,我正在创建一个读取文件的应用程序,它的内容应显示在recyclerview中,我已经完成了,但是只有第一行显示了剩余的行而不显示
我的文件包含如下所示的数据
123
345
567
我已经使用缓冲的读取器和输入流来读取文件
这是recyclerAdapter的类
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.Phone> {
List<PhoneNumber> phoneNumbers;
public RecyclerAdapter(List<PhoneNumber> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
@NonNull
@Override
public Phone onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.text,viewGroup,false);
Phone phone = new Phone(view);
return phone;
}
@Override
public void onBindViewHolder(@NonNull Phone phone, int i) {
phone.textView.setText(phoneNumbers.get(i).number);
}
@Override
public int getItemCount() {
return phoneNumbers.size();
}
public class Phone extends RecyclerView.ViewHolder {
TextView textView;
public Phone(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.txt);
}
}
}
这是我班上的代码
public class ScheduledFragment extends Fragment {
String[] strings;
RecyclerView listView;
List<PhoneNumber> phoneNumbers;
public ScheduledFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_scheduled, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = view.findViewById(R.id.list);
ReadFile();
initialiseAdapter();
}
private void initialiseAdapter() {
listView.setHasFixedSize(true);
listView.setLayoutManager(new LinearLayoutManager(getContext()));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(phoneNumbers);
listView.setAdapter(recyclerAdapter);
}
private void ReadFile() {
phoneNumbers = new ArrayList<>();
try {
InputStream inputStream = getActivity().getAssets().open("phone.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
boolean hasNext = true;
while (hasNext) {
String line = bufferedReader.readLine();
phoneNumbers.add(new PhoneNumber(line));
hasNext = line != null;
}
inputStream.close();
} catch (IOException e) {
//log the exception
}
}
}
class PhoneNumber {
String number;
public PhoneNumber() {
}
public PhoneNumber(String number) {
this.number = number;
}
}
我只在recyclerview中显示第一行节目
预期结果:
123
345
567
我得到的结果:
123
答案 0 :(得分:0)
尝试改善自己的时间,为此不需要变量:
while (true) {
String line = bufferedReader.readLine();
if(line == null) {
break;
} else if (line.equals("")) {
phoneNumbers.add(new PhoneNumber("\n"));
/*I'm not sure if you really want "/n" breaks*/
} else {
phoneNumbers.add(new PhoneNumber(line));
}
Log.d("test", line);
}
ps:为了惯例,仅对类使用大写字母,而不对方法(readFile不是ReadFile)