Android Question How to read the first line of a .txt file?

Matteo Granatiero

Active Member
Licensed User
I would like to read the first line of a .txt file, for example composed as follows:
first line: Hello everyone
second line: how are you?
third line: Well you?
 

colboy

Member
Licensed User
Longtime User
I would like to read the first line of a .txt file, for example composed as follows:
first line: Hello everyone
second line: how are you?
third line: Well you?
This will read all of the lines. You can just forget the loop if you want the first line only.

B4X:
Dim lReader As TextReader
lReader.Initialize(File.OpenInput([The folder where the file is], [The name of the file]))
Dim lLine As String
lLine = lReader.ReadLine
Do While lLine <> Null
    lLine = lReader.ReadLine
Loop
lReader.Close

Colin
 
Upvote 0

Matteo Granatiero

Active Member
Licensed User
Use a list. Suppose file is saved in assets:
B4X:
Dim MyList As List
    MyList=File.ReadList(File.DirAssets,"myfile.txt")
    Log(MyList.Get(0))  'displays first line: Hello everyone
it works with the log, but when I use EditText it gives me an error: java.lang.RuntimeException: Object should first be initialized (EditText).
edittext is about the designer. my code is:
B4X:
Dim EditText1 As EditText
Dim list As List
list= File.ReadList(File.DirRootExternal, "/My Folder/textfile.txt")
EditText1.Text=list.Get(0)
 
Upvote 0

udg

Expert
Licensed User
Longtime User
edittext is about the designer.
If that means that your EditText is part of a layout file produced by the Designer you load before the shown code than you shouldn't declare it again in your code (i.e. remove the "Dim EdiText1.. line).

ps: send greetings to Gargano!
 
Upvote 0

musaso

Active Member
Licensed User
Longtime User
B4X:
Dim myans() As String
    myans = SplitText(File.ReadString(File.DirAssets,"myfile.txt"))
    EditText1.Text = myans(0)
 
Upvote 0

musaso

Active Member
Licensed User
Longtime User
Sorry ......
B4X:
Sub SplitText(Text As String) As String()
    Dim sText() As String
    sText = Regex.Split(CRLF, Text)
    Return sText
End Sub
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
Can you zip and post your project?
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
was already included in the global sub, but continues to give me error
Did you load the layout before
EditText1.Text = myans(0)
?
Loading the layout file that includes EditText1 initializes EditText1. So you need something like this
B4X:
Activity.LoadLayout("TheNameYouGaveYourLayoutFile")
before
B4X:
Dim myans() As String
myans = SplitText(File.ReadString(File.DirAssets,"myfile.txt"))
EditText1.Text = myans(0)
(note, I'm just repeating what @udg said).
Finally, EditText1 must be the correct object name, meaning, it is the same name given in your layout. So make sure your layout includes an EditText object/view that is named EditText1 (here I'm just repeating what @Mahares said).
 
Upvote 0
Top