Sarath Nadendla Sarath Nadendla - 1 month ago 6
Android Question

Got String Data from Internal Storage When i set it to listview only last item is displayed

Got String Data from Internal Storage.When i tried to display that data on listview only last item is displayed.
Here is my code.


listView=(ListView)findViewById(R.id.listview);


Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("/storage/sdcard0/client_new.txt")));
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
System.out.println(myChar);
String str_new = String.valueOf(myChar);
String[] items={str_new};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < items.length; ++i)
{
list.add(items[i]);
}

Toast.makeText(ExistingContacts.this,str_new,Toast.LENGTH_LONG).show();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,list);
listView.setAdapter(adapter);


}
}catch (Exception e)
{
e.printStackTrace();;
}

Answer

use final ArrayList list = new ArrayList(); before while loop

listView=(ListView)findViewById(R.id.listview);


    Scanner s = null;
    try {
        s = new Scanner(new BufferedReader(new FileReader("/storage/sdcard0/client_new.txt")));
final ArrayList<String> list = new ArrayList<String>();
        while (s.hasNext()) {
            String str = s.next();
            char[] myChar = str.toCharArray();
            System.out.println(myChar);
            String str_new = String.valueOf(myChar);
            String[] items={str_new};

            for (int i = 0; i < items.length; ++i)
            {
                list.add(items[i]);
            }

            Toast.makeText(ExistingContacts.this,str_new,Toast.LENGTH_LONG).show();
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,list);
            listView.setAdapter(adapter);


        }
    }catch (Exception e)
    {
        e.printStackTrace();;
    }