I am new to android, and I have to create an app that plots data. One set of data is about 7000 data point, and I've been using AChartEngine. I am using an ArrayList to hold the data.
ArrayList<Double> forehead = new ArrayList<Double>();
private XYMultipleSeriesDataset getforeDataset() {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
XYSeries firstSeries = new XYSeries("Forehead");
for (int i = 0; i < forehead.size(); i++)
firstSeries.add(i, forehead.get(i));
dataset.addSeries(firstSeries);
return dataset;
this is where I add data into the ArrayList, a sample string that would be read in is:
"02888 0 096 098 080"
private void getIntegerArray(ArrayList<String> stringArray) {
for (String s:stringArray){
String[] str = s.split("\t");
forehead.add(Double.parseDouble(str[3]));
}
}
private XYMultipleSeriesRenderer getforeRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setMargins(new int[] { 0, 0, 0, 0 });
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(Color.BLUE);
r.setPointStyle(PointStyle.POINT);
r.setFillPoints(false);
renderer.addSeriesRenderer(r);
return renderer;
}
plotting
mChartView2 = ChartFactory.getLineChartView(getActivity(), getforeDataset(),
getforeRenderer());
layout2.addView(mChartView2);
Here is my application and no data is displayed, how can I display the 'forehead' ArrayList?
http://imgur.com/aYyDVnL
Use this
String[] str = s.split(" ");
instead of
String[] str = s.split("\t");
I think you are not getting the values as you want.
Related
community,
I am currently stuck on a homework assignment which requires me to read a text file and then make further calculations with it, my questions are now.
How do I read a text file and store the columns in several arrays to make further calculations?
I have written a piece of code which already reads the file, but doesn't seem to store the columns in arrays as I keep getting "ArrayOutOfBoundsException".
I have already tried the given code below, which doesn't give me what I need.
Unfortunately, I haven't found anything that was able to solve the problem.
The columns are separated by Tabs.
This is what the table looks like
Date Open High Low Close Volume
29.12.2017 12.980,09 12980.74 12.911,773 12.917.64 1.905.806.208
....
....
....
and so on
try {
ArrayList < String > KursDaten = new ArrayList<String>();
String Zeile = null;
while ((Zeile = in.readLine()) != null) {
Zeile = Zeile.replaceAll("\u0000", "");
Zeile = Zeile.replaceAll("�", "");
String[] columns = in.readLine().split(" ");
columns = in.readLine().split("\t");
String data = columns[columns.length - 1];
KursDaten.add(data);
out.println(Zeile);
}
int size = KursDaten.size();
out.println(KursDaten.size());
String[] arr1 = new String[size];
String[] arr2 = new String[size];
String[] arr3 = new String[size];
String[] arr4 = new String[size];
String[] arr5 = new String[size];
String[] arr6 = new String[size];
for (int i = 0; i < size; i++) {
String[] temp = KursDaten.get(i).split("\t\t");
temp = KursDaten.get(i).split("\t");
arr1[i] = temp[0];
arr2[i] = temp[1];
arr3[i] = temp[2];
arr4[i] = temp[3];
arr5[i] = temp[4];
arr6[i] = temp[5];
System.out.println(Arrays.toString(arr1));
}
}
catch (NullPointerException e) {
}
I expect the columns of the list to be stored in the different arrays, with which I then can make further calculations as needed.
I am using MPAndroid Library to create pie chart in my app, i am able take user input and display in pie chart but when user enter same value which is already in pie chart it won't displayed in pie chart and again when i enter different value, the previous value which i entered but didn't displayed will display in pie chart.
Any help will be appreciated !! Thank You.
Below is my pieChart method:
public void pieChart() {
mydb = new DBHelper(this);
try {
//Check for table in database
if (mydb.checkForTables())
{
stringItems.addAll(mydb.getAllItem());
intItems.addAll(mydb.getAllAmount());
} else {
Toast.makeText(this, "Data table is empty.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
List<Entry> yVals1 = new ArrayList<Entry>();
if(intItems.size() > 0)
{
for (int i = 0; i < intItems.size(); i++)
yVals1.add(new Entry(intItems.get(i), i));
}
else {
Toast.makeText(this,"intItem is empty !!",Toast.LENGTH_LONG).show();
}
List<String> xVals = new ArrayList<String>();
if(stringItems.size() > 0)
{
for (int i = 0; i < stringItems.size(); i++)
xVals.add(stringItems.get(i));
}else {
Toast.makeText(this,"stringItem is empty !!",Toast.LENGTH_LONG).show();
}
// create pieDataSet
PieDataSet dataSet = new PieDataSet(yVals1, " ");
dataSet.setSliceSpace(3);
dataSet.setSelectionShift(5);
// adding colors
List<Integer> colors = new ArrayList<Integer>();
// Added My Own colors
for (int c : MY_COLORS)
colors.add(c);
dataSet.setColors(colors);
// create pie data object and set xValues and yValues and set it to the pieChart
PieData data = new PieData(xVals, dataSet);
// data.setValueFormatter(new DefaultValueFormatter());
// data.setValueFormatter(new PercentFormatter());
data.setValueFormatter(new MyValueFormatter());
data.setValueTextSize(10f);
data.setValueTextColor(Color.WHITE);
mChart.setData(data);
// undo all highlights
mChart.highlightValues(null);
// refresh/update pie chart
mChart.invalidate();
// animate piechart
mChart.animateXY(1400, 1400);
// Legends to show on bottom of the graph
Legend l = mChart.getLegend();
l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
l.setXEntrySpace(7);
l.setYEntrySpace(5);
}
private SpannableString generateCenterSpannableText() {
SpannableString s = new SpannableString("Overview");
s.setSpan(new RelativeSizeSpan(1.7f), 0, 8, 0);
s.setSpan(new StyleSpan(Typeface.NORMAL), 8, s.length(), 0);
return s;
}
public class MyValueFormatter implements ValueFormatter {
private DecimalFormat mFormat;
public MyValueFormatter() {
mFormat = new DecimalFormat("###,###,##0"); // use one decimal if needed
}
#Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
// write your logic here
return mFormat.format(value) + ""; // e.g. append a dollar-sign
}
}
I have produced a line graph like this. Even though there are no zero data for the blue line and also the red line only have the value until 100. So how do i set the blue line to start at zero and red to finish until 200 like this:
My data in textfile (outputAvgGen.txt) are:
11752.58,HC
11819.65,HC
11941.75,HC
12398.45,HC
12401.06,HC
12531.09,HC
12634.33,HC
12748.83,HC
12787.36,HC
12799.44,HC
.
.
.
30137.15,P3
31919.46,P3
32323.8,P3
.
.
.
and so on until 200 data
This is my code:
public class Graph2 extends JFrame{
public Graph2(){
setTitle("P3 Performance Analysis");
JPanel chartPanel = createChartPanel();
add(chartPanel, BorderLayout.CENTER);
setSize(640, 480);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Graph2().setVisible(true);
}
});
}
private JPanel createChartPanel() {
// creates a line chart object
// returns the chart panel
String chartTitle = "Average Fitness against No. of Generations";
String xAxisLabel = "No. of Generations";
String yAxisLabel = "Average Fitness";
XYDataset dataset = createDataset();
JFreeChart chart = ChartFactory.createXYLineChart(chartTitle,
xAxisLabel, yAxisLabel, dataset);
XYPlot plot = chart.getXYPlot();
NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
yAxis.setAutoRangeIncludesZero(true);
return new ChartPanel(chart);
}
private XYDataset createDataset() {
ArrayList<PlotData2> dataList = readData();
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries series1 = new XYSeries("Hill Climber");
XYSeries series2 = new XYSeries("P3");
for (int i = 0; i < dataList.size(); i++){
if (dataList.get(i).getAlgo().equals("HC")){
series1.add(i, dataList.get(i).getAvg());
System.out.println("HC i=" + i);
}
else if (dataList.get(i).getAlgo().equals("P3")){
series2.add(i, dataList.get(i).getAvg());
System.out.println("P3 i=" + i);
}
}
/*
for (int i = 0; i < dataList.size(); i++){
if (dataList.get(i).getAlgo().equals("HC")){
System.out.println("i = " + i);
series1.add(i, dataList.get(i).getAvg());
}
}
for (int j = 0; j < dataList.size(); j++){
if (dataList.get(j).getAlgo().equals("P3")){
System.out.println("j = " + j);
series2.add(j, dataList.get(j).getAvg());
}
}*/
/*
series1.add(1.0, 2.0);
series1.add(2.0, 3.0);
series1.add(3.0, 2.5);
series1.add(3.5, 2.8);
series1.add(4.2, 6.0);
series2.add(2.0, 1.0);
series2.add(2.5, 2.4);
series2.add(3.2, 1.2);
series2.add(3.9, 2.8);
series2.add(4.6, 3.0); */
dataset.addSeries(series1);
dataset.addSeries(series2);
return dataset;
}
public static ArrayList<PlotData2> readData(){
ArrayList<PlotData2> dataList = new ArrayList<PlotData2>();
try {
BufferedReader in = new BufferedReader( new FileReader("outputAvgGen.txt") );
String str;
while ( (str = in.readLine() )!= null ) {
String[] data = str.split( "," );
double avg = Double.parseDouble(data[0]);
String algo = data[1];
// int gen = Integer.parseInt(data[2]);
dataList.add(new PlotData2(algo,avg));
}
in.close();
} catch ( IOException ex ) {
System.err.println( "Error: Can't open the file for reading." );
}
return dataList;
}
}
Actually my original data being computed are in pairs of HC and P3 in a textfile like this:
15426.35,HC
38903.93,P3
13777.49,HC
34480.21,P3
15199.38,HC
38559.36,P3
13399.15,HC
32931.49,P3
.
.
and so on..
but I sorted it to make the graph being plotted ascendingly but when sorted it doesn't plot according to the pairs.
Can someone please help with the code at least to make it start at zero and end at max range for both lines to make it look simultaneous. Thank you.
The major issue with your code is that you are incrementing the x values for both series simultaneously. You need to do that separately. Furthermore, you are using hardcoded strings in your createDataset method.
Try this approach instead:
public static HashMap<String, List<Double>> readData() {
HashMap<String, List<Double>> dataList = new HashMap<String, List<Double>>();
try {
BufferedReader in = new BufferedReader(new FileReader("outputAvgGen.txt"));
String str;
while ((str = in.readLine()) != null) {
String[] data = str.split(",");
String algo = data[1];
if (dataList.get(algo) == null) {
dataList.put(algo, new ArrayList<Double>());
}
dataList.get(algo).add(Double.parseDouble(data[0]));
}
in.close();
}
catch (IOException ex) {
System.err.println("Error: Can't open the file for reading.");
}
return dataList
}
private XYDataset createDataset() {
HashMap<String, List<Double>> dataList = readData();
XYSeriesCollection dataset = new XYSeriesCollection();
Set<String> keys = dataList.keySet();
for (String key : keys) {
XYSeries series = new XYSeries(key);
List<Double> numbers = dataList.get(key);
for (int i = 0; i < numbers.size() - 1; i++) {
series.add(i, numbers.get(i), false);
}
series.add(numbers.size() - 1, numbers.get(numbers.size() - 1), true);
dataset.addSeries(series);
}
return dataset;
}
Here I am reading a string by opening my database and then trying to plot a graph based on that.I will really appreciate if anyone could help me solve this.Thanks
Method from MyDatabase which I am reading;
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_SYSTOLIC,KEY_DIASTOLIC,KEY_PULSE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result =" ";
int iSys = c.getColumnIndex(KEY_SYSTOLIC);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iSys) + ",";
}
return result;
// The string from the database looks like "1,2,3,4,5";
MyDatabase myDb = new MyDatabase(this);
myDb.open();
String pull = myDb.getData();
pull = pull.substring(0, pull.length() - 1);
myDb.close();
String test = '"' + pull + '"';
String[] items = test.split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {};
}
// doesn't plots a graph on int[] results.
int[] yAxis = new int[]{11,12,13};
TimeSeries series = new TimeSeries("X-Axis");
for(int s=0; s< results.length; s++){
series.add(results[s], yAxis[s]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer renderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(renderer);
LinearLayout chart_container=(LinearLayout)findViewById(R.id.Chart_layout);
mChart=(GraphicalView)ChartFactory.getLineChartView(getBaseContext(), dataset, mRenderer);
chart_container.addView(mChart);
}
The variable i is not available outside the for loop.
You could declare a variable i before the for loop and use it, but it would not help you in this case.
If you want to populate the arr[], try this:
String[] items = test.split(",");
int[] arr = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
arr[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {};
}
You cannot access i outside the for loop. It's not related to try/catch
As a work around you can define i before the loop
I have an array that is from .split command and want to put it into an array called String[][] datatabvars, I do not know how to turn datatabvars into a two dimensional array and put the data into it.
public String[] getList() {
String file_name = "path";
String[] links = null;
String[][] datatabvars = null; // this var
int numberOfDatatabs = 0;
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for(i=0; i < aryLines.length; i++) { //aryLines.length
if (aryLines[i].substring(0, 7).equals("datatab")) {
aryLines[i] = aryLines[i].replace("datatab["+Integer.toString(numberOfDatatabs)+"] = new Array(", "");
aryLines[i] = aryLines[i].replace(");", "");
datatabvars = aryLines[i].split(","); // this split array
numberOfDatatabs++;
}
}
System.out.println(datatabvars[0]);
}catch (IOException e) {
System.out.println( e.getMessage() );
}
return links;
}
Update the two lines(I added comment) as below: (I am assuming that rest of your code is working)
String[][] datatabvars = null; // this var
int numberOfDatatabs = 0;
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
datatabvars = new String[aryLines.length][]; // INITIALIZED
int i;
for(i=0; i < aryLines.length; i++) { //aryLines.length
if (aryLines[i].substring(0, 7).equals("datatab")) {
aryLines[i] = aryLines[i].
replace("datatab["+Integer.toString(numberOfDatatabs)+"] =
new Array(", "");
aryLines[i] = aryLines[i].replace(");", "");
datatabvars[i] = aryLines[i].split(","); // this split array: ASSIGNED
numberOfDatatabs++;
}
}
System.out.println(datatabvars[0]);
In general, arrays are to avoided like the plague - use collections if possible:. In this case, split() returns a String[], so use that, but use List<String[]> to store multiple String[]:
List<String[]> datatabvars = new ArrayList<String[]>();
...
String[] array = input.split(",");
datatabvars.add(array);
You find life is much easier using collections than arrays.