Cursussen/Courses Codesnippets     Top 
B4A-lists - Item page


1. Layout
Go to the B4XMainPage tab in the IDE. Open the designer and open the MainPage layout file.
Generate the members: btn1, cbx1, cbx2, clv1.


2. Comboboxes
Write code to fill the combobox 1 with a list of categories.
Write code to fill the combobox 2 with a list of subcategories for the selected category.
If the user changes the selection of one of the comboboxes the method _SelectedIndexChanged is used to update the views (cbx1, cbx2 and clv1) accordingly.
Public Sub FillComboBox1
	Private lst As List
	lst.Initialize
	If (File.Exists(File.DirInternal,"category.txt")) Then
		lst = File.ReadList(File.DirInternal,"category.txt")
	End If
	'lst.SortCaseInsensitive(True)
	If lst.Size > 0 Then
		cbx1.SetItems(lst)
		cbx1.SelectedIndex = 0
		SelectedIndex1 = 0
		SelectedItem1 = cbx1.GetItem(SelectedIndex1)
	End If
	FillComboBox2
End Sub

Public Sub FillComboBox2
	If cbx1.Size < 1 Then
		Return
	End If
	Private lst As List
	lst.Initialize
	If (File.Exists(File.DirInternal,SelectedItem1 & "_subcategories.txt")) Then
		lst = File.ReadList(File.DirInternal,SelectedItem1 & "_subcategories.txt")
	End If
	'lst.SortCaseInsensitive(True)
	If lst.Size > 0 Then
		cbx2.SetItems(lst)
		cbx2.SelectedIndex = 0
		SelectedIndex2 = 0
		SelectedItem2 = cbx2.GetItem(SelectedIndex2)
	End If
	load_list
End Sub

Sub cbx1_SelectedIndexChanged (Index As Int)
	save_list(SelectedItem1,SelectedItem2)
	clv1.Clear
	SelectedIndex1 = Index
	SelectedItem1 = cbx1.SelectedItem
	FillComboBox2
End Sub

Sub cbx2_SelectedIndexChanged (Index As Int)
	save_list(SelectedItem1,SelectedItem2)
	clv1.Clear
	SelectedIndex2 = Index
	SelectedItem2 = cbx2.SelectedItem
	load_list
End Sub


3. Read or write
Write the load_list subroutine. The filename is composed of the categoryname and the subcategoryname that were selected.
Write the save_list subroutine. The parameters are the category and subcategory that were selected.
Sub load_list
	Private lst As List
	lst.Initialize
	If (File.Exists(File.DirInternal,cbx1.SelectedItem & "_" & cbx2.SelectedItem & ".txt")) Then
		lst = File.ReadList(File.DirInternal,cbx1.SelectedItem & "_" & cbx2.SelectedItem & ".txt")
	End If
	For i = 0 To lst.Size-1
		clv1.AddTextItem(lst.Get(i), lst.Get(i))
	Next
End Sub

Sub save_list(cat As String,subcat As String)
	Private lst As List
	lst.Initialize
	For i = 0 To clv1.Size-1
		lst.Add(clv1.GetValue(i))
	Next
	File.Delete(File.DirInternal,cat & "_" & subcat & ".txt")
	File.WriteList(File.DirInternal,cat & "_" & subcat & ".txt",lst)
End Sub