-2

I have searched in stack and web a lot, for parsing a CSV file.
But I won't get what I want.

I have this table in CSV format,

enter image description here

what I want is, if I give the "ID"(which is 0,1,2,3... ) it should return me the value right to it i.e., if i give

"2" it should return me "hello how are you ?".

"4" it should return me "What do you prefer over tea ?"

How to achieve this?
Right now I kept my CSV file in the raw folder.

Any help will be apppreciated

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ranjan
  • 1,326
  • 18
  • 38
  • 2
    'I have searched in stack and web a lot, for parsing a CSV file.' This sounds a bit questionable, since it's the first result if I google for 'android parse csv file'. See http://stackoverflow.com/questions/5360628/get-and-parse-csv-file-in-android – 0xDEADC0DE Dec 15 '16 at 07:41
  • but i want to get the value from id i.e., 0,1,2.. I have n number of Strings – Ranjan Dec 15 '16 at 07:46
  • I don't want to traverse through loop, – Ranjan Dec 15 '16 at 07:51
  • You'll have to, because you have read through the file. You'll need to read through the file, store each line as a key-value pair to match the number onto a string – 0xDEADC0DE Dec 15 '16 at 07:53
  • So, in csv file how do i store in key and value pair. – Ranjan Dec 15 '16 at 07:58

2 Answers2

0

You can save data in CSV as:-

ArrayList<TableData> arrayList=new ArrayList<>();
        arrayList.add(new TableData(1,"Hello"));
        arrayList.add(new TableData(2,"How are u"));
        arrayList.add(new TableData(3,"I am fine"));
        arrayList.add(new TableData(4,"Thank You"));

        File file;
        File root   = Environment.getExternalStorageDirectory();
        if (root.canWrite()){
            File dir    =   new File (root.getAbsolutePath() + "/PersonData");
            dir.mkdirs();
            file   =   new File(dir, "Data.csv");
            FileOutputStream out   =   null;
            try {
                // write to byte array
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(baos);
                for (TableData element : arrayList) {
                    dos.writeUTF(String.valueOf(element.id));
                    dos.writeUTF(String.valueOf(element.name));
                }
                byte[] bytes = baos.toByteArray();
                out = new FileOutputStream(file);

                out.write(bytes);
                out.close();
            }catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

And Retrive it as:-

File file;
        File root   = Environment.getExternalStorageDirectory();

            File dir    =   new File (root.getAbsolutePath() + "/PersonData");
            dir.mkdirs();
            file   =   new File(dir, "Data.csv");


        Uri u1  =   null;
        u1  =   Uri.fromFile(file);
        try {
            FileInputStream inputStream=new FileInputStream(file);
            String input="2";
            String previousValue="";
            ByteArrayInputStream bais = new ByteArrayInputStream(readFully(inputStream));
            DataInputStream in = new DataInputStream(bais);
            while (in.available() > 0) {
                String element = in.readUTF();
                if(previousValue.equalsIgnoreCase(input)){
                    textView.setText(element);
                }
                previousValue=element;

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Method to convert inputStream to byte[]:-

public static byte[] readFully(InputStream input) throws IOException
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        while ((bytesRead = input.read(buffer)) != -1)
        {
            output.write(buffer, 0, bytesRead);
        }
        return output.toByteArray();
    }
Nainal
  • 1,728
  • 14
  • 27
0

Create a separate class for reading CSV file as:-

    public class CSVFile {
        InputStream inputStream;

        public CSVFile(InputStream inputStream){
            this.inputStream = inputStream;
        }

        public List read(){
            List resultList = new ArrayList();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String csvLine;
                while ((csvLine = reader.readLine()) != null) {
                    String[] row = csvLine.split(",");
                    resultList.add(row);
                }
            }
            catch (IOException ex) {
                throw new RuntimeException("Error in reading CSV file: "+ex);
            }
            finally {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    throw new RuntimeException("Error while closing input stream: "+e);
                }
            }
            return resultList;


   }
}

Now call this in your activity:-

String input="2";
        InputStream inputStream = getResources().openRawResource(R.raw.sample);
        CSVFile csvFile = new CSVFile(inputStream);
        List scoreList = csvFile.read();
        for(int i=0;i<scoreList.size();i++){
            Object data_list=scoreList.get(i);
            String a[]= (String[]) data_list;
            String id=a[0];
            String value=a[1];
            if(input.equalsIgnoreCase(id)){
                Log.d("TAG", "Value Found "+value);
            }

        }
Nainal
  • 1,728
  • 14
  • 27