-1

I am developing an android app, In the app I have to display data from .csv file in a spinner. While I am trying to run an app, the sql query is getting executed(as per the logs) but I am not able to see any table in the database and in the logs its coming that its not able to find the file. I am going to past the DbHelper.java and the class where I am calling the DbHelper. DbHelper.java

  private static final String filepath = "CancerType.csv";

  public void onCreate(SQLiteDatabase db) {
        //String sql1=String.format("create table %s(%s int primary key,%s TEXT,%s      TEXT,%s TEXT,%s int,%s int)", table1,C_ID,Title,Description,Tag,Is_Active,Is_Default);
    String sql2="CREATE TABLE "+ table2 + "(" + C_ID + " INTEGER PRIMARY KEY,"+ Title + " TEXT,"+ Description +" TEXT,"+ Tag +" TEXT,"+ Is_Active +" TEXT,"+ Is_Default +" TEXT)";
    //String sql3=String.format("create table %s(%s int primary key,%s TEXT,%s TEXT,%s TEXT,%s int,%s int)", table3,C_ID,Title,Description,Tag,Is_Active,Is_Default);


    db.execSQL(sql2);
    Log.d(TAG,"onCreate sql: "+sql2);
    //db.execSQL(sql3);



    BufferedReader br = null;   

    ArrayList<String> list=new ArrayList<String>();


    try {
         br = new BufferedReader(new FileReader(filepath));
        while ((line = br.readLine()) != null)
        {
            list.add(line);


        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    insertList(list,db);// call function to process the list and insert into the datbase
}

public void insertList(ArrayList<String> list,SQLiteDatabase db)
{

    try
    {
        db.beginTransaction();

    Iterator<String> it=list.iterator();
    while(it.hasNext())
    {
        String temp=it.next();
        String[] insertValues=temp.split(",");

        ContentValues values=new ContentValues();
        values.put(C_ID, insertValues[0]);
        values.put(Title, insertValues[1]);
        values.put(Description, insertValues[2]);
        values.put(Tag, insertValues[3]);
        values.put(Is_Active, insertValues[4]);
        values.put(Is_Default, insertValues[5]);

        db.insert(table2, null, values);

    }
    db.setTransactionSuccessful();
    }catch (SQLException e) {
        System.out.println("Exception occured");
    } finally {
          db.endTransaction();
        }
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("drop table if exists "+ table2);
    Log.d(TAG,"onUpgrade dropped table");
    this.onCreate(db);
}

public List<String> getAllEntries()
{
    List<String> entries = new ArrayList<String>();

    //Select Query
    String selectQuery="SELECT Title FROM " + table2;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    //Looping through all the entries
    if(cursor.moveToFirst())
    {
        do {
            entries.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }

    //closing connections
    cursor.close();
    db.close();

    //returning entries
    return entries;
}


  }

SpinnerType.java

  public class SpinnerType extends Activity {
SQLiteDatabase db;
DbHelper DbHelper;
Spinner spinner2;

 @SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_spinner_type);

    spinner2 = (Spinner) findViewById(R.id.spinner1);


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Show the Up button in the action bar.
        getActionBar().setDisplayHomeAsUpEnabled(true);

    }
       loadSpinnerData();


}

 /**
     * Function to load the spinner data from SQLite database
     * */

public void loadSpinnerData() 
 {
     DbHelper db=new DbHelper(getApplicationContext());

    // Spinner Drop down elements
     List<String> enteries = db.getAllEntries();

    // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, enteries);

        dataAdapter
        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner
        spinner2.setAdapter(dataAdapter);
 }

  }

I am also going to paste the logs...

  07-08 22:05:06.326: D/DbHelper(1142): onUpgrade dropped table
  07-08 22:05:06.346: D/DbHelper(1142): onCreate sql: CREATE TABLE IuCancerType(_id      INTEGER PRIMARY KEY,Title TEXT,Descripton TEXT,Tag TEXT,IsActive TEXT,IsDefault TEXT)
  07-08 22:05:06.366: W/System.err(1142): java.io.FileNotFoundException: /CancerType.csv: open failed: ENOENT (No such file or directory)
  07-08 22:05:06.366: W/System.err(1142):   at libcore.io.IoBridge.open(IoBridge.java:416)
  07-08 22:05:06.386: W/System.err(1142):   at java.io.FileInputStream.<init>(FileInputStream.java:78)
  07-08 22:05:06.396: W/System.err(1142):   at java.io.FileInputStream.<init>(FileInputStream.java:105)
  07-08 22:05:06.416: W/System.err(1142):   at java.io.FileReader.<init>(FileReader.java:66)
  07-08 22:05:06.416: W/System.err(1142):   at com.example.cancerresources.DbHelper.onCreate(DbHelper.java:70)
  07-08 22:05:06.436: W/System.err(1142):   at com.example.cancerresources.DbHelper.onUpgrade(DbHelper.java:127)
  07-08 22:05:06.436: W/System.err(1142):   at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
  07-08 22:05:06.436: W/System.err(1142):   at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
  07-08 22:05:06.445: W/System.err(1142):   at com.example.cancerresources.DbHelper.getAllEntries(DbHelper.java:137)
  07-08 22:05:06.445: W/System.err(1142):   at com.example.cancerresources.SpinnerType.loadSpinnerData(SpinnerType.java:75)
  07-08 22:05:06.465: W/System.err(1142):   at com.example.cancerresources.SpinnerType.onCreate(SpinnerType.java:36)
  07-08 22:05:06.465: W/System.err(1142):   at android.app.Activity.performCreate(Activity.java:5104)
   07-08 22:05:06.476: W/System.err(1142):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
  07-08 22:05:06.486: W/System.err(1142):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
  07-08 22:05:06.496: W/System.err(1142):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
  07-08 22:05:06.496: W/System.err(1142):   at android.app.ActivityThread.access$600(ActivityThread.java:141)
  07-08 22:05:06.515: W/System.err(1142):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
   07-08 22:05:06.515: W/System.err(1142):  at android.os.Handler.dispatchMessage(Handler.java:99)
  07-08 22:05:06.536: W/System.err(1142):   at android.os.Looper.loop(Looper.java:137)
 07-08 22:05:06.546: W/System.err(1142):    at android.app.ActivityThread.main(ActivityThread.java:5041)
  07-08 22:05:06.556: W/System.err(1142):   at java.lang.reflect.Method.invokeNative(Native Method)
 07-08 22:05:06.556: W/System.err(1142):    at java.lang.reflect.Method.invoke(Method.java:511)
  07-08 22:05:06.575: W/System.err(1142):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 07-08 22:05:06.575: W/System.err(1142):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
 07-08 22:05:06.605: W/System.err(1142):    at dalvik.system.NativeStart.main(Native Method)
 07-08 22:05:06.605: W/System.err(1142): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
07-08 22:05:06.645: W/System.err(1142):     at libcore.io.Posix.open(Native Method)
07-08 22:05:06.666: W/System.err(1142):     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
07-08 22:05:06.666: W/System.err(1142):     at libcore.io.IoBridge.open(IoBridge.java:400)
07-08 22:05:06.685: W/System.err(1142):     ... 24 more
07-08 22:05:09.845: D/dalvikvm(1142): GC_FOR_ALLOC freed 51K, 5% free 4254K/4468K, paused 28ms, total 34ms
07-08 22:05:09.855: I/dalvikvm-heap(1142): Grow heap (frag case) to 5.340MB for 1127536-byte allocation
07-08 22:05:09.915: D/dalvikvm(1142): GC_FOR_ALLOC freed 1K, 4% free 5353K/5572K, paused 53ms, total 53ms
07-08 22:05:09.965: D/dalvikvm(1142): GC_CONCURRENT freed 3K, 4% free 5356K/5572K, paused 4ms+19ms, total 59ms
07-08 22:05:11.096: W/InputEventReceiver(1142): Attempted to finish an input event but the input event receiver has already been disposed.

Please help me where I am going wrong.

Thanks a lot in advance.

user1495220
  • 111
  • 1
  • 2
  • 15
  • a CSV file is not a database... are you sure that's what you want to be using? – Codeman Jul 08 '13 at 22:55
  • @Pheonixblade9 I have a data in .csv file which I need to store in the database. Can you suggest a better way? – user1495220 Jul 09 '13 at 01:13
  • @user1495220 it's not best practice (since you have to parse your .csv into the db on first start-up which consumes time) but it's quite ok, unless your .csv has multiple 100 kilobytes in size. if the size of the .csv is to large or you notice any performance issues from parsing, you can have a look at [this question](http://stackoverflow.com/questions/513084/how-to-ship-an-android-application-with-a-database), up to then you should be fine with the csv – Christian R. Jul 09 '13 at 01:41

1 Answers1

1

tell us please, where you put your .csv file. your file reader can't find it there.

if you want to deliver the file with your apk and have stored it in the /assets/ folder, you can get an inputStream from context.getAssets().open(fileName) - you can either give your inputstream to your db-helper class via setter/constructor or (if not done already) give your dbHelper a reference to your activity.

if you downloaded the file during runtime and saved it anywhere on the phone, you should have file object and can use that, for your new fileReader(File file)

Edit

to clearify the question from the comment: your DbHelper needs a reference to the activity. therefore you could do something like (if you don't have the context already).

private Context context;
//non-default constructor with the callers context
public DbHelper(Context context) {
    this.context = context;
}
// .... create your br like this:
 br = new BufferedReader(this.context.getAssets().open(filePath));

and if you instantiate your DbHelper as you already do

DbHelper helper = new DbHelper(getApplicationContext());

if you see this tutorial for a DbHelper, you'll notice that they already have the context, since they have to use the super(Context context, ...) call inside their constructor. if your DbHelper has this already, it's enough to store it into a member of your DbHelper implementation like above

edit2

you already use a constructor like this, so you only have to reference the constructor locally like written above.

Christian R.
  • 1,528
  • 9
  • 16
  • I dnt know where to keep the .csv file(kept it at the wrong place), now as per your suggestion I have moved it to the assets folder. I knind of dnt get what do you mean by ( you can either give your inputstream to your db-helper class via setter/constructor or (if not done already) give your dbHelper a reference to your activity.)Please help me in solving this. – user1495220 Jul 09 '13 at 01:16
  • you need a context (like your activity) to get the assetManager with getAssets(). since you want to read the file outside of an activity (inside your DbHelper class), you have to add the Activity to the DbHelper. at best, you can add a parameter to your constructor. i ll edit this into my answer. – Christian R. Jul 09 '13 at 01:21
  • Thanks a lot for your reply. Can you please write a little bit of code for this,so that I will have a better picture. – user1495220 Jul 09 '13 at 01:28
  • ah, didn't notice, you already use your DbHelper with the constructor `DbHelper db=new DbHelper(getApplicationContext())`, then it's no problem to do, what's written above – Christian R. Jul 09 '13 at 01:47
  • Thank you so much it worked. I am getting the data in the spinner.:) – user1495220 Jul 09 '13 at 01:50
  • no problem, don't forget to mark the question as answered ;-) – Christian R. Jul 09 '13 at 01:55