如何保存多列并显示单列列表视图? [关闭]

Posted

技术标签:

【中文标题】如何保存多列并显示单列列表视图? [关闭]【英文标题】:how to save multiple column and display single column list view? [closed] 【发布时间】:2018-09-02 13:37:40 【问题描述】:

嘿,我正在尝试使用数据库助手使用数据库,我可以根据 toast 写入数据,但是每当我获得记录以列出视图时,应用程序就会停止工作请任何人都可以提供帮助。这是 MainActivity.java 的代码

package com.example.dhruv.bills;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class bills extends AppCompatActivity 
DBAdapter dbAdapter;
ListView mrecycleview;
private static final String TAG ="bills";
@Override
protected void onCreate(Bundle savedInstanceState) 
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bills);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mrecycleview =(ListView) findViewById(R.id.mRecycleView);
    dbAdapter = new DBAdapter(this);
    // mlistview();
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            Intent i = new Intent(getApplicationContext(),Editbills.class);
            startActivity(i);
        
    );
   // mlistview();


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_bills, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);

 /* private void mlistview()
    Log.d(TAG,"mlistview:Display data in listview");
    Cursor mCursor = dbAdapter.getAllRecords();
    ArrayList<String> listData = new ArrayList<>();
    while (mCursor.moveToNext())
        listData.add(mCursor.getString(1));
    
    ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
    mrecycleview.setAdapter(adapter);
*/

这是我用来保存和读取数据库并将其显示在列表视图上的 DbAdapter 代码。

package com.example.dhruv.bills;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter 
public static final String KEY_ROWID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_DUEDATE = "duedate";
public static final String KEY_COURSE = "course";
// public static final String KEY_NOTES = "notes";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;

private static final String DATABASE_CREATE =
    "create table if not exists assignments (id integer primary key autoincrement, "
    + "title VARCHAR not null, duedate date, course VARCHAR );";

private final Context context;    

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) 

    this.context = ctx;
    DBHelper = new DatabaseHelper(context);


private static class DatabaseHelper extends SQLiteOpenHelper 

    DatabaseHelper(Context context) 
    
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
    
        try 
            db.execSQL(DATABASE_CREATE);    
         catch (SQLException e) 
            e.printStackTrace();
        
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    
    

//---opens the database---
public DBAdapter open() throws SQLException 

    db = DBHelper.getWritableDatabase();
    return this;


//---closes the database---    
public void close() 

    DBHelper.close();


//---insert a record into the database---
public long insertRecord(String title, String duedate, String course) 

    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_TITLE, title);
    initialValues.put(KEY_DUEDATE, duedate);
    initialValues.put(KEY_COURSE, course);
    return db.insert(DATABASE_TABLE, null, initialValues);


//---deletes a particular record---
public boolean deleteContact(long rowId) 

    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;


//---retrieves all the records---
public Cursor getAllRecords()
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM" + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
    return data;


//---retrieves a particular record---
public Cursor getRecord()
String query1 ="SELECT * FROM" + KEY_TITLE;
    Cursor mCursor = db.rawQuery(query1,null);
    if (mCursor != null) 
        mCursor.moveToFirst();
    
    return mCursor;


//---updates a record---
public boolean updateRecord(long rowId, String title, String duedate, String course) 

    ContentValues args = new ContentValues();
    args.put(KEY_TITLE, title);
    args.put(KEY_DUEDATE, duedate);
    args.put(KEY_COURSE, course);
    return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;


这是我得到的代码的logcat,请帮忙

03-24 01:16:22.787 1096-1096/com.example.dhruv.bills E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: com.example.dhruv.bills, PID: 1096
                                                                   java.lang.RuntimeException: Unable to start activity ComponentInfocom.example.dhruv.bills/com.example.dhruv.bills.bills: android.database.sqlite.SQLiteException: near "FROMbills1": syntax error (code 1): , while compiling: SELECT * FROMbills1
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2656)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2721)
                                                                       at android.app.ActivityThread.access$900(ActivityThread.java:168)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:135)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5753)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
                                                                    Caused by: android.database.sqlite.SQLiteException: near "FROMbills1": syntax error (code 1): , while compiling: SELECT * FROMbills1
                                                                       at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                       at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
                                                                       at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
                                                                       at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                       at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                                                                       at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                       at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                       at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1454)
                                                                       at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1393)
                                                                       at com.example.dhruv.bills.DBAdapter.getAllRecords(DBAdapter.java:98)
                                                                       at com.example.dhruv.bills.bills.mlistview(bills.java:68)
                                                                       at com.example.dhruv.bills.bills.onCreate(bills.java:42)
                                                                       at android.app.Activity.performCreate(Activity.java:6112)
                                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1117)
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2721) 
                                                                       at android.app.ActivityThread.access$900(ActivityThread.java:168) 
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                       at android.os.Looper.loop(Looper.java:135) 
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5753) 
                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                       at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 

【问题讨论】:

请提供日志猫以便识别错误> @NiamatullahBakhshi 现在如何附加 logcat? 尝试编辑您的问题,您必须在编辑时看到图库图标。 @NiamatullahBakhshi 现在附上请检查 @KlingKlang 是的,它现在工作得很好。谢谢你的帮助兄弟。 【参考方案1】:

您在关键字FROM 和表bills1 之间省略了一个空格,即SQL 有FROMbills1 而应该是FROM bills1 (见下文重新表名)

查看您的代码,您有两种方法需要更改。而不是:-

//---retrieves all the records---
public Cursor getAllRecords()
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM" + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
    return data;


//---retrieves a particular record---
public Cursor getRecord()
String query1 ="SELECT * FROM" + KEY_TITLE;
    Cursor mCursor = db.rawQuery(query1,null);
    if (mCursor != null) 
        mCursor.moveToFirst();
    
    return mCursor;

你可以:-

//---retrieves all the records---
public Cursor getAllRecords()
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE; //<<<< space added after FROM
Cursor data = db.rawQuery(query,null);
    return data;


//---retrieves a particular record---
public Cursor getRecord()
String query1 ="SELECT * FROM " + KEY_TITLE; //<<<< space added after FROM
    Cursor mCursor = db.rawQuery(query1,null);
    if (mCursor != null) 
        mCursor.moveToFirst();
    
    return mCursor;

请注意,第二种方法会失败,因为 KEY_TITLE 会解析为 title 不是表格。

我无法从提供的代码中看到您如何获得表名 bills1,因为 DATABASE_TABLE 被定义为 bills。此外,您的代码似乎只根据以下内容创建一个名为 assignments 的表:-

private static final String DATABASE_CREATE =
    "create table if not exists assignments (id integer primary key autoincrement, "
    + "title VARCHAR not null, duedate date, course VARCHAR );";

我建议在整个代码中仅使用单一来源的表名和列名。这样做可以在很大程度上消除这些问题。


附加

仔细观察 DBAdapter 类还有其他问题,这是一个重新编写的版本,它结合了表和列名的单一定义并修复了这些问题(参见 cmets):-

public class DBAdapter 
    public static final String KEY_ROWID = "id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_DUEDATE = "duedate";
    public static final String KEY_COURSE = "course";
    // public static final String KEY_NOTES = "notes";
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "billsdb";
    private static final String DATABASE_TABLE = "bills";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE =
            "create table if not exists assignments (id integer primary key autoincrement, "
                    + "title VARCHAR not null, duedate date, course VARCHAR );";

    // Replaces DATABASE_CREATE using the one source definition
    private static final String TABLE_CREATE =
            "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
                    KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
                    KEY_TITLE + " DATE NOT NULL, " +
                    KEY_DUEDATE + " DATE ," +
                    KEY_COURSE + " VARCHAR " +
                    ")";

    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context ctx)
    
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    

    private static class DatabaseHelper extends SQLiteOpenHelper
    
        DatabaseHelper(Context context)
        
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        

        @Override
        public void onCreate(SQLiteDatabase db)
        
            db.execSQL(TABLE_CREATE); // NO need to encapsulate in try clause
        

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts"); //????????
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        
    

    //---opens the database---
    public DBAdapter open() throws SQLException
    
        db = DBHelper.getWritableDatabase();
        return this;
    

    //---closes the database---
    public void close()
    
        DBHelper.close();
    

    //---insert a record into the database---
    public long insertRecord(String title, String duedate, String course)
    
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_DUEDATE, duedate);
        initialValues.put(KEY_COURSE, course);
        //return db.insert(DATABASE_TABLE, null, initialValues);
        // Will return NULL POINTER EXCEPTION as db isn't set
        // Replaces commented out line
        return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
                null,
                initialValues
        );
    

    //---deletes a particular record---
    public boolean deleteContact(long rowId)
    
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    

    //---retrieves all the records--- SEE FOLLOWING METHOD
    public Cursor getAllRecords()
    SQLiteDatabase db = DBHelper.getWritableDatabase();
        String query ="SELECT * FROM " + DATABASE_TABLE;
        Cursor data = db.rawQuery(query,null);
        return data;
    

    //As per getAllRecords but using query convenience method
    public Cursor getAllAsCursor() 
        return DBHelper.getWritableDatabase().query(
                DATABASE_TABLE,
                null,null,null,null,null,null
        );
    

    //---retrieves a particular record--- THIS WILL NOT WORK - NO SUCH TABLE
    public Cursor getRecord()
    String query1 ="SELECT * FROM" + KEY_TITLE;
        Cursor mCursor = db.rawQuery(query1,null);
        if (mCursor != null) 
            mCursor.moveToFirst();
        
        return mCursor;
    

    // Retrieve a row (single) according to id
    public Cursor getRecordById(long id) 
        return DBHelper.getWritableDatabase().query(
                DATABASE_TABLE,
                null,
                KEY_ROWID + "=?",
                new String[]String.valueOf(id),
                null,null,null
                );
    


    //---updates a record---
    public boolean updateRecord(long rowId, String title, String duedate, String course)
    
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_DUEDATE, duedate);
        args.put(KEY_COURSE, course);
        String whereclause = KEY_ROWID + "=?";
        String[] whereargs = new String[]String.valueOf(rowId);
        // Will return NULL POINTER EXCEPTION as db isn't set
        //return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
        // Replaces commented out line
        return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
                args,
                whereclause,
                whereargs
        ) > 0;
    

上面的代码已经用下面的代码测试过(至少插入和检索数据):-

public class MainActivity extends AppCompatActivity 

    DBAdapter mDBAdapter;
    Cursor mCsr;

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

        mDBAdapter = new DBAdapter(this);
        addSomeData();

        mCsr = mDBAdapter.getAllAsCursor();
        while (mCsr.moveToNext()) 
            Log.d("BILLDATA",
                    "Title="+mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_TITLE)) +
                            " Due Date=" + mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_DUEDATE)) +
                            " Course=" + mCsr.getString(mCsr.getColumnIndex(DBAdapter.KEY_COURSE))
            );
        
        mCsr.close();
    

    // Add some data (note will add 3 rows each time it is run)
    private void addSomeData() 
        mDBAdapter.insertRecord("Bill1","2018-10-02","English");
        mDBAdapter.insertRecord("Bill2","2018-09-03","Mathematics");
        mDBAdapter.insertRecord("Bill3","2018-11-04", "Geography");
    

输出到日志(第三次运行后):-

03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill1 Due Date=2018-10-02 Course=English
03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill2 Due Date=2018-09-03 Course=Mathematics
03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill3 Due Date=2018-11-04 Course=Geography
03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill1 Due Date=2018-10-02 Course=English
03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill2 Due Date=2018-09-03 Course=Mathematics
03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill3 Due Date=2018-11-04 Course=Geography
03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill1 Due Date=2018-10-02 Course=English
03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill2 Due Date=2018-09-03 Course=Mathematics
03-23 21:34:10.164 1644-1644/so49457069bills.so49457069bills D/BILLDATA: Title=Bill3 Due Date=2018-11-04 Course=Geography

注意

我强烈建议您在进行更改后卸载应用程序或在运行应用程序之前清除应用程序的数据。这将删除数据库,然后重新创建数据库,然后调用数据库助手的 onCreate 方法

【讨论】:

感谢兄弟,它工作得很好。感谢您的帮助。 @dhruvsachdeva 很好。您能否在已回答的问题上打勾。 完成了兄弟。 ? 请也回答这个问题。 ***.com/questions/49497655/…

以上是关于如何保存多列并显示单列列表视图? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

具有多列的表视图

MySQL - 如何在多列 html 表中显示,单列 mysql 表

将 SQLite 表数据显示到列表视图中,就在将数据插入同一 Activity 上的表之后,无需关闭 Activity 并重新打开

如何创建具有多行多列的表格视图?

listbox的值怎么获取vba

无法保存数据并从关闭中重新加载表视图