File won't read into multiple array positions - android

I'm trying to store each line from a file into an arraylist and then combine two arraylists into one. Currently, when I try this, all the different lines are being stored in one line. I want it to say something like User : Score . However, right now it is showing up like UseruserUsernamePerson : Score. (many different names and only one score). Can anyone see where I'm going wrong here? Also, pardon my poor naming practice. My array lists used to be Vectors, but I changed them into ArrayLists and forgot to change their titles.
public class DisplayScores extends ListActivity{
private ArrayList<String> scoreVector = new ArrayList<String>();
private ArrayList<String> userVector = new ArrayList<String>();
private ArrayList<String> comboVector = new ArrayList<String>();
private int c = 0;
File root = Environment.getExternalStorageDirectory();
File scores = new File(root, "scores.txt");
File users = new File(root, "names.txt");
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String line = null;
try {
FileReader scoresFileReader = new FileReader(scores);
BufferedReader scoresReader = new BufferedReader(scoresFileReader);
while ((line = scoresReader.readLine())!= null)
{
scoreVector.add(line);
}
scoresFileReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String userLine = null;
try{
FileReader userFileReader = new FileReader(users);
BufferedReader userReader = new BufferedReader(userFileReader);
while((userLine = userReader.readLine())!= null)
{
userVector.add(userLine);
}
userReader.close();
} catch (IOException e){
e.printStackTrace();
}
for(String s : scoreVector)
{
comboVector.add(userVector.get(c) + ": " + s);
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, comboVector));
}
}

from the code it seems that the value of c is not incrementing..
c is always 0
for(String s : scoreVector)
{
comboVector.add(userVector.get(c) + ": " + s);
}

Related

Android notifyDataSetChanged not refreshing the items after removing

So I am trying to remove the itempending however it does not remove it from the listview immediately on click. I have to go back and come back to this screen and it will be removed. However my other listview on the same screen was updated immediately (The submitted profile method). I tried to create a method that does the same function I need and call it in before the notifyDataSetChanged but nothing works. Any advise on why my notifyDataSetChanged is not working would be appreciated thanks.
ArrayAdapter<String> adapterSubmit, adapterPending;
ArrayList<String> itemsSubmit, itemsPending;
ListView lstSubmitPro, lstPendingPro;
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CaptureLogs";
Button btnSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_pro_list);
btnSubmit = (Button) findViewById(R.id.btnTest);
lstSubmitPro = (ListView) findViewById(R.id.lstSubmitPro);
lstPendingPro = (ListView) findViewById(R.id.lstPendingPro);
itemsSubmit = new ArrayList<String>();
adapterSubmit = new ArrayAdapter(this, R.layout.prolist, R.id.tvRows, itemsSubmit);
lstSubmitPro.setAdapter(adapterSubmit);
itemsPending = new ArrayList<String>();
adapterPending = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, itemsPending);
lstPendingPro.setAdapter(adapterPending);
lstPendingPro.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
pendingSubmitProfile();
SubmittedProfile();
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray sp = lstPendingPro.getCheckedItemPositions();
if (sp!= null) {
for (int i = 0; i < sp.size(); i++) {
if (sp.valueAt(i) == true) {
SubmittedProfile();
adapterSubmit.notifyDataSetChanged();
itemsPending.remove(sp.get(i));
adapterPending.notifyDataSetChanged();
Toast.makeText(ProList.this, "Your profiles have been submitted successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ProList.this, "Please choose a profile to be submitted.", Toast.LENGTH_LONG).show();
}
}
}
}
});
public void pendingSubmitProfile()
{
File dir = new File(path);
File[] files = dir.listFiles();
for (File f : files) {
if (f.isFile()) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(f));
String lineToRead = "--PENDING SUBMIT--";
String CurrentLine;
while ((CurrentLine = inputStream.readLine()) != null) {
if (CurrentLine.equals(lineToRead)) {
String filen = f.getName().substring(0, f.getName().lastIndexOf("."));
itemsPending.add(filen);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void SubmittedProfile()
{
File dir = new File(path);
File[] files = dir.listFiles();
for (File f : files) {
if (f.isFile()) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader(f));
String lineToRead = "--SUBMITTED--";
String CurrentLine;
while ((CurrentLine = inputStream.readLine()) != null) {
if (CurrentLine.equals(lineToRead)) {
String filen = f.getName().substring(0, f.getName().lastIndexOf("."));
itemsSubmit.add(filen);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
LOG
Before, 2 items but 1 checked
05-02 08:00:02.409 4293-4293/com.example.irambi.irmobilewizard D/returned value:: 2 1 2
After, 2 items but 1 checked
05-02 08:00:03.726 4293-4293/com.example.irambi.irmobilewizard D/returned value:: 0 1 0
This is for 1 item and 1 checked. I cannot tell if this is before or after since theres only 1 printed on logcat. This will crash and error is as follows
05-02 08:03:35.345 4293-4293/com.example.irambi.irmobilewizard D/returned value:: 1 1 1
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Before, 2 items but 2 checked
05-02 08:07:56.378 4596-4596/com.example.irambi.irmobilewizard D/returned value:: 2 2 2
After, 2 items but 2 checked - This will crash
05-02 08:07:57.671 4596-4596/com.example.irambi.irmobilewizard D/returned value:: 0 2 0
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
All the testing are done using
itemsPending.remove(sp.keyAt(i));
adapterPending.remove(adapterPending.getItem(sp.keyAt(i)));
Log based on:
Log.d("returned value:", itemsPending.size() + " " + sp.size() + " " + adapterPending.getCount());
Try this one
itemsPending.remove(sp.keyAt(i));
adapterPending.remove(adapterPending.getItem(sp.keyAt(i)));
adapterPending.notifyDataSetChanged();
EDIT:
So basically the switching of list data is working fine. What's messing the code is his file writing. I resolve it this way.
First is a create a function that would update my Pending Files to submitted.
public void submitPendingProfile(String filename){
try {
BufferedReader file = new BufferedReader(new FileReader(path + "/" + filename+".txt"));
String line;
StringBuffer inputBuffer = new StringBuffer();
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
String inputStr = inputBuffer.toString();
file.close();
inputStr = inputStr.replace("--PENDING SUBMIT--", "--SUBMITTED--");
FileOutputStream fileOut = new FileOutputStream(path + "/" + filename+".txt");
fileOut.write(inputStr.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Then i refactor the loop for simplier process. Like removing the line SubmittedProfile(); that keeps reading all text files if conditions is true. That is a lot of process. Here's how instead.
for(int i = lstPendingPro.getAdapter().getCount() - 1 ; i >= 0; i--) {
if (sp.get(i)) {
//So when file is submitted, i update the files status using the above function.
submitPendingProfile(itemsPending.get(i));
//To avoid rereading of files, just add the item before removing it to the pending list
itemsSubmit.add(itemsPending.get(i));
adapterSubmit.notifyDataSetChanged();
itemsPending.remove(sp.keyAt(i));
adapterPending.notifyDataSetChanged();
Toast.makeText(ProList.this, "Your profiles have been submitted successfully.", Toast.LENGTH_LONG).show();
}
}
Did You tried changing your code to this order
btnSubmit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v){
SparseBooleanArray sp = lstPendingPro.getCheckedItemPositions();
if (sp != null) {
for (int i = 0; i < sp.size(); i++) {
if (sp.valueAt(i) == true) {
SubmittedProfile();
itemsPending.remove(sp.get(i));
Toast.makeText(ProList.this, "Your profiles have been submitted successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(ProList.this, "Please choose a profile to be submitted.", Toast.LENGTH_LONG).show();
}
}
}
adapterSubmit.notifyDataSetChanged();
adapterPending.notifyDataSetChanged();
}
});
Try this code..
itemsPending.remove(itemsPending.indexOf(sp.get(i)));
adapterPending.notifyDataSetChanged();
itemsPending.remove(sp.get(i));
adapterPending.notifyDataSetChanged();
listview.invalidate();
Try above code might be it will help you.

How to read a CSV file?

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

FileNotFoundException in Android but File is setup properly, what is wrong?

I am having a problem. When I implemented the following file in this class which when run independently seems to show the properly being read it works and saves the data into the ArrayLists. This the code I have for that class:
MachineLearningInstance.java
public class MachineLearningInstance {
/*
* Setup Arraylist of Iris Items which will be the size of the .data file
*/
private ArrayList<Iris> irisData = new ArrayList<Iris>();
private ArrayList<Iris> trainingArray = new ArrayList<Iris>();
private Context context;
/*
* These are values for the NeuralNetwork Constructor
*/
private final String comma = ",";
private final String irisSetosa = "Iris-setosa";
private final String irisVersicolor = "Iris-versicolor";
private final String irisVirginica = "Iris-virginica";
public MachineLearningInstance(File f, Context context) {
this.context = context;
try {
int noOfRowsInData = 0;
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
try {
lnr.skip(Long.MAX_VALUE);
noOfRowsInData = lnr.getLineNumber();
//System.out.println(noOfRowsInData);
lnr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
irisData = new ArrayList<Iris>();
// While there is another line in inFile.
Scanner inFile = new Scanner(f);
for (int i = 0; i < noOfRowsInData - 1; i++) {
if (inFile.hasNextLine()) {
// Store line into String
String line = inFile.nextLine();
// Partition values into separate elements in array
String[] numbers = line.split(comma);
// Grab values from that line and store it into a Iris ArrayList Item
irisData.add(i, new Iris(i, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]));
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (irisData == null) {
Toast.makeText(context, "IRIS DATA IS NULL!", Toast.LENGTH_LONG);
}
for (int i = 0; i < irisData.size(); i++) {
Toast.makeText(context, irisData.get(i).getId(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, irisData.get(i).getIrisClassName(), Toast.LENGTH_SHORT).show();
} // Used to check values
//sortData();
}
/*
Initialize method to grab the 2-D array of the Iris items
*/
public ArrayList<Iris> getTestData() {
return irisData;
}
public ArrayList<Iris> getTrainingData() {
return trainingArray;
}
public ArrayList<Iris> sortData() {
trainingArray.addAll(irisData.subList(0, 100));
return trainingArray;
}
}
When I implement the following code into this fragment, I get a NullPointerException which I think is being caused by a FileNotFoundException because I think the file is not being read properly when implemented through a fragment. Here is the code I have for the Fragment:
public class PredictFragment extends Fragment {
private ListView mListView;
private ArrayList<Iris> irisArrayList;
private ArrayList<Iris> trainingSet = new ArrayList<Iris>();
private ArrayList<Iris> testSet = new ArrayList<Iris>();
private MachineLearningInstance machineLearningInstance;
private IrisAdapter irisAdapter;
private FileOutputStream rawFile;
private File rawFileOutput;
/*
MachineLearningInstance to grab data from .data file and sort it into partition arraylists
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.predict_listview, container, false);
rawFileOutput = new File("C:\\iris\\iris.data");
machineLearningInstance = new MachineLearningInstance(rawFileOutput, getActivity());
trainingSet = machineLearningInstance.getTrainingData();
testSet = machineLearningInstance.getTestData();
irisAdapter = new IrisAdapter(getActivity(), testSet);
mListView = (ListView) view.findViewById(R.id.listView);
mListView.setAdapter(irisAdapter);
return view;
}
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.irisclassification, PID: 1675
java.lang.NullPointerException
at >com.irisclassification.PredictFragment.onCreateView(PredictFragment.java:59)
at android.app.Fragment.performCreateView(Fragment.java:1700)
EDIT:
So would using a fileoutstream and then casting it to a file object be the best way to go about this?
I went ahead and bundles the .data file into the raw assets folder in the resources directory, would this be the correct approach to go about getting access to the .data file on the android device?
public FileOutputStream createFile() {
try {
InputStream inputStream = getActivity().getResources().openRawResource(R.raw.iris);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int size = 0;
// Read the entire resource into a local byte buffer
byte[] buffer = new byte[1024];
while ((size = inputStream.read(buffer, 0, 1024)) >= 0) {
outputStream.write(buffer, 0, size);
}
inputStream.close();
buffer = outputStream.toByteArray();
rawFile = new FileOutputStream("iris.data");
rawFile.write(buffer);
rawFile.close();
} catch (IOException e) {
e.printStackTrace();
}
return rawFile;
}
C:\iris\iris.data is not existent in Android. You have to change the path to a file that exists on your device (Reading files may need an additional permission!) or bundle it and use AssetManager to retrieve it at runtime (like Nobu Games wrote).

Calling the values out from CSV file for aGraphEngine (Android)

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'm not understanding the following code

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!

Categories

Resources