1

I am working on a project to get into android development, having some knowledge of java before I am thinking of reading data from a text file, which will be formatted like this;

Type: House
Image link: www.bit.ly/image1
Name: Black
Download Link: www.bit.ly/image1download 
----------
Type: Car
Image link: www.bit.ly/image2 
Name: yellow
Download Link: www.bit.ly/image2download 
----------
Type: Backyard
Image link: www.bit.ly/image3 
Name: Green
Download Link: www.bit.ly/image3download
----------
Type: Window
Image link: www.bit.ly/image4 
Name: Solid
Download Link: www.bit.ly/image4download 
----------
Type: Table
Image link: www.bit.ly/image5  
Name: Brown
Download Link: www.bit.ly/image5download 
----------

The data contains 4 pieces of information per set, Type, Image, Name and Download. I need a way of reading this and saving/writing it to a arraylist which I then can display in a listview that I will have on my app. (I am currently looking at tutorials on creating listview, if you know any useful tutorials please let me know)

Arraylist <String> data = new ArrayList<String>();
Data.add(“House”,” www.bit.ly/image1”,”black”,”www.bit.ly/image1download”);
Data.add(“Car”,” www.bit.ly/image2”,”yellow”,” www.bit.ly/image2download”);
……..
……..

In reality there will be a lot more data then just 5 sets , so I want to use for loop to loop through each data data and add it to the data arraylist.

I am not sure how I can approach this, any help is welcomed, I am really stuck. Please let me know if I have not explained my question properly.

EDITED:

Would this be the correct way of reading data from a textfile?

Scanner content = new Scanner(new File("Data.txt"));
ArrayList<String> data = new ArrayList<String>();
while (content.hasNext()){
    data.add(content.next());
}
content.close();

Or is this another way in android

Henry
  • 1,042
  • 2
  • 17
  • 47
  • What is the problem exact!y. With data.add() you add four strings. If you read the file line by line you can collect/fill in these four sting variables and then add() them. – greenapps Jan 20 '16 at 09:56
  • I am not sure of how I can read data from a file in the format that is shown in the post. For example, how do I put the first type, image, name and download in first row and sparate it separate with ----------- and then read the second data set and so on, then put it in the arraylist. – Henry Jan 20 '16 at 10:13
  • Well start reading a file line by line. Then check every line for it contents and put the content in one of the four variables. Start coding. Then show your code if you need help. – greenapps Jan 20 '16 at 10:16

3 Answers3

1

Do this way define a setter getter class to hold and return values like this :

Data.class

public class Data {
String type,Image,Name,Link ;

public Data() {

}
public String getType() {
return type;
 }

 public void setType(String type) {
this.type = type;
  }

 public String getImage() {
return Image;
}

 public void setImage(String image) {
Image = image;
 }

 public String getName() {
return Name;
 }

 public void setName(String name) {
Name = name;
 }

 public String getLink() {
return Link;
  }

 public void setLink(String link) {
Link = link;
 }
 }

using for loop set data in a arraylist

Arraylist <Data> arrayListData = new ArrayList<Data>();
for(int i=0;i<arrayListData .size();i++){
 Data data=new Data();
 data.setType("");
 ...
 ...
 ...  
 arrayListData.add(data);
 }

and to fetch data from arraylist

String type= arrayListData.get(position).getType();

Updated :

read .txt file like this , I am assuming your text file is saved in sdcard of device :

    public void readfile() {
    StringBuilder text = new StringBuilder();
    File sdcard = Environment.getExternalStorageDirectory();
    ArrayList<Data> arrayList=new ArrayList<Data>();
    //Get the text file
    File file = new File(sdcard,"textfile.txt");

    //Read text from file


    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        Data data=new Data();
        while ((line = br.readLine()) != null) {

            text.append(line);
            text.append('\n');
            if(line.contains(":")){
                int index=line.indexOf(":");
                String s=line.substring(index+1).trim();
                if(line.contains("Type")){
                    data.setType(s);
                }
                if(line.contains("Image")){
                    data.setImage(s);

                }
                if(line.contains("Name")){
                data.setName(s);

              }
             if(line.contains("Download")){
                data.setLink(s);
              }

            }
            if(line.contains("-")){
             arrayList.add(data);
             data=new Data();
            }
        }
        System.out.println(text);

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

    }
    }
Kapil Rajput
  • 11,429
  • 9
  • 50
  • 65
  • Is this like creating custom arraylist adapter, I have been looking at custom listview and this looks similar to what I found on custom listview. – Henry Jan 20 '16 at 10:18
  • But I am little confused on how do I read in the data from the text file and place it in this arraylist – Henry Jan 20 '16 at 10:18
  • hi, thanks. looks good. Just for my own knowledge, does setter means setting the variables and getter means returning the variables in a getsomething() method which returns the value of specified variable. Do I have two questions I would need to make a sparate class for the data.class and rest of the code can go in my mainactivity and secondly would it be possible to not include the heading for the data. For example, if(line.contains("Type")){ data.setType(s); } I don't want Type to be written/displayed on listview. – Henry Jan 20 '16 at 13:17
  • Also, I am pretty sure I can work this out but you see for your for loop for(int i=0;i<6;i++), it will only loop 6 times but my data will have more then 6 data sets – Henry Jan 20 '16 at 13:27
  • @Henry i have write `for` loop with condition only for your understanding , you can check according to arraylist size see my edit answer and yes i would prefer to write `data.class` separately and you can set whatever you want to show in a listview by fetching its value accordingly from arraylist. – Kapil Rajput Jan 20 '16 at 14:51
  • Thanks. One more question, does the readFile method goes inside the for loop? or are these two separate things? – Henry Jan 21 '16 at 08:26
  • I am little confused how the for loop works with the read file, please help. – Henry Jan 21 '16 at 09:19
1

Before start go through this link for reading

How can I read a text file in Android?

Use PoJo Models for your needs,

Create a PoJo class like this

public class Film {

private String filmName;
private String mainStar;

public String getFilmName() {
    return filmName;
}
public void setFilmName(String filmName) {
    this.filmName = filmName;
}

public String getMainStar() {
    return mainStar;
}
public void setMainStar(String mainStar) {
    this.mainStar = mainStar;
}
}

Create ArrayList

private ArrayList<Film > filmArray=new ArrayList<Film>();

Store Each arraylist with instance of your PoJo class like this

for(int i=0;i<sizei++)
{
Film film=new Film();
film.setFilmName("your value");
film.setMainStar("your value");
filmArray.add(film);
}

and then access list of values in arraylist of PoJo class in filmArray list.

Simple and elegant solution.

Community
  • 1
  • 1
Brendon
  • 1,368
  • 1
  • 12
  • 28
1

Here is the parser

    public class FileParser {

    private static final String DATA_TERMINATION = "----------";

    private static final String TYPE="Type";
    private static final String IMAGE="Image link";
    private static final String NAME= "Name";
    private static final String DWNLD_LNK= "Download Link";

    public static void main(String[] args) {
        FileParser parser =  new FileParser();
        try {
            for(Data d:parser.parseDataFile(new File("F:\\data.txt"))){
                System.out.println(TYPE+":"+d.getType());
                System.out.println(IMAGE+":"+d.getImage());
                System.out.println(NAME+":"+d.getName());
                System.out.println(DWNLD_LNK+":"+d.getLink());
                System.out.println(DATA_TERMINATION);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public List<Data> parseDataFile(File input) throws Exception{
        List<Data> output =null;
        List<String> fileOp= null;
        try {

            validateInput(input);
            fileOp =  readFile(input);
            output = parseData(fileOp);



        } catch (Exception e) {
            throw e;
        }
        return output;


    }

    private List<Data> parseData(List<String> fileOp) {
        List<Data> output =null;

        output = new ArrayList<Data>();
        Data data;

        data = new Data();
        for(String line:fileOp){
            if(DATA_TERMINATION.equalsIgnoreCase(line)){
                output.add(data);
                data = new Data();
            }else{
                parseField(data,line);
            }
        }
        return output;
    }

    private void parseField(Data data, String line) {
        StringTokenizer tokenzr =  new StringTokenizer(line,":");
        if(tokenzr.countTokens() !=2){
            System.out.println("Cant parse line"+line);
        }else{

            switch (tokenzr.nextToken()) {
            case TYPE:
                data.setType(tokenzr.nextToken());
                break;
            case IMAGE:
                data.setImage(tokenzr.nextToken());
                break;
            case NAME:
                data.setName(tokenzr.nextToken());
                break;
            case DWNLD_LNK:
                data.setLink(tokenzr.nextToken());
                break;

            default:
                break;
            }
        }

    }

    private List<String> readFile(File input) throws Exception {

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
        String line = null;
        List<String> op = new ArrayList<String>();
        try {
            while((line = reader.readLine()) != null){
                op.add(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw e;
        }
        return op;
    }

    private void validateInput(File input) throws Exception {
        if(input == null){
            throw new Exception("Null input");      

        }else if(!input.exists() || !input.isFile() || !input.canRead()  ) {
            throw new Exception("File not readable");
        }

    }



}
Henry
  • 1,042
  • 2
  • 17
  • 47
Vasco
  • 782
  • 1
  • 5
  • 22