Loading text file data to listview

ginsh

Member
Licensed User
Longtime User
Hi,

I want to load data from a text file (test.txt) to a listviews..
Text file data will be for e.g.
12343
2345
23678
897345
34536
Each data in text file should be as loaded as different items in listview.
B4X:
Sub ReadTextReader    
Dim TextRd As TextReader    
TextRd .Initialize(File.OpenInput(File.DirRootExternal, "test.txt"))   
Dim line As String    
line = TextRd .ReadLine        
Do While line <> Null                
line = TextRd .ReadLine    
Loop    
ListView1.AddSingleLine(line)
TextRd .Close
End Sub

i tried the above code but giving me null pointer error. anyone please help me..

Thanks
 

Ricky D

Well-Known Member
Licensed User
Longtime User
Which line causes the error?

Regards, Ricky
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
Try this code:
B4X:
Sub ReadTextReader    
    Dim TextRd As TextReader    
    TextRd.Initialize(File.OpenInput(File.DirRootExternal, "test.txt"))  
    ListView1.Clear
    Dim line As String    
    line = TextRd .ReadLine        
    ListView1.AddSingleLine(line)
    Do While line <> Null                
        line = TextRd .ReadLine    
        ListView1.AddSingleLine(line)
    Loop    
    TextRd .Close
End Sub
Best regards.
 
Upvote 0

kjoussen

Member
Licensed User
Longtime User
I could imagine that this solution will also crash when the textfile is empty.
Leave out the two lines before the Do-While-Clause and this should be fixed.
 
Upvote 0

kickaha

Well-Known Member
Licensed User
Longtime User
B4X:
Sub*ReadTextReader****
****Dim*TextRd*As*TextReader****
****TextRd.Initialize(File.OpenInput(File.DirRootExternal,*"test.txt"))**
****ListView1.Clear
****Dim*line*As*String****
****line*=*TextRd.ReadLine********
****Do*While*line*<>*Null*****
***** **ListView1.AddSingleLine(line)*********
********line*=*TextRd.ReadLine****
****Loop****
****TextRd*.Close
End*Sub

The above is more correct, as you read a line first, and only run the loop if it is not null. Then the loop adds the line to the listview and gets next line. This continues until line is null.
 
Upvote 0
Top