我正在开发一个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.
请在我出错的地方帮助我。
提前多多感谢。
答案 0 :(得分:1)
请告诉我们,您放置.csv文件的位置。你的文件阅读器在那里找不到它。
如果你想用apk传送文件并将其存储在/ assets /文件夹中,你可以从context.getAssets().open(fileName)
获得一个inputStream - 你可以通过setter将你的输入流提供给你的db-helper类/ constructor或(如果尚未完成)为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());
如果你看到this tutorial的DbHelper,你会注意到他们已经拥有了上下文,因为他们必须在他们的构造函数中使用super(Context context,...)调用。如果您的DbHelper已经有了这个,那就足以将它存储到DbHelper实现的成员中,如上所述
<强> EDIT2 强>
你已经使用了这样的构造函数,所以你只需要在本地引用构造函数,如上所述。