dds dds - 29 days ago 7
Android Question

Why are there missing sentences with Bufferedreader

I am triying to get sentences from my txt file in android and it gets sentences by lines but some of them are missing? Why? Here is my code:

public ArrayList<String> sorulist = new ArrayList<String>();
........
try {


InputStream ins = getResources().openRawResource(
getResources().getIdentifier("sorular",
"raw", getPackageName()));
InputStreamReader InputRead= new InputStreamReader(ins);

BufferedReader r = new BufferedReader(InputRead);

while ((r.readLine()) != null) {
sorulist.add(r.readLine());
}

InputRead.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "nothing!",
Toast.LENGTH_SHORT).show();
}


When I try to show the list with this code:

sorutxt.setText(sorulist.toString());


I am getting this in my textview so this is the list:

[Yaptırımı manevi olan kurallar hangileridir?,Bir ülkede uygulanan, halen yürürlükteki yazılı ve yazısız hukuk kurallarına ne ad verilir?,null]


But something in list is missing because my original txt file is this:

Sosyal hayatı düzenleyen kurallar hangileridir?
Yaptırımı manevi olan kurallar hangileridir?
Hukukun yaptırım türleri hangileridir?
Bir ülkede uygulanan, halen yürürlükteki yazılı ve yazısız hukuk kurallarına ne ad verilir?
"Pozitif hukuk" ile "tabii hukuk" arasındaki fark aşağıdaki seçeneklerden hangisidir?


I think the index 0, 2 and 4 items are missing? What is wrong in my code?
Thanks everyone

Answer
while ((r.readLine()) != null) {
        sorulist.add(r.readLine());
}

Basically you are dropping every other line because of the if. readLine() actually reads a line, so when you call it next time you already passed the first line. So your code behaves if the line read is not null I am going to read the next line and put it in the list.

A fix could be:

String lineFromFile;
while ((lineFromFile = r.readLine()) != null) {
        sorulist.add(lineFromFile);
}
Comments