-1

我正在开发一个 android 应用程序,在该应用程序中,我必须在微调器中显示来自 .csv 文件的数据。当我尝试运行应用程序时,正在执行 sql 查询(根据日志),但我无法在数据库中看到任何表,并且在日志中它无法找到文件。我将通过 DbHelper.java 和我调用 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);
 }

  }

我还要贴日志...

  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.

请帮助我哪里出错了。

提前非常感谢。

4

1 回答 1

1

请告诉我们,您将 .csv 文件放在哪里。您的文件阅读器在那里找不到它。

如果您想将文件与您的 apk 一起交付并将其存储在 /assets/ 文件夹中,您可以从中获取 inputStream context.getAssets().open(fileName)- 您可以通过 setter/constructor 将输入流提供给您的 db-helper 类,或者(如果尚未完成) 为您的 dbHelper 提供您的活动的参考。

如果您在运行时下载文件并将其保存在手机上的任何位置,您应该有文件对象并且可以使用它来为您的new fileReader(File file)

编辑

从评论中清除问题:您的 DbHelper 需要对活动的引用。因此你可以做类似的事情(如果你还没有上下文)。

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));

如果你像你已经做的那样实例化你的 DbHelper

DbHelper helper = new DbHelper(getApplicationContext());

如果您看到DbHelper 的本教程,您会注意到它们已经拥有上下文,因为它们必须在其构造函数中使用 super(Context context, ...) 调用。如果您的 DbHelper 已经有了这个,那么将它存储到您的 DbHelper 实现的成员中就足够了,就像上面一样

编辑2

你已经使用了这样的构造函数,所以你只需要像上面写的那样在本地引用构造函数。

于 2013-07-08T23:06:09.363 回答