简体   繁体   English

在listView android应用中显示现有的SQLite数据库

[英]Show existing SQLite database in listView android app

hi everyone I have been trying to use a database and show Its information into a listView but I can't make it work . 大家好,我一直在尝试使用数据库并将其信息显示在listView中,但我无法使其正常工作。 Here is my DatabaseHelper class(It extends from SQLiteOpenHelper): 这是我的DatabaseHelper类(它从SQLiteOpenHelper扩展):

public static String DB_PATH = "/data/data/ice.tea09.sqlitedemo/databases/";

public static String DB_NAME = "Test.sqlite";

public static final int DB_VERSION = 1;

public static final String TB_USER = "Users";

private SQLiteDatabase myDB;
private Context context;

//private String DB_PATH =context.getFilesDir().getPath();

public DatabaseHelper(Context context)
{
    super(context, DB_NAME, null, DB_VERSION);  
    this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db)
{
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    // TODO Auto-generated method stub

}

@Override
public synchronized void close()
{
    if(myDB!=null)
    {
        myDB.close();
    }
    super.close();
}

public List<String> getAllUsers()
{
    List<String> listUsers = new ArrayList<String>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c;

    try
    {
        c = db.rawQuery("SELECT * FROM " + TB_USER , null);
        if(c == null) return null;

        String name;
        c.moveToFirst();
        do
        {
            name = c.getString(1);
            listUsers.add(name);
        } while (c.moveToNext()); 
        c.close();
    }
    catch (Exception e)
    {
        Log.e("tle99", e.getMessage());
    }


    db.close();     

    return listUsers;
}


/*
 * Copy database from source code assets to device
 * @throws IOException
 */
public void copyDataBase() throws IOException
{
    try
    {
        InputStream myInput = context.getAssets().open(DB_NAME);
        String outputFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outputFileName);

        byte[] buffer = new byte[1024];
        int length;

        while((length = myInput.read(buffer))>0)
        {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }
    catch (Exception e)
    {
        Log.e("tle99 - copyDatabase", e.getMessage());
    }

}

/*
 * Check if the database doesn't exist on device, create new one
 * @throws IOException
 */
public void createDataBase() throws IOException
{
    boolean dbExist = checkDataBase();      

    if (dbExist)
    {

    }
    else
    {
        this.getReadableDatabase();
        try
        {
            copyDataBase();
        }
        catch (IOException e)
        {
            Log.e("tle99 - create", e.getMessage());
        }
    }
}

// ---------------------------------------------
// PRIVATE METHODS
// ---------------------------------------------

/*
 * Check if the database is exist on device or not
 * @return
 */
private boolean checkDataBase()
{
    SQLiteDatabase tempDB = null;
    try
    {
        String myPath = DB_PATH + DB_NAME;
        tempDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }
    catch (SQLiteException e)
    {
        Log.e("tle99 - check", e.getMessage());
    }
    if (tempDB != null)
    {
        tempDB.close();
    }

    return tempDB != null ? true : false;
}

And this is my ActivityMain:` 这是我的ActivityMain:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dataBaseHandler=new DataBaseHandler(this);
    try
    {
        dataBaseHandler.createDataBase();
    }

    catch (IOException e) {
        e.printStackTrace();
    }

    listViewusers=findViewById(R.id.listView);
    List<String> list=dataBaseHandler.getAllUsers();
    if(list!=null) {
        arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.activity_list_item, list);
        listViewusers.setAdapter(arrayAdapter);
    }`

I have a database in my assets folder The app shows nothing when its up and running can anyone help me with this please I really dont have any idea . 我的资产文件夹中有一个数据库该应用程序在启动和运行时不显示任何内容,任何人都可以帮我解决这个问题,我真的没有任何想法。

at the first is better to get database address with 首先比较好用

@SuppressLint("SdCardPath")
private void checkDBAddress(Context context) {
    if (android.os.Build.VERSION.SDK_INT >= 17) {
        DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
    } else {
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    }
}

in that line you should start from Zero, so if you just have one Field change it 在那一行中,您应该从零开始,所以如果您只有一个字段,请更改它

name = c.getString(1);

to

name = c.getString(0);

at last I got exception on your ArrayAdapter, if you have the same problem change adapter to 最后,如果您遇到相同的问题,请将ArrayAdapter更改为ArrayAdapter上的异常

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM