1

So I have this two classes called ReadFromFile (provided by @Pankaj Nimgade) and MainActivity to import and read my test.txt. I want the integers on the text file to be read in my app with library achartengine.They have to be formatted to be put in the int[] force_l and int[] force_r: Can you help me to format the integers the way I need and how to put them in the int[] force_l and int[] force_r?

private void openChart() {
        int[] x = {0,1,2,3,4,5,6,7,8,9,10};
        int[] force_l = {0,25,24,25,15,16,17,25,24,21,24}; //replace this {} values with the ones from the text file
        int[] force_r = {0,48,36,26,43,45,30,33,33,28,42}; //replace this {} values with the ones from the text file

The test.txt is has two lines:

0 25 24 25 15 16 17 25 24 21 24
0 48 36 26 43 45 30 33 33 28 42

Now, how do I pass the integer string from ReadFromFile to be read in MainActivity?

The ReadFromFile class provided by @Pankaj Nimgade:

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Arrays;
import java.util.List;

public class ReadFromFile {

    public static void main(String[] args) {

        int[] force_l = null;
        int[] force_r = null;
        try {

            File file = new File("test.txt");
            List<String> strings = FileUtils.readLines(file);
            int count = 0;
            for (String s : strings) {

                String[] integer_Strings = s.split(" ");
                if (count == 0) {

                    force_l = new int[integer_Strings.length];
                    for (int i = 0; i < integer_Strings.length; i++) {
                        force_l[i] = Integer.parseInt(integer_Strings[i]);
                    }
                    count++;
                } else if (count == 1) {
                    force_r = new int[integer_Strings.length];
                    for (int i = 0; i < integer_Strings.length; i++) {
                        force_r[i] = Integer.parseInt(integer_Strings[i]);
                    }
                }

            }

            System.out.println(Arrays.toString(force_l));
            System.out.println(Arrays.toString(force_r));


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

}

The MainActivity class:

import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import org.achartengine.ChartFactory;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.BasicStroke;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

public class MainActivity extends AppCompatActivity {

    private View mChart;
    private String[] mTime = new String[]{
            "0",
            "1","2","3","4","5","6","7","8","9","10",
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting reference to the button btn_chart
        Button btnChart = (Button) findViewById(R.id.btn_chart);

        // Defining click event listener for the button btn_chart
        View.OnClickListener clickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Draw the Chart
                openChart();
            }
        };

        // Setting event click listener for the button btn_chart of the     SensorGraph layout
        btnChart.setOnClickListener(clickListener);

    }

    private void openChart() {
        int[] x = {0,1,2,3,4,5,6,7,8,9,10};
        int[] force_l;
        int[] force_r;

        // Creating an XYSeries for Right Force
        XYSeries force_rSeries = new XYSeries("Force R (N)");
        // Creating an XYSeries for Left Force
        XYSeries force_lSeries = new XYSeries("Force L (N)");
        // Adding data to Force Series
        for (int i = 0; i < x.length; i++) {
            force_lSeries.add(i, force_l[i]);
            force_rSeries.add(i, force_r[i]);
        }

        // Creating a dataset to hold each series
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        // Adding Left Force Series to dataset
        dataset.addSeries(force_lSeries);
        // Adding Right Force Series to the dataset
        dataset.addSeries(force_rSeries);

        // Creating XYSeriesRenderer to customize Force R Series
        XYSeriesRenderer force_rRenderer = new XYSeriesRenderer();
        force_rRenderer.setColor(Color.RED); //color of the graph set to green
        force_rRenderer.setFillPoints(true);
        force_rRenderer.setLineWidth(2f);
        force_rRenderer.setDisplayChartValues(false);
        //setting chart value distance
        // force_rRenderer.setDisplayChartValuesDistance(10);
        //setting line graph point style to circle
        // force_rRenderer.setPointStyle(PointStyle.CIRCLE);
        //setting stroke of the line chart to solid
        force_rRenderer.setStroke(BasicStroke.SOLID);

        // Creating XYSeriesRenderer to customize Force L Series
        XYSeriesRenderer force_lRenderer = new XYSeriesRenderer();
        force_lRenderer.setColor(Color.BLUE);
        force_lRenderer.setFillPoints(true);
        force_lRenderer.setLineWidth(2f);
        force_lRenderer.setDisplayChartValues(false);
        //setting line graph point style to circle
        // force_lRenderer.setPointStyle(PointStyle.SQUARE);
        //setting stroke of the line chart to solid
        force_lRenderer.setStroke(BasicStroke.SOLID);

        // Creating a XYMultipleSeriesRenderer to customize the whole chart
        XYMultipleSeriesRenderer multiRenderer = new     XYMultipleSeriesRenderer();
        multiRenderer.setXLabels(0);
        //multiRenderer.setChartTitle("High Speed");
        multiRenderer.setXTitle("time (s)");
        multiRenderer.setYTitle("Force (N)");

        /***
         * Customizing graphs
         */
        //setting text size of the title
        multiRenderer.setChartTitleTextSize(28);
        //setting text size of the axis title
        multiRenderer.setAxisTitleTextSize(24);
        //setting text size of the graph lable
         multiRenderer.setLabelsTextSize(24);
         //setting zoom buttons visiblity
         multiRenderer.setZoomButtonsVisible(false);
         //setting pan enablity which uses graph to move on both axis
        multiRenderer.setPanEnabled(false, false);
        //setting click false on graph
        multiRenderer.setClickEnabled(false);
        //setting zoom to false on both axis
        multiRenderer.setZoomEnabled(false, false);
        //setting lines to display on y axis
        multiRenderer.setShowGridY(true);
        //setting lines to display on x axis
        multiRenderer.setShowGridX(true);
        //setting legend to fit the screen size
        multiRenderer.setFitLegend(true);
        //setting displaying line on grid
        multiRenderer.setShowGrid(true);
        //setting zoom to false
        multiRenderer.setZoomEnabled(false);
        //setting external zoom functions to false
        multiRenderer.setExternalZoomEnabled(false);
        //setting displaying lines on graph to be formatted(like using graphics)
        multiRenderer.setAntialiasing(true);
        //setting to in scroll to false
        multiRenderer.setInScroll(false);
        //setting to set legend height of the graph
        multiRenderer.setLegendHeight(30);
        //setting x axis label align
        multiRenderer.setXLabelsAlign(Paint.Align.CENTER);
        //setting y axis label to align
        multiRenderer.setYLabelsAlign(Paint.Align.LEFT);
        //setting text style
        multiRenderer.setTextTypeface("sans_serif", Typeface.NORMAL);
        //setting no of values to display in y axis
        multiRenderer.setYLabels(10);
        // setting y axis max value, Since i'm using static values inside the graph so i'm setting y max value to 60.
        // if you use dynamic values then get the max y value and set here
        multiRenderer.setYAxisMin(0);
        multiRenderer.setYAxisMax(80);

        multiRenderer.setXLabels(4);
        //setting used to move the graph on xaxis to 0 to the right
        multiRenderer.setXAxisMin(0);
        //setting used to move the graph on xaxis to 0 to the right
        multiRenderer.setXAxisMax(61);
        //setting bar size or space between two bars
        //multiRenderer.setBarSpacing(0.5);
        //Setting background color of the graph to transparent
        multiRenderer.setBackgroundColor(Color.TRANSPARENT);
        //Setting margin color of the graph to transparent
        multiRenderer.setMarginsColor(Color.argb(0x00, 0x01, 0x01, 0x01));
        multiRenderer.setApplyBackgroundColor(true);
        multiRenderer.setScale(2f);
        //setting x axis point size
        multiRenderer.setPointSize(4f);
        //setting the margin size for the graph in the order top, left, bottom, right    
        multiRenderer.setMargins(new int[]{30, 30, 30, 30});

        /*for(int i=0; i< x.length;i++){
            multiRenderer.addXTextLabel(i, mTime[i]);
        }*/

        // Adding Force L Renderer and Force R Renderer to multipleRenderer
        // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
        // should be same
        multiRenderer.addSeriesRenderer(force_lRenderer);
        multiRenderer.addSeriesRenderer(force_rRenderer);

        //this part is used to display graph on the xml
        LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart);
        //remove any views before u paint the chart
        chartContainer.removeAllViews();
        //drawing bar chart
        mChart = ChartFactory.getLineChartView(MainActivity.this, dataset, multiRenderer);
        //adding the view to the linearlayout
        chartContainer.addView(mChart);

    }
}
João Amaro
  • 454
  • 2
  • 10
  • 23
  • What is the problem you are experiencing with the code above? – Benjamin Lowry Feb 11 '16 at 14:55
  • The problem is that I don't know how to format the values from the text file in the way I need and I don't know either how to import them to the int[] force_l and int[] force_r – João Amaro Feb 11 '16 at 14:58

2 Answers2

1

Use a BufferedReader to read the input file line by line(see this answer How to get file read line by line) and for each line make a split over the " "(space)

String line = "0 25 24 25 15 16 17 25 24 21 24"; /* this should be the line from file*/
String[] force_l  = line.split(" ");
force_l[0]; // this will contain "0"
force_l[1]; // this will contain " 25"

Then you can convert values to int like

Integer.parseInt(force_l[0])

Also add the file to assets, it will be easy for you not to use an absolute path like "C:/test.txt"

Community
  • 1
  • 1
Pahomi
  • 455
  • 6
  • 17
1

Things that you should pay attention is that you get individual line with line of integers separated by space, from this you can generate a String array like this String[] integer_Strings = s.split(" "); now that you have the string value for each integer you can convert this string value to int like this Integer.parseInt("2"). This method return 2 in int 2, code is also available in github

    int[] force_l = null;
    int[] force_r = null;
    try {

        File file = new File("file_json_test_three.txt");
        Path path = file.toPath();
        List<String> strings = Files.readAllLines(path);
        //List<String> strings = FileUtils.readLines(file); can be used with common-io-2.4 library
        int count = 0;
        for (String s : strings) {
            //System.out.println(s);
            String[] integer_Strings = s.split(" ");
            //System.out.println(Arrays.deepToString(integer_Strings));
            if (count == 0) {
                force_l = new int[integer_Strings.length];
                for (int i = 0; i < integer_Strings.length; i++) {
                    force_l[i] = Integer.parseInt(integer_Strings[i]);
                }
                count++;
            } else if (count == 1) {
                force_r = new int[integer_Strings.length];
                for (int i = 0; i < integer_Strings.length; i++) {
                    force_r[i] = Integer.parseInt(integer_Strings[i]);
                }
            }

        }

        System.out.println(Arrays.toString(force_l));
        System.out.println(Arrays.toString(force_r));


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

Output

[0, 25, 24, 25, 15, 16, 17, 25, 24, 21, 24]
[0, 48, 36, 26, 43, 45, 30, 33, 33, 28, 42]
Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30
  • Thanks. It says "Cannot resolve method 'toPath()' and I can't find an answer in google – João Amaro Feb 13 '16 at 12:30
  • @JoãoAmaro, well it should work in java, or you can try it out common-io-2.4 library, and the commented code will work, code is available here, https://github.com/pankajnimgade/JavaCoding_tutorials/blob/master/src/stack/overflow/test/two/ReadIntegerFromFile.java if you would like download the project and run it – Pankaj Nimgade Feb 13 '16 at 14:05
  • @JoãoAmaro, java.io.File you need to import for File, your JDK should be 1.8 to be able to use this method. or you can add the library ( common-io-2.4 ) which is available in the project – Pankaj Nimgade Feb 13 '16 at 14:13
  • still can't use it in Android Studio after upgrading to 1.8. So if I add "common-io-2.4", what should I comment and what should I uncomment? – João Amaro Feb 14 '16 at 15:48
  • comment this line, Path path = file.toPath(); List strings = Files.readAllLines(path);... and UN-comment this line List strings = FileUtils.readLines(file);,..... your code might change depending on how you are reading the file (example asset or raw) – Pankaj Nimgade Feb 14 '16 at 18:17
  • Thanks a lot! Now I changed the question and put my code because I'm a total noob and I can't figure out how to send the strings from one class to another. Can you help me with that? – João Amaro Feb 15 '16 at 23:59
  • check how getter and setter method works, it would be a one line code for you, all you have to do is store data in String variable, make a static getter method which returns String for that, and you can call that method from anywhere to retrieve the String variable – Pankaj Nimgade Feb 16 '16 at 05:25
  • @JoãoAmaro, check this out, it will give you some idea about getter and setters http://stackoverflow.com/questions/2036970/how-do-getters-and-setters-work, you will have to use static member. once done it will be piece of cake – Pankaj Nimgade Feb 16 '16 at 05:52
  • Great! Thank you @Pankaj Nimgade – João Amaro Feb 16 '16 at 12:27
  • @JoãoAmaro, You are welcome, I am glad, that I could help – Pankaj Nimgade Feb 16 '16 at 14:07
  • I'm trying different methods, but still totally not getting it! – João Amaro Feb 16 '16 at 17:43
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/103632/discussion-between-pankaj-nimgade-and-joao-amaro). – Pankaj Nimgade Feb 16 '16 at 17:57
  • @JoãoAmaro, check this code i have tested and it works, https://github.com/pankajnimgade/Tutorial/blob/master/app/src/main/java/miscellaneous/list/activities/ReadFromAssetActivity.java – Pankaj Nimgade Feb 17 '16 at 04:56