I need to know how I use a . text as a database; I just need it to show the data contained in it

Asked

Viewed 102 times

3

My application is a manual that when the user clicks on the item in the listview appears the descriptions contained in each item, along with a photo. Another thing like putting . text data in a Listview. This is my doubt.

  • 3

    Hello Paulo Cesar. Well, for your problem, accessing data from a file . txt is not the solution, by the way, never store data in files . txt . The problem with them is that you have to deal with opening and closing files correctly, create an efficient algorithm of access to items, etc. That is, it is too much work! Therefore, the ideal is you use the Sqlite database, because it is proper for Android , which already has its own resources to perform queries, persistence, etc.

1 answer

1

Come on!
I’ll show you how to load a . txt from the Assets folder:
create a file called dados.txt inside the Assets folder It will possess the following structure:

item 1;descrição um;image1.png
item 2;descrição dois;image2.png

To Load this file use the following code:

 /**
 * Carrega um arquivo txt e transforma as linhas em Objeto.
 */
private void load(){
      try {
         final InputStream inputStream = getAssets().open("dados.txt");
         final InputStreamReader inputreader = new InputStreamReader(inputStream); 
            BufferedReader buffreader = new BufferedReader(inputreader); 
            final List<Item> itens = new ArrayList<MainActivity.Item>(0);
            String line = "";
                while ((line = buffreader.readLine()) != null){
                    String[] values = line.split(";");
                    final Item item = new Item(values[0], values[1], values[2]);
                    itens.add(item);
                }

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

 /** 
 * Representa o objeto que será exibido
 */
public static class Item {
     public Item(final String title, final String description, final String image) {
         this.title = title;
         this.description = description;
         this.image = image;
    }
     public String title;
     public String description;
     public String image;
 }

I hope I’ve helped!
Greetings!

  • 1

    Remembering that there are also other models to save this data, the demonstrated is the famous CSV, but can also be used TSV that would be separated by tab. Or a . txt that records content with XML tags or a JSON.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.