如何阅读,将数据库添加到ArrayList?

时间:2016-02-26 07:38:18

标签: android sqlite arraylist

我是Android Studio新手。我不知道如何阅读和添加数据库到Arraylist。你能帮帮我吗:P?我已经尝试了一些方法,但它仍然没有工作@。@。

     public class DatabaseHelper extends SQLiteOpenHelper 
{
            public static final String DATABASE_NAME = "ToDoList.db";
            public static final String TABLE_NAME = "ToDoList_Table";
            public static final String DATABASE_TABLE = "ToDo_DBTable";
            public static final String COL_1 = "ID";
            public static final String COL_2 = "TODO";

            public DatabaseHelper(Context context) {
                super(context, DATABASE_NAME, null, 1);
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,TODO TEXT)");
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
                onCreate(db);
            }

            public boolean insertData(String TODO) {
                SQLiteDatabase db = this.getWritableDatabase();
                ContentValues contentValues = new ContentValues();
                contentValues.put(COL_2, TODO);
                long result = db.insert(TABLE_NAME, null, contentValues);
                if (result == -1)
                    return false;
                else
                    return true;
            }
            public ArrayList<String> getRecords(){
                SQLiteDatabase db = this.getReadableDatabase();
                ArrayList<String> data=new ArrayList<String>();
                Cursor cursor = db.query(TABLE_NAME, new String[]{COL_2},null, null, null, null, null);
                String fieldToAdd=null;
                while(cursor.moveToNext()){
                    fieldToAdd=cursor.getString(0);
                    data.add(fieldToAdd);
                }
                cursor.close();
                return data;
            }
        }       

    public class MainActivity extends AppCompatActivity
    {
        DatabaseHelper TDdb;
        ArrayList<String> todoItems;
        ArrayAdapter<String> aTodoAdapter;
        ListView lvItems;
        EditText editTD;
        Button btnAddItems;



        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            populateArrayItems();

            editTD = (EditText) findViewById(R.id.tdEditText);
            lvItems = (ListView) findViewById(R.id.lvItems);
            btnAddItems = (Button) findViewById(R.id.tdAddItems);
            AddData();

            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setLogo(R.drawable.list_ingredients);
            getSupportActionBar().setDisplayUseLogoEnabled(true);
            lvItems.setAdapter(aTodoAdapter);
            lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
                                               long id) {
                    todoItems.remove(position);
                    aTodoAdapter.notifyDataSetChanged();
                    return true;
                }
            });
            TDdb = new tdls.todolistapps.DatabaseHelper(this);
        }
        public void AddData()
        {
            btnAddItems.setOnClickListener(
                    new View.OnClickListener()
                    {
                        @Override
                    public void onClick(View view)
                        {
                           boolean isInserted = TDdb.insertData(editTD.getText().toString());
                            if(isInserted = true )

                                Toast.makeText(MainActivity.this,"Items Inserted",Toast.LENGTH_LONG).show();
                                else
                                Toast.makeText(MainActivity.this,"Items not Inserted",Toast.LENGTH_LONG).show();

                        }
                    }
            );
        }
        public void populateArrayItems()
        {
            todoItems = new ArrayList<String>();
            todoItems.add("Item 1");
            todoItems.add("Item 2");
            todoItems.add("Item 3");
            aTodoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems );

        }

        @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_main, menu);
            menu.add("Email");
            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);
        }

        public void onAddItem(View v)
        {
            aTodoAdapter.add(editTD.getText().toString());
            editTD.setText("");
        }
    }

这是图片,它说项目已插入,但它不会显示:&#39;(

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试替换以下代码

 if(isInserted = true ){
                todoItems.add(editTD.getText().toString());
                aTodoAdapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this,"Items Inserted",Toast.LENGTH_LONG).show();
 }
 else {
                Toast.makeText(MainActivity.this, "Items not Inserted", Toast.LENGTH_LONG).show();
 }

在向数据库添加数据后,您还需要更新适配器。

答案 1 :(得分:0)

首先更改你的getRecords()函数,如下所示:

public ArrayList<String> getRecords(){
    open();
    ArrayList<String> data = new ArrayList<>();
    Cursor cursor = db.query(DATABASE_TABLE, new String[]{COL_2}, null, null, null, null, null, null);
    if (cursor.moveToFirst()){
        do {
            data.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }
    close();
    return data;
}