填充用sql数据库项目列表视图

编程入门 行业动态 更新时间:2024-10-22 04:53:09
本文介绍了填充用sql数据库项目列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的申请是基于当用户输入了添加类别按钮显示对话框。然后,它应该将数据保存到一个SQL数据库和填充用户添加了每个项目的列表视图。我选择了SQL数据库,因为我希望当用户结束应用程序中的数据进行保存。我怎么居然填充的项目列表视图?以下是我迄今为止:

公共类CategoryDatabase {公共静态最后弦乐KEY_ROWID =_id;公共静态最后弦乐KEY_CATEGORY =类别;私有静态最后弦乐DATABASE_NAME =DBCategory;私有静态最后弦乐DATABASE_TABLE =categoryTable;私有静态最终诠释DATABASE_VERSION = 1;私人DbHelper ourHelper;私人最终上下文ourContext;私人SQLiteDatabase ourDatabase;公共CategoryDatabase(上下文C){    ourContext = C;}公共CategoryDatabase的open()抛出的SQLException {    ourHelper =新DbHelper(ourContext);    ourDatabase = ourHelper.getWritableDatabase();    返回此;}公共无效的close(){    ourHelper.close();}私有静态类DbHelper扩展SQLiteOpenHelper {    公共DbHelper(上下文的背景下){        超(背景下,DATABASE_NAME,空,DATABASE_VERSION);        // TODO自动生成构造函数存根    }    @覆盖    公共无效的onCreate(SQLiteDatabase DB){        db.execSQL(CREATE TABLE+ DATABASE_TABLE +(+                KEY_ROWID +INTEGER PRIMARY KEY AUTOINCREMENT,+                KEY_CATEGORY +TEXT NOT NULL);        );    }    @覆盖    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){        db.execSQL(DROP TABLE IF EXISTS+ DATABASE_TABLE);        的onCreate(DB);    }}众长createEntry(串类){    ContentValues​​ CV =新ContentValues​​();    cv.put(KEY_CATEGORY,类别);    返回ourDatabase.insert(DATABASE_TABLE,空,CV);}}

和主要活动:

公共类MainActivity延伸活动{最后上下文的背景下=这;ArrayAdapter<串GT; arrayAdapter;ArrayList的<串GT;时listItems =新的ArrayList<串GT;();LV的ListView;@覆盖保护无效的onCreate(捆绑savedInstanceState){    super.onCreate(savedInstanceState);    的setContentView(R.layout.main);    LV =(ListView控件)findViewById(R.id.listView1);    arrayAdapter =新ArrayAdapter<串GT;(这一点,android.R.layout.simple_list_item_1,listItems中);    lv.setAdapter(arrayAdapter);}@覆盖公共布尔onCreateOptionsMenu(菜单菜单){    //充气菜单;如果是present这增加了项目操作栏。    。getMenuInflater()膨胀(R.menu.main,菜单);    返回true;}@覆盖公共布尔onOptionsItemSelected(菜单项项){    开关(item.getItemId()){    案例R.id.menu_add_cat:        LayoutInflater李= LayoutInflater.from(背景);        查看promptAdd = li.inflate(R.layout.prompt_add,NULL);        AlertDialog.Builder alertDialogBu​​ilder =新AlertDialog.Builder(背景);        //设置prompts.xml到alertDialogBu​​ilder        alertDialogBu​​ilder.setView(promptAdd);        最终的EditText etAddCat =(EditText上)promptAdd.findViewById(R.id.etDialogInput);        //设置对话框消息        alertDialogBu​​ilder.setPositiveButton(完成,新DialogInterface.OnClickListener(){            @覆盖            公共无效的onClick(DialogInterface对话,诠释它){            / *             *添加一个这里的猫             *如果(空=输入和放大器;!&安培; input.length()0){                    listItems.add(输入);                    arrayAdapter.notifyDataSetChanged();                }其他{                    Toast.makeText(getApplicationContext(),请输入一个新的类别,Toast.LENGTH_LONG).show();                }             * /                布尔didItWork = TRUE;                尝试{                    串类= etAddCat.getText()的toString()。                    CategoryDatabase进入=新CategoryDatabase(MainActivity.this);                    entry.open();                    entry.createEntry(类);                    entry.close();                }赶上(例外五){                    didItWork = FALSE;                    字符串错误= e.toString();                    对话D =新的对话框(MainActivity.this);                    d.setTitle(该死!);                    TextView的电视=新的TextView(MainActivity.this);                    tv.setText(错误);                    d.setContentView(电视);                    d.show();                }最后{                    如果(didItWork){                        对话D =新的对话框(MainActivity.this);                        d.setTitle(见鬼啊!);                        TextView的电视=新的TextView(MainActivity.this);                        tv.setText(成功);                        d.setContentView(电视);                        d.show();                    }                }            }        })        .setNegativeButton(取消,新DialogInterface.OnClickListener(){            @覆盖            公共无效的onClick(DialogInterface对话,诠释它){                dialog.cancel();            }        });        //创建警报对话框        AlertDialog alertDialog = alertDialogBu​​ilder.create();        // 展示下        alertDialog.show();        打破;    }    //返回super.onOptionsItemSelected(项目);    返回true;}} // MainActivity结束

解决方案

创建一个函数 getAllCategory()在 CategoryDatabase 类。

公开名单<串GT; getAllCategory(){    清单<串GT;表=新的ArrayList<串GT;();    //选择所有查询    字符串selectQuery =SELECT * FROM+ DATABASE_TABLE;    光标光标= ourDatabase.rawQuery(selectQuery,NULL);    //通过所有行循环,并增加列表    如果(cursor.moveToFirst()){        做{            List.add(cursor.getString(1));        }而(cursor.moveToNext());    }    返回列表;   }

要填充项目的ListView。

在你的 MainActivity 说上按一下按钮。

CategoryDatabase进入=新CategoryDatabase(MainActivity.this);            entry.open();            清单<串GT;所有= entry.getAllCategory();            LV =(ListView控件)findViewById(R.id.listView1);            arrayAdapter =新ArrayAdapter<串GT;(MainActivity.this,android.R.layout.simple_list_item_1,全部);            lv.setAdapter(arrayAdapter);

编辑:

在的onCreate

CategoryDatabase进入=新CategoryDatabase(MainActivity.this);            entry.open();            清单<串GT;所有= entry.getAllCategory();                如果(all.size()0)//检查列表中包含的项目。                {            LV =(ListView控件)findViewById(R.id.listView1);            arrayAdapter =新ArrayAdapter<串GT;(MainActivity.this,android.R.layout.simple_list_item_1,全部);            lv.setAdapter(arrayAdapter);                }                其他                {                   Toast.makeText(MainActivity.this,没有条款显示,1000).show();                }

My application is based on displaying a dialog box when the user enters the "add category" button. It then should save data into an SQL Database and populate a list view with each item the user adds. I chose SQL database because I want the data to be saved when the user ends the app. How do I actually populate the list view with those items ? Here is what I have so far:

public class CategoryDatabase { public static final String KEY_ROWID = "_id"; public static final String KEY_CATEGORY = "category"; private static final String DATABASE_NAME = "DBCategory"; private static final String DATABASE_TABLE = "categoryTable"; private static final int DATABASE_VERSION = 1; private DbHelper ourHelper; private final Context ourContext; private SQLiteDatabase ourDatabase; public CategoryDatabase(Context c){ ourContext = c; } public CategoryDatabase open() throws SQLException{ ourHelper = new DbHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close(){ ourHelper.close(); } private static class DbHelper extends SQLiteOpenHelper{ public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_CATEGORY + " TEXT NOT NULL);" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); onCreate(db); } } public long createEntry(String category) { ContentValues cv = new ContentValues(); cv.put(KEY_CATEGORY, category); return ourDatabase.insert(DATABASE_TABLE, null, cv); } }

and the Main Activity:

public class MainActivity extends Activity { final Context context = this; ArrayAdapter<String> arrayAdapter; ArrayList<String> listItems = new ArrayList<String>(); ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv = (ListView)findViewById(R.id.listView1); arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems); lv.setAdapter(arrayAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.menu_add_cat: LayoutInflater li = LayoutInflater.from(context); View promptAdd = li.inflate(R.layout.prompt_add, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); //set prompts.xml to alertDialogBuilder alertDialogBuilder.setView(promptAdd); final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput); //set a dialog message alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /* * add a cat here * if(null != input && input.length() > 0){ listItems.add(input); arrayAdapter.notifyDataSetChanged(); }else{ Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show(); } */ boolean didItWork = true; try{ String category = etAddCat.getText().toString(); CategoryDatabase entry = new CategoryDatabase(MainActivity.this); entry.open(); entry.createEntry(category); entry.close(); }catch(Exception e){ didItWork = false; String error = e.toString(); Dialog d = new Dialog(MainActivity.this); d.setTitle("Dang it ! "); TextView tv = new TextView(MainActivity.this); tv.setText(error); d.setContentView(tv); d.show(); }finally{ if(didItWork){ Dialog d = new Dialog(MainActivity.this); d.setTitle("Heck yea ! "); TextView tv = new TextView(MainActivity.this); tv.setText("Success"); d.setContentView(tv); d.show(); } } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); break; } //return super.onOptionsItemSelected(item); return true; } }// end of MainActivity

解决方案

Create a function getAllCategory() in CategoryDatabase class.

public List<String> getAllCategory() { List<String> List = new ArrayList<String>(); // Select All Query String selectQuery = "SELECT * FROM " + DATABASE_TABLE; Cursor cursor = ourDatabase.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { List.add(cursor.getString(1)); } while (cursor.moveToNext()); } return List; }

To populate items to listview.

In your MainActivity say on button click.

CategoryDatabase entry = new CategoryDatabase(MainActivity.this); entry.open(); List<String> all = entry.getAllCategory(); lv = (ListView)findViewById(R.id.listView1); arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all); lv.setAdapter(arrayAdapter);

Edit :

In onCreate

CategoryDatabase entry = new CategoryDatabase(MainActivity.this); entry.open(); List<String> all = entry.getAllCategory(); if(all.size()>0) // check if list contains items. { lv = (ListView)findViewById(R.id.listView1); arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all); lv.setAdapter(arrayAdapter); } else { Toast.makeText(MainActivity.this,"No items to display",1000).show(); }

更多推荐

填充用sql数据库项目列表视图

本文发布于:2023-08-05 21:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1308156.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   数据库   项目   列表   sql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!