Search code examples
javaandroidsqlitesettext

Android Sql database just gives last data


I am trying to receive all data of my sqli database, but strangely I just get the last data if I try to print it on a textview.

But trying to log the data gives mme the full database which is correct,

I just cannot print them all.

code for this:

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

Again with Systemoutprint I get all data in the console, but if I try to setText I just get the last data.


Solution

  • Since 'test' is getting declared inside the loop, every time the following line

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

    runs, it will put a new value in the variable, that you are showing using setText(), which will remove the earlier text and display the current text.

    In my view, the following might help you achieve what you are looking after:

    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