androidandroid-gridview

How do i retrive text from sdcard and set text view accordingly?


I am using gridview and layout inflater to display icon with text.

It should look like this:

enter image description here

My text file contains following data:

Profile 0|Profile 1|Profile 2

I am using following code:

    public View getView(final int position, View convertView, ViewGroup parent) {
        View v;
        //String text;
        final ImageView picturesView;
        if (convertView == null) {
            LayoutInflater li = getLayoutInflater();
            v = li.inflate(R.layout.icon, null);
            File sdcard = Environment.getExternalStorageDirectory();
            File file = new File(sdcard,"string.txt");
            //StringBuilder stext = new StringBuilder();
            TextView tv = (TextView)v.findViewById(R.id.icon_text);
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                while ((line = br.readLine()) != null) {
                    String[] columns = line.split("\\|");
                    for (String name : columns){ 

                       tv.setText(name);
                    }

                    //stext.append(line);
                    //stext.append('\n');
                }
            }
            catch (IOException e) {
                //You'll need to add proper error handling here
            }

            
            tv.setTextSize(12);
            tv.setTextColor(Color.BLACK);              
            
        }
        else {
            v = convertView;
        }

}

I want to set the text view with the string values

TextView tv = (TextView)v.findViewById(R.id.icon_text);
tv.setText();

I tried to check the columns length through Toast.makeText(SDCardImagesActivity.this, ""+columns.length, Toast.LENGTH_LONG).show(); but it is showing 1(5 times)

I am confused how to use columns value in tv.setText and whether columns array is correct or not.


Solution

  • Looking at the code you're referencing

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View v;
            if(convertView==null){
                LayoutInflater li = getLayoutInflater();
                v = li.inflate(R.layout.icon, null);
                TextView tv = (TextView)v.findViewById(R.id.icon_text);
                tv.setText("Profile "+position);
                ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
                iv.setImageResource(R.drawable.icon);
            }
            else
            {
                v = convertView;
            }
            return v;
        }
    

    Instead of this line...

    tv.setText("Profile "+position);
    

    ...use the following...

    tv.setText(columns[position]);