How to read a txt file store value in integer type?

0

I'm using this example:

try {
    AssetManager assetManager = getResources().getAssets();
    InputStream inputStream = assetManager.open("nome-do-arquivo.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String linha;

    while((linha = bufferedReader.readLine())!=null){
      nome = linha;
       id = bufferedReader.readLine() // Aqui é um tipo inteiro
    }
    inputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

No arquivo txt is thus

fulano
R.drawble.image

I would like to make R.drawble.image store in an integer type because I tried to convert from String to int but it did not work.

    
asked by anonymous 03.03.2016 / 19:51

2 answers

3

You can try something like this on your while :

while ((linha = bufferedReader.readLine()) != null) {
    if (linha.startsWith("R.drawble.")) {
        String name = linha.replace("R.drawble.", "");
        int resource = getResources().getIdentifier(name, "drawable", getPackageName());
    }
}

Where resource will be the integer corresponding to the drawable of your application.

    
03.03.2016 / 20:21
1

As stated by @Paulo Rodrigues, you can use the getIdentifier method of Resource.

Follow the documentation

Example usage:

   try {
        AssetManager assetManager = getResources().getAssets();
        InputStream inputStream = assetManager.open("nome-do-arquivo.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String linha;


        while((linha = bufferedReader.readLine())!=null){
            String id = bufferedReader.readLine();
            if(id.contains(".")){ // garantimos que haja pontos na string...
                String[] valores = id.split("."); // quebramos a string nos pontos {"R", "rawble", image"}
                // Vamos pegar sua identificação conforme os valores...
                int resource = getResources().getIdentifier(valores[2], valores[1], getActivity().getPackageName());
            }


        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
03.03.2016 / 20:46