Android Sql 数据库只给出最后的数据

Android Sql database just gives last data

我正在尝试接收我的 sqli 数据库的所有数据,但奇怪的是,如果我尝试在文本视图上打印它,我只会得到最后的数据。

但是尝试记录数据给了我正确的完整数据库,

我无法全部打印出来。

代码:

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            DatabaseHandler db = new DatabaseHandler(getActivity());
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            int currentView = getArguments().getInt(ARG_SECTION_NUMBER);

            List<Contact> contacts = db.getAllContacts();

            if (currentView == 1) {
                for (Contact cn : contacts) {
                    TextView asd = (TextView) rootView.findViewById(R.id.section_label);
                    String test = "Id: " + cn.getID() + cn.getJokeCat01();
                    System.out.println(test);
                    asd.setText(test);
                }
            }
        }

我再次使用 Systemoutprint 在控制台中获取所有数据,但如果我尝试设置文本,我只会获取最后的数据。

由于 'test' 是在循环内声明的,每次下面的行

String test = "Id: " + cn.getID() + cn.getJokeCat01();

运行,它会在变量中放入一个新值,您正在使用 setText() 显示该值,这将删除较早的文本并显示当前文本。

在我看来,以下内容可能会帮助您实现目标:

if (currentView == 1) {
  String test="";
  for (Contact cn : contacts) {
    TextView asd = (TextView) rootView.findViewById(R.id.section_label);
    test += "Id: " + cn.getID() + cn.getJokeCat01();
    System.out.println(test);

  } // end of for

  Witze.setText(test);

}  // end of if