Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

FILE IO

Options
  • 29-03-2014 12:58pm
    #1
    Registered Users Posts: 72 ✭✭


    HI Folks - As part of my app i am going to read in a file(.csv which is a library of categories) and put them into my SQLite DB - so i set up a class called Categories_Read.java which when the user presses the 'Proceed' button on the main screen i want the program to read in these details and put them into the DB - i can read the file no problem in a .java file and print to the console, but in android it just doesn't seem to be working. I have tried putting a toast in as well as a log but cannot get anything - any advice thanks..

    my Categories_Read is the following: -
    package com.teamkp.wattless;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.StringWriter;
    import java.io.Writer;
    import android.util.Log;
    
    public class Categories_Read {
    	
    	static StringBuilder sbuilder;
    	static FileInputStream fStream;
        static BufferedReader input;
        static String categoriesFile = "";
        static File file = new File("C:\\Users\\DeeWilliam\\Desktop\\categories_json_csv_formatted.txt");
    	static FileInputStream fis;
    	
    	
     public static String readFromFile() {
    	 
    	 try{
    		input = new BufferedReader(new FileReader(file));
    		categoriesFile = input.readLine();
    		while(categoriesFile != null) {
    			categoriesFile = input.readLine();
    			Log.d("Reading From File", categoriesFile);
    		}
    		input.close();
    	 }catch(IOException e) {
    		 Log.d("Read Caught From File", categoriesFile);
    	 }
    	 return categoriesFile;
    	 	
    	 
     }
    }
    

    and my Launch_Screen where proceed button is as follows: -

    [code] package com.teamkp.wattless;


    import java.util.ArrayList;

    import com.teamkp.wattless.Data.DataBaseHandler;

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.database.sqlite.SQLiteDatabase;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.WindowManager;
    import android.view.inputmethod.InputMethodManager;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Launch_Screen extends Activity {

    DataBaseHandler dataBaseHandler;

    SQLiteDatabase db;

    Button launch;
    private Context context;


    //////////////////////////////////////////////////////////////////////
    // //
    // ON CREATE //
    // //
    //////////////////////////////////////////////////////////////////////

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch__main__screen);
    // Old Code

    //Call the Database Handler Constructor
    dataBaseHandler = new DataBaseHandler(this);

    // SQLiteDatabase db = dataBaseHandler.getWritableDatabase();

    // String[] s2 = {"teamKP123 Buildings", "1 on the Road to Nowhere",null, "Dublin 1", "Technology", "Software Developement"};

    // dataBaseHandler.insertDataSiteTable(db, s2);

    // //Toast.makeText(context, "After writing in launch: ", Toast.LENGTH_LONG).show();

    // dataBaseHandler.close();


    db = dataBaseHandler.getReadableDatabase();
    ArrayList<String> s = new ArrayList<String>();
    s = dataBaseHandler.getSiteNames(db);

    //Toast.makeText(context, "Reading Site Names: "+s, Toast.LENGTH_LONG).show();

    Log.i("dataBaseHandler","Reading Site Names"+s);
    dataBaseHandler.close();
    //Log.i("dataBaseHandler","Main 5");
    Toast.makeText(getApplicationContext(), "Reading Site Names: "+s, Toast.LENGTH_LONG).show();
    }


    //////////////////////////////////////////////////////////////////////
    // //
    // PROCEED BUTTON //
    // //
    //////////////////////////////////////////////////////////////////////

    public void proceedButton(View v) {
    Categories_Read read = new Categories_Read();
    Log.d("PROCEED BUTTON READ FROM FILE", Categories_Read.readFromFile());
    EditText et = (EditText) findViewById(R.id.EnterUsername);
    EditText et1 = (EditText) findViewById(R.id.EnterPassword);

    try{
    Intent intent = null;
    intent = new Intent(Launch_Screen.this, MySiteActivity.class);
    launch = (Button) findViewById(R.id.arrowButton_Proceed);
    startActivity(intent);

    }catch(Exception e){
    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
    }
    }
    // try{
    //
    // if ((et.getText().toString().equals(username))
    // && (et1.getText().toString().equals(password))) {
    // Toast.makeText(getApplicationContext(), "Welcome to Wattless", Toast.LENGTH_SHORT).show();
    //
    //
    // Intent intent = null;
    // intent = new Intent(Launch_Screen.this, MySiteActivity.class);
    // launch = (Button) findViewById(R.id.login_button);
    // startActivity(intent);
    //
    // }else{
    // Toast.makeText(getApplicationContext(), "You Entered the Incorrect Username, Please try again", Toast.LENGTH_SHORT).show();
    // }
    // }catch(Exception e){
    // Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
    // }
    // }



    //////////////////////////////////////////////////////////////////////
    // //
    // ON CREATE OPTIONS MENU //
    // //
    //////////////////////////////////////////////////////////////////////

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.launch__main__screen, menu);
    return true;

    }
    }

    [code]

    Thanks


Comments

  • Registered Users Posts: 2,345 ✭✭✭Kavrocks


    First things first in Android the file paths do not resemble what you have hardcoded.
    C:\\Users\\DeeWilliam\\Desktop\\categories_json_csv_formatted.txt
    

    My advice would be
    • Write your programs for Android, and not Windows or at least change what needs to be changed when porting
    • Google your problem
    • Reformat your post and remove the code you have commented out so its easier for somebody to read and possibly spot your error without having to go to a lot of trouble

    Help us to help you.


  • Registered Users Posts: 72 ✭✭shanard


    Kavrocks wrote: »
    First things first in Android the file paths do not resemble what you have hardcoded.
    C:\\Users\\DeeWilliam\\Desktop\\categories_json_csv_formatted.txt
    

    I have moved my file to assets folder and calling AssetManager - this ok??

    Even if i forget the original code in java class and try reading it in from assets folder using InputStream is = am.open("fileName.txt"); - this still does not work.

    I have been messing about with it for 3-4 hours now and cannot find any clarification through Google to find out even correct syntax - as i am sure i have syntax correct.....

    Here is the method to readFile i have placed in my Launch_Activity.java screen instead of having separate class as per my first query....

    [code]
    public void readFile() {
    try {
    InputStream is = am.open("categories_json_csv_formatted.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = "";
    line = br.readLine();
    while(line !=null) {
    line=br.readLine();
    }br.close();
    } catch (IOException e) {
    Log.d("CAUGHT IN READFILE", "Test Catch");
    e.printStackTrace();
    }


    }
    [code]

    Thanks


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    Not wanting to be obvious here, but what error messages are you getting?


  • Registered Users Posts: 72 ✭✭shanard


    HI,

    I have the file reading in ok for categories but for the other txt file (types_csv.txt) where there are comma separated values and "" on some lines, - there should be 13 fields which i need to split - i have included below my code to split this by ',' but just doesnt seem to be working, and i have included a sample of couple of lines from the types_csv.txt file if someone can assist me in splitting this by ',' and "" where applicable.

    Sample File -

    45,4,LED GU10 Cluster 3w,3.0,1,LED,,3.0,0,,False,,
    46,4,LED GU10 Cluster 4w,4.0,1,LED,,4.0,0,,False,,
    47,4,LED GU10 Cluster 5w,5.0,1,LED,,5.0,0,,False,,
    48,5,PLE-D 42w,42.0,1,"Fluorescent - Compact, Integral Ballast",,42.0,0,,False,,
    49,5,PLE-C 5w,5.0,1,"Fluorescent - Compact, Integral Ballast",,5.0,0,,False,200,
    50,5,PLE-C 9w,9.0,1,"Fluorescent - Compact, Integral Ballast",,9.0,0,,False,425,

    public void readFromAssets_Library() {
    		Log.d("TESTING IF READING LIBRARY TYPES ", "TYPES");
    		String libraryFile;
    		String csvSplit;
    		byte[] buffer = null;
    		InputStream is;
    	try {
    		is = getResources().openRawResource(R.raw.types_csv);
    		int size = is.available(); //size of the file in bytes
    		buffer = new byte[size]; //declare the size of the byte array with size of the file
    		is.read(buffer); //read file
    	
    		
    		is.close(); //close file
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    		// Store text file data in the string variable
    		String str_data = new String(buffer);
    		String[] library = str_data.split("\\u000A");
    		
    		for(String s: library){
    			Log.d("READING LIBRARIES ", s);
    			String[] libTypes = s.split(",");
    			for(String str : libTypes){
    				Log.d("READING LIBRARIES ", str);
    			}
    		}
    		
    	}
    		
    

    Thanks


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    shanard wrote: »
    I have the file reading in ok for categories but for the other txt file (types_csv.txt) where there are comma separated values and "" on some lines, - there should be 13 fields which i need to split - i have included below my code to split this by ',' but just doesnt seem to be working, and i have included a sample of couple of lines from the types_csv.txt file if someone can assist me in splitting this by ',' and "" where applicable.
    Could you be more specific? Error messages? Description of how it's failing?

    All you're doing at the moment is posting your code and, with very little information, asking us to debug it all for you, and frankly we all have better things to do.


  • Advertisement
  • Registered Users Posts: 72 ✭✭shanard


    There are no errors - just the out put is not what i am looking for - some lines have "" in them as well as the commas, and i am looking to split the line by (,) and ("") - just seem to get it working???

    Thanks


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    shanard wrote: »
    There are no errors - just the out put is not what i am looking for - some lines have "" in them as well as the commas, and i am looking to split the line by (,) and ("") - just seem to get it working???
    OK. Clearer now. Thanks.

    Your problem appears your approach is flawed in that you can't really just do a split with your file as some will contain quotes and some not.

    First, I would check if there is a quote character as you go through each line. If not, you can do a simple split based upon the comma separator. Otherwise, you need to parse through it more carefully.

    One approach is to run through the line character by character, constructing a temporary Stringbuffer as you go along until you hit either a comma or quote and using a boolean that you can toggle so that you know when to ignore commas, when reading inside quotes.

    As an additional tip, I find that with things like this, it's easier to write them as a Java console application, as output and thus debugging is faster than having to do so through an Android app.

    The logic would be something like this:
    1. Read the next character.
    2. If '"' and your ignore_comma boolean is false (opening quote), toggle ignore_comma to true. Ignore the character.
    3. Else if '"' and your ignore_comma boolean is true (closing quote), toggle ignore_comma to false. Ignore the character.
    4. Else if ',' and ignore_comma boolean is true (comma within quotes), append the character to your temporary Stringbuffer.
    5. Else if ',' and ignore_comma boolean is false (comma delineator), append to your temporary Stringbuffer to your line array and clear the Stringbuffer. Ignore the character.
    6. Else append the character to your temporary Stringbuffer (all other content).
    7. If all the characters have been read, read the next line.
    8. Go to step 1.
    Personally I would do this while reading the file, line by line - read line, parse, insert parsed array data into database - rather than reading what could be a very large file into memory first, as you appear to be doing.


  • Registered Users Posts: 72 ✭✭shanard


    Thanks - We got it by inserting a | where the commas were and split it using the unicode value for a | and it seems to have worked.

    Thanks for your help!!


Advertisement