csv 文件 -> SQLite 表,并显示列表视图



我想将"*.csv"文件(在android资产文件夹中)转换为SQLite表。

然后,使用listview显示表。(:读取csv-使用->sqlite表-使用->显示列表视图)

但都是错误。

请帮忙。

  • 对不起,我的英语不清楚
  • 我没有任何生根装置。总是在我的真实设备(而不是测试设备或虚拟机)中运行

代码中仍然存在错误。并且未创建"test.db"文件。

logcat:Nullpointerexception,无法打开文件进行读取。。。等


public class FirstActivity extends Activity {
    public static DBHelper mDBManager;
    private SQLiteDatabase db;
    Cursor c;
    ListView list = (ListView) findViewById(R.id.listView1);
    String arrname[] = null;
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mtname);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first);
        mDBManager = new DBHelper(this);  
        db = mDBManager.getWritableDatabase();
        db = mDBManager.getReadableDatabase();
        Log.d("FirstActivity:onCreate", "oncreate");
        displayList();
    }
    private void displayList() {
        // TODO Auto-generated method stub
        c = mDBManager.SortAllRows();
        Log.d("FirstActivity:displayList", "displayList");
        int i = 0;
        if (c.moveToFirst()) {        
            do {
                arrname[i] = c.getString(c.getColumnIndexOrThrow("_name"));
            } while (c.moveToNext());
        }
        list.setAdapter(adapter);
        c.close();
        db.close();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.first, menu);
        return true;
    }
}

public class DBHelper extends SQLiteOpenHelper {
    private static String DB_PATH = "/mnt/sdcard/";
    private static final String TABLE_NAME = "test";
    private DBHelper dbHelper;
    private SQLiteDatabase db;
    private String fileName = "test.csv"; // "file:///android_asset/test.csv"; //"/mnt/sdcard/test.csv";
    private Context mcontext;
    public DBHelper(Context context)
    {
        super(context, DB_PATH + "test.db", null, 1);
        mcontext = context;
        // TODO Auto-generated constructor stub
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + TABLE_NAME + "(_index INTEGER PRIMARY KEY AUTOINCREMENT, _name TEXT, _ad TEXT, _ca TEXT, _sp TEXT);");
        AssetManager am = mcontext.getAssets();
        InputStream is = null;
        try {
            is = am.open(fileName);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("DBHelper:onCreate", "csv file open");
        }
        BufferedReader buffer = null;
        buffer = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

/** I tried this way. but there was all error(Including the above way). NullPointerException **
* for '*. csv' file to change the table of sqlite. (csv file->sqlite table)
        //InputStream in = mcontext.getAssets().open(fileName);
        //BufferReader buffer = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        //AssetManager am = mcontext.getAssets();
        //BufferedReader buffer = new BufferedReader(new InputStreamReader(am.open(fileName), "UTF-8"));
        //FileReader fr = new FileReader(new File("file:///android_asset/","test.csv"));
        //BufferedReader buffer = new BufferedReader(fr);
        //AssetFileDescriptor descriptor = am.openFd(fileName);
        //FileReader file = new FileReader(descriptor.getFileDescriptor());
        //FileReader file = new FileReader(fileName);
        //BufferedReader buffer = new BufferedReader(file);
*/
        String line = "";
        String columns = "_index, _name, _ad, _ca, _sp";
        String str1 = "INSERT INTO " + TABLE_NAME + " (" + columns + ") values(";
        String str2 = ");";
        db.beginTransaction();
        try {
            while ((line = buffer.readLine()) != null) {
                StringBuilder sb = new StringBuilder(str1);
                String[] str = line.split(",");
                sb.append("'" + str[0] + "',");
                sb.append(str[1] + "',");
                sb.append(str[2] + "',");
                sb.append(str[3] + "'");
                sb.append(str[4] + "'");
                sb.append(str2);
                db.execSQL(sb.toString());
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Log.d("DBHelper:onCreate","DB CREATE");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.w("DBHelper:onUpgrade", "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
    public Cursor SortAllRows() {
        return db.query(TABLE_NAME, new String[] { "_index", "_name", "_ad", "_ca", "_sp" }, null, null, null, null, null, "_name" + " ASC");
    }
    public void close() {
        Log.d("DBHelper:close","DBhelper close");
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}

11-27 15:13:15.893: E/(19898): Can't open file for reading
11-27 15:13:15.893: E/(19898): Can't open file for reading
11-27 15:13:15.973: D/memalloc(19898): ion: Mapped buffer base:0x4c3ab000 size:1536000 offset:0 fd:78
11-27 15:13:16.024: I/Adreno200-EGLSUB(19898): <ConfigWindowMatch:2081>: Format RGBA_8888.
11-27 15:13:16.024: D/memalloc(19898): ion: Mapped buffer base:0x4c728000 size:1536000 offset:0 fd:81
11-27 15:13:16.024: D/memalloc(19898): ion: Unmapping buffer  base:0x4be87000 size:1536000
11-27 15:13:16.024: D/memalloc(19898): ion: Unmapping buffer  base:0x4c3ab000 size:1536000
11-27 15:13:16.034: D/memalloc(19898): ion: Mapped buffer base:0x4be87000 size:1536000 offset:0 fd:74
11-27 15:13:16.704: D/memalloc(19898): ion: Mapped buffer base:0x4c3ab000 size:1536000 offset:0 fd:78
11-27 15:13:18.606: I/Adreno200-EGLSUB(19898): <ConfigWindowMatch:2081>: Format RGBA_8888.
11-27 15:13:18.606: D/memalloc(19898): ion: Mapped buffer base:0x4c89f000 size:1536000 offset:0 fd:87
11-27 15:13:18.636: D/memalloc(19898): ion: Mapped buffer base:0x4ca16000 size:1536000 offset:0 fd:90
11-27 15:13:18.646: D/memalloc(19898): ion: Unmapping buffer  base:0x4c728000 size:1536000
11-27 15:13:18.646: D/memalloc(19898): ion: Unmapping buffer  base:0x4be87000 size:1536000
11-27 15:13:18.646: D/memalloc(19898): ion: Unmapping buffer  base:0x4c3ab000 size:1536000
11-27 15:13:19.837: D/memalloc(19898): ion: Mapped buffer base:0x4be87000 size:1536000 offset:0 fd:74
11-27 15:13:29.196: D/FirstActivity:onCreate(19898): mDBManager
11-27 15:13:29.196: D/FirstActivity:onCreate(19898): oncreate
11-27 15:13:29.196: I/FirstActivity:displayList(19898): displayList
11-27 15:13:29.196: W/dalvikvm(19898): threadid=1: thread exiting with uncaught exception (group=0x40ce31f8)
11-27 15:13:29.196: E/AndroidRuntime(19898): FATAL EXCEPTION: main
11-27 15:13:29.196: E/AndroidRuntime(19898): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.FirstActivity}: java.lang.NullPointerException
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1961)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.app.ActivityThread.access$600(ActivityThread.java:128)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1152)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.os.Looper.loop(Looper.java:137)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.app.ActivityThread.main(ActivityThread.java:4449)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at java.lang.reflect.Method.invokeNative(Native Method)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at java.lang.reflect.Method.invoke(Method.java:511)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at dalvik.system.NativeStart.main(Native Method)
11-27 15:13:29.196: E/AndroidRuntime(19898): Caused by: java.lang.NullPointerException
11-27 15:13:29.196: E/AndroidRuntime(19898):    at com.example.test.DBHelper.SortAllRows(DBHelper.java:139)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at com.example.test.FirstActivity.displayList(FirstActivity.java:50)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at com.example.test.FirstActivity.onCreate(FirstActivity.java:38)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.app.Activity.performCreate(Activity.java:4465)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-27 15:13:29.196: E/AndroidRuntime(19898):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1925)
11-27 15:13:29.196: E/AndroidRuntime(19898):    ... 11 more

您没有在构造函数中初始化db变量。因此:

SortAllRows()方法在执行return db.query(TABLE_NAME, new String[] { "_index", "_name", "_ad", "_ca", "_sp" }, null, null, null, null, null, "_name" + " ASC"); 时抛出NullPointerException

此外,您的表名将是test,而不是test.db,因为private static final String TABLE_NAME = "test";

为什么不将*.csv文件包含到SQlite数据库中,然后将该数据库添加到assets文件夹中。这将使事情变得简单,然后您可以轻松地从数据库中获取详细信息。

最新更新