有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android Sql数据库只提供最后一个数据

我试图接收sqli数据库的所有数据,但奇怪的是,如果我试图在textview上打印数据,我只会得到最后的数据

但是尝试记录数据会给mme提供完整的数据库,这是正确的

我只是不能把它们全部打印出来

代码:

        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,我在控制台中获取所有数据,但如果我尝试设置text,我只获取最后一个数据


共 (1) 个答案

  1. # 1 楼答案

    因为“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