I have to retrieve some data from a file to show it in a chart. The function that shows the chart requires he data as float[] whereas the retrieved data is in the form ArrayList<String>.
What is the easiest way to convert ArrayList<String> to float[]?
try {
FileInputStream fIn = context.openFileInput(fileDir+fileName);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
ArrayList<String> list_prix = new ArrayList<String>();
String ligne;
while ((ligne = b.readLine()) != null) {
String dtVal = ligne.split(" ")[2];
dtVal = dtVal.substring(0, dtVal.length() - 2);
list_prix.add(dtVal);
}
//just here if i can convert list_prix to float[]
fIn.close();
ipsr.close();
}
catch (Exception e)
{
Log.e("blah", "Exception", e);
}
Thank you for your help.
I think the following will do it using Guava...
Collection<Float> floats = Collections2.transform(list_prix, new Function<String, Float>() {
public Float apply(String input) {
return Float.parseFloat(input);
}
});
Float[] floatArray = new Float[floats.size()];
floats.toArray(floatArray);
You can loop and use Float.parseFloat().
float [] floatValues = new float[list_prix.size()];
for (int i = 0; i < list_prix.size(); i++) {
floatValues[i] = Float.parseFloat(list_prix.get(i));
}
Now, this assumes that every string in your ArrayList can actually be parsed into a float. If not, it could throw an exception, so you may want to do this in a try/catch block if you are not sure.
Related
I am creating an application where i do some real-time image analysis and store them into a csv file. The csv has 2 columns time and y-value of each frame.
I want to read this file and store the values from 2 columns into to double array. I want this because i want to perform an fast Fourier transformation on the data.
public class MainActivity extends AppCompatActivity implements CameraView.PreviewReadyCallback {
private static Camera camera = null;
private CameraView image = null;
private LineChart bp_graph;
private int img_Y_Avg, img_U_Avg, img_V_Avg;
private long end = 0, begin = 0;
double valueY, valueU, valueV;
Handler handler;
private int readingRemaining = 1200;
private static long time1, time2, timeDifference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
bp_graph = (LineChart)findViewById(R.id.graph);
graph_features();
//open camera
try {
camera = Camera.open();
handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
camera.stopPreview();
camera.release();
}
};
handler.postDelayed(runnable, 30000);
} catch (Exception e) {
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if (camera != null) {
image = new CameraView(this, camera);
FrameLayout camera_view = (FrameLayout) findViewById(R.id.camera_view);
camera_view.addView(image);
image.setOnPreviewReady(this);
}
}
#Override
protected void onResume(){
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onPreviewFrame(long startTime, int ySum, int uSum, int vSum, long endTime) {
begin = startTime;
img_Y_Avg = ySum;
img_U_Avg = uSum;
img_V_Avg = vSum;
end = endTime;
showResults(begin, img_Y_Avg, img_U_Avg, img_V_Avg, end);
}
private void showResults(long startTime, int ySum, int uSum, int vSum, long endTime){
//set value of Y on the text view
TextView valueOfY = (TextView)findViewById(R.id.valueY);
//valueY = img_Y_Avg;
valueOfY.setText(String.valueOf(img_Y_Avg));
//start time in milliseconds
long StartDurationInMs = TimeUnit.MILLISECONDS.convert(begin, TimeUnit.MILLISECONDS);
ArrayList<Long> startOfTime = new ArrayList<>();
startOfTime.add(StartDurationInMs);
//store value to array list
ArrayList<Integer> yAverage = new ArrayList<>();
yAverage.add(img_Y_Avg);
//convert to readable format
String readableDate = new SimpleDateFormat("MMM dd,yyyy, HH:mm:ss.SSS").format(EndDurationInMs);
Log.d("Date ", readableDate);
Log.d("time ", String.valueOf(String.valueOf(yAverage.size())));
//store when all array are generated
Log.d("time ", String.valueOf(StartDurationInMs));
ArrayList<Long> getValues = new ArrayList<>();
for(int i = 0; i < yAverage.size(); i++) {
getValues.add(startOfTime.get(i));
getValues.add((long)(yAverage.get(i)));
}
//store the yAverage and start time to csv file
storeCsv(yAverage, getValues);
Log.d("MyEntryData", String.valueOf(getValues));
}
public void storeCsv(ArrayList<Integer>yAverage, ArrayList<Long>getValues){
String filename = "temporary.csv";
//File directoryDownload = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/bpReader";
//File logDir = new File (directoryDownload, "bpReader"); //Creates a new folder in DOWNLOAD directory
File logDir = new File(path);
logDir.mkdirs();
File file = new File(logDir, filename);
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file, true);
//outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
for (int i = 0; i < yAverage.size(); i += 2) {
outputStream.write((getValues.get(i) + ",").getBytes());
outputStream.write((getValues.get(i + 1) + "\n").getBytes());
//outputStream.write((getValues.get(i + 2) + ",").getBytes());
//outputStream.write((getValues.get(i + 3) + "\n").getBytes());
}
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void readCsv(){
}
}
This is my MainActivity. What I am doing here is getting the data from CameraView class for each frame with the help of an interface that I created. After that im storing the values into a CSV file called temporary.csv.
Issues
I want to read this csv and store the first column(the time) into one double array and the second column(yAverage) into another double array.
I also want to delete the file once i have all the data stored into the into the double array.
How can I do that?
I would suggest youto use an open source library like OpenCSV to get the datafrom the CSV file. When you have the library implemented it's only a matter of iterating through the x and y columns and assign them to an array. With OpenCSV it would look like that. But i would also suggest you an more object orientec approach if the x and y with the same index coords are related to each other.
String csvFile = "/Users/mkyong/csv/country3.csv";
int length = 100; //If you dont know how many entries the csv file has i would suggest to use ArrayList
double[] xCoords = new double[length];
double[] yCoords = new double[length];
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(csvFile));
String[] line;
int i = 0;
while ((line = reader.readNext()) != null) {
xCoords[i] = Double.parseDouble(line[0]);
yCoords[i] = Double.parseDouble(line[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
From the answer given by Lucas, I got the direction to my solution
public void readCsv(){
//set the path to the file
String getPath = Environment.getExternalStorageDirectory() + "/bpReader";
String csvFile = "temporary.csv";
String path = getPath+ "/" + csvFile;
//File file = new File(path, csvFile);
int length = 500;
double[] xCoords = new double[length];
double[] yCoords = new double[length];
CSVReader reader = null;
try {
File myFile = new File (path);
reader = new CSVReader(new FileReader(myFile));
String[] line;
int i = 0;
while ((line = reader.readNext()) != null) {
xCoords[i] = Double.parseDouble(line[0]) ;
yCoords[i] = Double.parseDouble(line[1]);
Log.d("read:: ", "Time: "+String.valueOf(xCoords[i])+" Y: "+String.valueOf(yCoords[i]));
}
myFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
And then i had to add
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.6'
to my gradle,, which can be found at MVN repository
I have created an ArrayList. I read text file from Android phone and store String[3] in each array. I used the debugger to trace the value of each variable. The value in ArrayList seem like always follow the value of buffer. Is it any link between them?
ArrayList<String[]> label_list = new ArrayList<>();
try {
FileInputStream fIn = new FileInputStream(getPath());
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String[] buffer = new String[3];
int j=0;
while ((aDataRow = myReader.readLine()) != null) {
if(!aDataRow.equals("")){
buffer[j]=aDataRow;
j++;
}else{
label_list.add(buffer);
j=0;
}
}
label_list.add(buffer); //for last one
myReader.close();
for(int i=0;i<label_list.size();i++){
txt_show.append(label_list.get(i)[0]);
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
The text file i read.
The result of debugger. As you can see, all arrays have same value. The value in Arraylist will always follow the value of buffer.
You must put that j++ out of if else condition.
ArrayList<String[]> label_list = new ArrayList<>();
try {
FileInputStream fIn = new FileInputStream(getPath());
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String[] buffer = new String[3];
int j=0;
while ((aDataRow = myReader.readLine()) != null) {
if(!aDataRow.equals("")){
buffer[j]=aDataRow;
}else{
label_list.add(buffer);
}
j++;
}
label_list.add(buffer); //for last one
myReader.close();
for(int i=0;i<label_list.size();i++){
txt_show.append(label_list.get(i)[0]);
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
hope it helps
I found my mistake. Add buffer = new String[3]; will solve my problem but I do not know why. Can anyone explain to me?
try {
FileInputStream fIn = new FileInputStream(getPath());
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String[] buffer = new String[3];
int j=0;
while ((aDataRow = myReader.readLine()) != null) {
if(!aDataRow.equals("")){
buffer[j]=aDataRow;
j++;
}else{
label_list.add(buffer);
j=0;
**buffer = new String[3];**
}
}
myReader.close();
for(int i=0;i<label_list.size();i++){
txt_show.append(label_list.get(i)[0]);
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
I am trying to obtain the 4th and 5th elements from the csv data and use it as a dataset for the 2nd (mDatasetNormal) and third graph line. I was able to figure out how to obtain the data from the 3rd element however the rest is an issue.
My questions are:
How to read the Heappy_log.csv and than use the arrayList to obtain data for the graph?
After data is obtained from the csv how to use it for the same graph?
CSV file content:
Aug-30-2014,08:06 AM, 0,0,0
Sep-05-2014,08:09 AM, 0,3,2
Sep-05-2014,08:09 AM, 0,3,2
Whole code:
public class Chart extends Activity {
ArrayList<Integer> stateList = new ArrayList<Integer>();
ArrayList<Integer> normalList = new ArrayList<Integer>();
//Chart creation
private GraphicalView mChart, mChartNormal;
/**
* Create multiple data sets to be used on graph
*/
//Data sets used for graph manipulation
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
private XYSeries mCurrentSeries;
private XYSeriesRenderer mCurrentRenderer;
private XYMultipleSeriesDataset mDatasetNormal = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer mRendere2 = new XYMultipleSeriesRenderer();
private XYSeries mCurrentSeriesNormal;
private XYSeriesRenderer mCurrentRendererNormal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Code which makes activity full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_chart);
readHappyLog();
}
//Create a method for the aChart engine
private void initChart() {
//Series description for both charts
mCurrentSeries = new XYSeries("Amount of happy kids");
mDataset.addSeries(mCurrentSeries);
mCurrentSeriesNormal = new XYSeries("Amount of normal kids");
mDatasetNormal.addSeries(mCurrentSeriesNormal);
//Renderer for happy kids
mCurrentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(mCurrentRenderer);
mRenderer.setAxisTitleTextSize(24);
mRenderer.setYLabelsPadding(20);
mRenderer.setXLabelsPadding(10);
mRenderer.setXTitle(" Date of practice ");
mRenderer.setYTitle(" Number of kids ");
//Renderer for normal kids
mCurrentRendererNormal = new XYSeriesRenderer();
mRendere2.addSeriesRenderer(mCurrentRendererNormal);
mRendere2.setYTitle("Number of normal kids");
//Applying background
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.BLACK);
mRenderer.setMarginsColor(Color.BLACK);
mRenderer.setPointSize(20);
mRenderer.setShowGrid(true);
mRenderer.setAxesColor(Color.MAGENTA);
mRenderer.setGridColor(Color.MAGENTA);
mRenderer.setPanEnabled(true, true);
mRenderer.setXAxisMin(0.0);
mRenderer.setYAxisMin(0.0);
mRenderer.setLabelsTextSize(24);
//Sets the color of the graph line and width
mCurrentRenderer.setColor(Color.GREEN);
mCurrentRenderer.setLineWidth(10f);
mCurrentRendererNormal.setColor(Color.BLUE);
mCurrentRenderer.setLineWidth(10f);
}
//Add x and y data into the graph and mark the x graph
private void addHappyData(){
Integer x = 0;
for (Integer happy : stateList ){
mCurrentSeries.add(x += 10, happy);
}
}
//Add x and y for normal to the graph
private void addNormalData(){
Integer y = 0;
for (Integer happy : normalList ){
mCurrentSeriesNormal.add(y += 10, happy);
}
}
// Draw the graph
#Override
protected void onResume() {
super.onResume();
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
if (mChart == null){
initChart();
addHappyData();
addNormalData();
//Set chart type
mChart = ChartFactory.getLineChartView(this, mDataset , mRenderer);
layout.addView(mChart);
mChartNormal = ChartFactory.getLineChartView(this, mDatasetNormal,mRendere2);
layout.addView(mChartNormal);
}else{
mChart.repaint();
mChartNormal.repaint();
}
}
/**
* create a method to read the happy log
*/
private void readHappyLog(){
String FILENAME = "happy_log.csv"; //Open the file name under this string
FileInputStream inputStream = null; // Import the package
String temp;
String[] a;
try {
inputStream = openFileInput(FILENAME); //Open file desceriptor (Object)
byte[] reader = new byte [inputStream.available() ]; //Everything from disk is byte
while (inputStream.read( reader ) != -1 ){}
//Reader array now holds the entire file
//Needs to create scanner in order to read the file properly
Scanner s = new Scanner (new String(reader));
s.useDelimiter(("\\n"));
while (s.hasNext()){
//Split the string lines if he sees comma value
temp = s.next();
a = temp.split(",");
stateList.add(Integer.parseInt(a[2]));
normalList.add(Integer.parseInt(a[3]));
}
s.close();
}catch (Exception e ){
Log.e("Chart", e.getMessage());
}finally {
if (inputStream != null ){
try{ inputStream.close();
} catch (IOException e){
Log.e( "Chart", e.getMessage());
}
}
}
}
Problem solved:
//Add x and y data to series
private void addHappyData() {
Integer x = 0;
for (Integer happy : stateList) {
mCurrentSeries.add(x += 10, happy);
}
}
private void addNormalData() {
Integer x = 0;
for (Integer normal : normalList) {
mNormalSeries.add(x += 10, normal);
}
}
// Draw the graph
#Override
protected void onResume() {
super.onResume();
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
if (mChart == null) {
initChart();
addHappyData();
addNormalData();
//Set chart type
mChart = ChartFactory.getLineChartView(this, mDataset, mRenderer);
layout.addView(mChart);
} else {
mChart.repaint();
}
}
/**
* create a method to read the happy log
*/
private void readHappyLog() {
String FILENAME = "happy_log.csv"; //Open the file name under this string
FileInputStream inputStream = null; // Import the package
String temp;
String[] a;
try {
inputStream = openFileInput(FILENAME); //Open file desceriptor (Object)
byte[] reader = new byte[inputStream.available()]; //Everything from disk is byte
while (inputStream.read(reader) != -1) {
}
//Reader array now holds the entire file
//Needs to create scanner in order to read the file properly
Scanner s = new Scanner(new String(reader));
s.useDelimiter(("\\n"));
while (s.hasNext()) {
//Split the string lines if he sees comma value
temp = s.next();
a = temp.split(",");
stateList.add(Integer.parseInt(a[2]));
normalList.add(Integer.parseInt(a[3]));
}
s.close();
} catch (Exception e) {
Log.e("Chart", e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Chart", e.getMessage());
}
}
}
}
}
I cannot, by now, understand why I got an out-of-memory exception when I load 9 different textfiles into my android app. The total size of the textfiles is about 10 MB. And I hade to change to large-heapsize in the manifest file to be able to load these files. Its not a good solution, so I wonder if someone could help me to understand what causes the heapsize to rize over 100 MB.
Another thing, could be a clue of something??, is that when heapsize has climed a bit over 100 MB and allocated memory is sligtly below - all loading is done, something happends:
The garbagecollector makes something immediately when loading is finished - the allocated space falls dramatically from 100 MB to 35 MB.
SO I wonder - what is happening? Why is the loading so memory consuming?
I can say that I have a class called FileManager where all loading taking place.
And because FileManager do not extend Activity, I have to pass a context to this class.
Could it be the context that is memory consuming? I think It may be and I have to move the loading when the app starts app at first.
Here is the FileManager-class
public class FileManager {
private String[][] solarObj,, celestObj, stars, sun, moon, venus, march, jupiter, saturn;
private ArrayList <String[][]> stringObjects = new ArrayList <String[][]> () ;
private String[] textFile;
private Context context;
private AssetManager assetManager;
public FileManager(Context context) {
this.context = context;
assetManager = context.getResources().getAssets();
instanciateStrings();
putStringsToList();
initializeTextFile();
for (int array_index = 0; array_index < 9; array_index++) {
read(this.textFile[array_index], this.stringObjects.get(array_index).length, array_index);
//printString(array_index);
}
}
private void instanciateStrings() {
this.solarObj = new String[98][4];
this.celestObj = new String[7][3];
this.stars = new String[92][7];
this.sun = new String[14246][15];
this.moon = new String[14246][15];
this.venus = new String[14246][15];
this.march = new String[14246][15];
this.jupiter = new String[14246][15];
this.saturn = new String[14246][15];
}
/**
* Lägger in de tvådimensionella strängvektorerna i en arraylist.
*/
private void putStringsToList() {
this.stringObjects.add(this.celestObj);
this.stringObjects.add(this.solarObj);
this.stringObjects.add(this.stars);
this.stringObjects.add(this.sun);
this.stringObjects.add(this.moon);
this.stringObjects.add(this.venus);
this.stringObjects.add(this.march);
this.stringObjects.add(this.jupiter);
this.stringObjects.add(this.saturn);
}
/**
* Filnamnen läses in i en strängvektor
*/
private void initializeTextFile() {
this.textFile = new String[9];
this.textFile[0] = "celestobj_txt.txt";
this.textFile[1] = "solarObj_txt.txt";
this.textFile[2] = "stars_txt.txt";
this.textFile[3] = "sun_txt.txt";
this.textFile[4] = "moon_txt.txt";
this.textFile[5] = "venus_txt.txt";
this.textFile[6] = "march_txt.txt";
this.textFile[7] = "jupiter_txt.txt";
this.textFile[8] = "saturn_txt.txt";
}
private void read(String text_file, int len, int index) {
String[] stringBuffer = new String[len]; // temporär textsträng som read-objektet returnerar textraden till.
BufferedReader br;
try {
InputStream input = assetManager.open(text_file);
br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
//bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(text_file)));
String line;
int i = 0;
while ( (line = br.readLine()) != null) {
stringBuffer[i] = line; // läs in rader från textfilen
i++;
}
br.close();
} catch (FileNotFoundException fnde) {
//fnde.printStackTrace();
System.out.println("filerna kunde inte hittas");
} catch (Exception e) {
e.printStackTrace();
}
splitString(stringBuffer, index);
}
private void splitString(String[] str, int index) {
int nCols = this.stringObjects.get(index)[0].length; // antal kolumner
for (int i = 0; i < str.length; i++) {
StringTokenizer st = new StringTokenizer(str[i]);
for (int j = 0; j < nCols; j++) {
this.stringObjects.get(index)[i][j] = st.nextToken();
}
}
}
since its 9 files that is to be loaded this read-method are called 9 times. Could this be the source to te memory leak?
Greatful for answer
EDIT: I choosed to show the whole class. Thanks again!!!
I think it's because of the String[] you are using to store read lines. Can you try it with a StringBuilder instead of String[] ?
// stringBuffer[i] = line;
stringBuilder.append(line);
I have to understand this code to create my own app(almost based on this function):
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0;
String ligne;
int j = 0;
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
s[0][j] = ligne;
else {
s[1][j] = ligne;
j++;
}
i++;
}
fIn.close();
ipsr.close();
return s;
}
catch (Exception e)
{}
I'm not understanding why the using of a 2D array? and with two rows ?(String[][] s = new String[2][i/2];)
here is the data that it will be stored in the file:
data = date + " : " + y + "L/100KM"+ " " + value1 + "L "+ value2 + "KM\n";
Necessary functions:
public void updatelv(Activity activity) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String fileName = getResources().getString(R.string.fileName);
fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
s = myIO.ReadFilePerLine(getApplicationContext(), fileDir+fileName);
ListView L = (ListView) findViewById(R.id.lv);
L.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, s[0]));
for (int i = 0; i< s[0].length; i++) {
Log.d("Saves",s[0][i]);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.histo);
context = getApplicationContext();
activity = this;
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
String fileName = getResources().getString(R.string.fileName);
fileDir = "" + preferences.getString("login", "") + "."+ preferences.getString("marque", "") + ".";
s = myIO.ReadFilePerLine(getApplicationContext(), fileDir + fileName);
updatelv(this);
ListView L = (ListView) findViewById(R.id.lv);
L.setTextFilterEnabled(true);
L.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String tmp = s[1][position];
if (tmp == null)
tmp = "Aucun fichier trouvé!";
Toast.makeText(getApplicationContext(), tmp, Toast.LENGTH_SHORT)
.show();
}
});
ReadFilePerLine function:
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0;
String ligne;
int j = 0;
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
s[0][j] = ligne;
else {
s[1][j] = ligne;
j++;
}
i++;
}
fIn.close();
ipsr.close();
return s;
}
catch (Exception e)
{
}
Thank you for you help.
The code is clearly reading from a file whose format consists of pairs of lines; it puts the first line of each pair in s[0][...] and the second line of each pair in s[1][...]. If your format doesn't have that peculiarity -- which it doesn't sound as if it does -- then you don't need to do that. Just make an ordinary 1-dimensional array of Strings.
It appears that what they are doing is breaking the file down into two lists (or String arrays, in this case), one which contains all the even-numbered lines, and one which contains all the odd-numbered lines. I'll comment up the code for you:
public static String[][] ReadFilePerLine(Context context, String nom) {
int i = 0;
try {
//open the specified input file and create a reader
FileInputStream fIn = context.openFileInput(nom);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
//get the total number of lines in the file, and allocate
//a buffer large enough to hold them all
i = getLineNumber(context, nom);
String[][] s = new String[2][i/2];
i = 0; //set the current line to 0
String ligne;
int j = 0; //set the section index to 0
//now read through the lines in the file, and place every
//even-numbered line in the first section ('s[0]'), and every
//odd-numbered line in the second section ('s[1]')
while ((ligne = b.readLine()) != null) {
if (i % 2 == 0)
//even-numbered line, it goes into the first section
s[0][j] = ligne;
else {
//odd-numbered line, it goes into the second section
s[1][j] = ligne;
j++; //increment the section index
}
i++; //increment the line count
}
//done, cleanup and return
fIn.close();
ipsr.close();
return s;
}
catch (Exception e) {
//should at least log an error here...
}
}
As to why they chose to use a String[][], I cannot say. Probably for convenience, since they want a single object that they can return from this function that contains both lists. Personally I would use a Map that has two List instances in it, but the String[][] works just as well and is probably marginally more efficient.
Judging from your example data it does not appear that you need to use this format. But if you want to use it, you need to structure your data so that the key is on one line, and its associated value is on the next, like:
date
2011-03-19
userName
someGuy
it seems to read from a file, split it into the two dimensional array (based on row count).
Why it does it? I have no idea why you'd want that. Check out the function that it returns s to and find out!