标签:android listview gridview 数据库
昨天去学校的奶茶店买茶,发现他推出的积分卡不是很好用,就是买1杯就可以有1个积分,满10个积分就可以免费兑换一杯。因为人比较多,所以他用了两本类似相册的本子夹着这些积分卡,卡上盖了用户的几个积分章。之所以说难用是因为用户说多也不多,说少也还真不少,每次都翻那么多找到自己名字,真不爽。因此,就想到写一个APP,来帮他实现这些工作。
目标需求:能快速查询到自己名字;通过自己名字查看已经有多少积分。
分析:因为需求很简单,所以数据库的表只要3个字段就可以,一个是唯一key;一个是用户名字,这里也是要求唯一,因为大家都只填写名字,没有别的信息,所以必须规定已有的名字就不能再次被填写,不然通过名字访问数据库时就查找到多个对应记录;最后一个就是用户积分数,每次查询都是通过用户名字来查询积分数。这是对数据库的要求,其次就是界面的要求,为了尽量直观美观,主界面分两块,一个是输入名字,查询按钮,添加新用户按钮;另一块就是一个显示窗口,把已存在的用户分类显示出来。为了达到快速定位查找的效果,用户可以手动输入自己名字,也可以通过翻看显示,查找。为了翻看显示查找的快速,我把用户名字的第一个字按照拼音的首字母来分类显示出来。跳转的界面就是用户找到自己的名字了,要查看积分数,这里为了美观,除了直接把信息通过textview显示出来,还做了一个动态图,同时,动态图也是为了增加积分时的直观显示。界面大致如下:
这张是第一次进入程序的截屏,因为第一次没有任何记录,所以只显示了按照26个字母分类的条目,然后在上方的输入栏添加输入。如果是第一次输入,如果你按下的是查找button,那么会有提示,让你先添加你的名字到数据库。可以按右边的按键添加名字,但是名字是唯一查找信息源,没有别的参考信息,所以名字必须是唯一,如果重名会提示。
添加按钮会直接进入第二个界面,告诉用户你已经来消费一次了,有一个积分了,可以看到盖了一个章,也可以从textview上读出主要信息。
再次进入程序就应该是这样的显示,告诉你用户已经添加成功啦。这时你可以选择通过输入名字来点击搜索按键进入查看积分信息,也可以通过直接点击你的名字,直接进去查看积分信息。
当你再次来消费时,获得了增加一次积分的权利,可以直接进入查看积分的这个界面,然后点击空白的地方,然后就有上面的弹框,点击确定就可以再盖一次积分章啦。点击确定之后的显示就是下面这幅图啦。
当达到9次积分的时候,第十次来消费,这时盖章直接就会返回到第一界面,并且弹出提示,告诉你可以兑换积分啦,你再次进入的时候,也会有提示,告诉你上次你把10个积分都兑换了,现在一个章都没有啦。如下图显示:
这就是全部的流程的展示。
这里就把两个主要的界面的代码贴出来吧,如果有需要整个工程的可以直接去这个地址下载,不要积分哟!!!http://download.csdn.net/detail/u012321815/7958059
package com.example.changyin; import java.io.File; import java.io.IOException; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private String[] string = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; private MySQLiteOpenHelper myOpenHelper; private SQLiteDatabase sqlitedb; private File sqlpath = new File("/sdcard/test"); //数据库文件目录 private File sqlfile = new File("/sdcard/test/test.db"); //数据库文件 Button btn_search; Button btn_add; EditText et; boolean isExit; String string_et; int totalnum = 0; ListView listview; MyAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et = (EditText)findViewById(R.id.edittext); btn_add = (Button)findViewById(R.id.button_add); btn_search = (Button)findViewById(R.id.button_search); btn_add.setOnClickListener(listener); btn_search.setOnClickListener(listener); listview = (ListView) findViewById(R.id.listview); adapter = new MyAdapter(this); //shujuku myOpenHelper = new MySQLiteOpenHelper(MainActivity.this); //----如要在SD卡中创建数据库文件,先做如下的判断和创建相对应的目录和文件---- if(!sqlpath.exists()){ //判断目录是否存在 sqlpath.mkdirs(); //创建目录 } if(!sqlfile.exists()){ //判断文件是否存在 try{ sqlfile.createNewFile(); //创建文件 sqlitedb = SQLiteDatabase.openOrCreateDatabase(sqlfile, null); //新建数据表 String str = "create TABLE chz(id int,name varchar(20),number varchar(15));"; sqlitedb.execSQL(str); }catch(IOException e){ e.printStackTrace(); } } sqlitedb = SQLiteDatabase.openOrCreateDatabase(sqlfile, null); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub String strings = adapter.getItem(arg2).toString(); boolean f = true; for(int k=0;k<string.length;k++){ if(strings.equals(string[k])){ f = false; break; } } if(f){ Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("chz", strings); intent.putExtras(bundle); intent.setClass(MainActivity.this, SearchActivity.class); startActivity(intent); } } }); } @Override protected void onResume() { // TODO Auto-generated method stub adapter.clear(); int size = string.length; for (int i = 0; i < size; i++) { adapter.addSeparatorItem(string[i]); Cursor cursor = sqlitedb.rawQuery("select * from chz;" , null); String stringforname[] = new String[500]; int j = 0; while(cursor.moveToNext()){ stringforname[j] = cursor.getString(1); String pinyinString = HypyUtil.cn2py(stringforname[j]); String stringforfirstname = pinyinString.substring(0,1); if(stringforfirstname.equals(string[i])){ adapter.addItem(stringforname[j]); } j++; } } adapter.notifyDataSetChanged(); listview.setAdapter(adapter); super.onResume(); } Button.OnClickListener listener = new Button.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub if(arg0 == btn_add){ Cursor cur = sqlitedb.rawQuery("select * from chz;", null); totalnum = 0; while(cur.moveToNext()){ totalnum++; } string_et = et.getText().toString(); Cursor cursor = sqlitedb.rawQuery("select * from chz where name = '" + string_et + "';", null); boolean flag = true; while(cursor.moveToNext()){ String temp = cursor.getString(1); if(temp.equals(string_et)){ // Toast.makeText(MainActivity.this, "该用户名已被占用,请重新输入一个可用昵称!", Toast.LENGTH_SHORT).show(); dialog_zhanyong(); flag = false; break; } } if(flag){ if(string_et.equals("请输入姓名:")){ Toast.makeText(MainActivity.this, "你还未填写姓名呢。", Toast.LENGTH_SHORT).show(); }else { dialog_add(); } } }else if (arg0 == btn_search) { string_et = et.getText().toString(); Cursor cursor = sqlitedb.rawQuery("select * from chz where name = '" + string_et + "';", null); boolean flag = false; while(cursor.moveToNext()){ String temp = cursor.getString(1); if(temp.equals(string_et)){ flag = true; break; } } if(flag){ Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("chz", string_et); intent.putExtras(bundle); intent.setClass(MainActivity.this, SearchActivity.class); startActivity(intent); }else{ Toast.makeText(MainActivity.this, "亲,你这是第一次来哟,请先添加你的名字!", Toast.LENGTH_SHORT).show(); } } } }; protected void dialog_zhanyong(){ AlertDialog.Builder builder = new Builder(MainActivity.this); builder.setMessage("该用户名已被占用,请重新输入一个可用昵称!"); builder.setTitle("提示"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); builder.create().show(); } protected void dialog_add(){ AlertDialog.Builder builder = new Builder(MainActivity.this); builder.setMessage("确认添加么?"); builder.setTitle("提示"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { ContentValues cValue = new ContentValues(); cValue.put("id",totalnum+1); cValue.put("name",string_et); cValue.put("number","1"); sqlitedb.insert("chz",null,cValue); // Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); Bundle bundle = new Bundle(); string_et = et.getText().toString(); bundle.putString("chz", string_et); intent.putExtras(bundle); intent.setClass(MainActivity.this, SearchActivity.class); startActivity(intent); } }); builder.create().show(); } protected void dialog(){ AlertDialog.Builder builder = new Builder(MainActivity.this); builder.setMessage("这是海牛宝宝爱学习写的哟!"); builder.setTitle("关于"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); builder.create().show(); } //重写Activity中onKeyDown方法 public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exit(); return false; } else { return super.onKeyDown(keyCode, event); } } //写一个退出方法,名称就是onKeyDown中的exit() public void exit(){ if (!isExit) { isExit = true; Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); mHandler.sendEmptyMessageDelayed(0, 2000); } else { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); System.exit(0); } } //根据exit()方法中的的消息,写一个Handler Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); isExit = false; } }; @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) { // 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(); if (id == R.id.action_settings) { dialog(); return true; } return super.onOptionsItemSelected(item); } }
这是主界面的。
package com.example.changyin; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.ContentValues; import android.content.DialogInterface; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class SearchActivity extends Activity { private MySQLiteOpenHelper myOpenHelper; private SQLiteDatabase sqlitedb; private File sqlpath = new File("/sdcard/test"); //数据库文件目录 private File sqlfile = new File("/sdcard/test/test.db"); //数据库文件 String totalnumber = ""; String number = ""; String location = ""; String name=""; ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map = new HashMap<String, Object>(); GridView gridview; SimpleAdapter saImageItems; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.chaxun); myOpenHelper = new MySQLiteOpenHelper(SearchActivity.this); sqlitedb = SQLiteDatabase.openOrCreateDatabase(sqlfile, null); Bundle bundle = this.getIntent().getExtras(); name = bundle.getString("chz"); Cursor cursor = sqlitedb.rawQuery("select * from chz where name = '" + name + "';", null); while(cursor.moveToNext()){ totalnumber = cursor.getString(2); } number = String.valueOf(Integer.parseInt(totalnumber)%10); String s = "1"; if(number.equals("0")){ s = "亲爱的"+name+",你上一次已经把10分的积分兑换掉啦,现在没有剩余积分咯,赶紧来续杯吧!"; }else{ s = "亲爱的"+name+",你已经累积了"+number+"次积分啦,只需要再邀请小伙伴来"+(10-Integer.parseInt(number))+"次就可以兑换积分咯!"; } TextView tView = (TextView)findViewById(R.id.name); tView.setText(s); gridview = (GridView) findViewById(R.id.gridview); ArrayList<HashMap<String, Object>> lstImageItem1 = new ArrayList<HashMap<String, Object>>(); //生成动态数组,并且转入数据 for(int i=0;i<Integer.parseInt(number);i++) { map = new HashMap<String, Object>(); map.put("ItemImage", R.drawable.gai);//添加图像资源的ID map.put("ItemText", "NO."+String.valueOf(i+1));//按序号做ItemText lstImageItem1.add(map); } for(int i=Integer.parseInt(number);i<10;i++ ){ map = new HashMap<String, Object>(); map.put("ItemImage", R.drawable.no);//添加图像资源的ID map.put("ItemText", "NO."+String.valueOf(i+1));//按序号做ItemText lstImageItem1.add(map); } lstImageItem = lstImageItem1; //生成适配器的ImageItem <====> 动态数组的元素,两者一一对应 saImageItems = new SimpleAdapter(this, //没什么解释 lstImageItem,//数据来源 R.layout.night_item,//night_item的XML实现 //动态数组与ImageItem对应的子项 new String[] {"ItemImage","ItemText"}, //ImageItem的XML文件里面的一个ImageView,两个TextView ID new int[] {R.id.ItemImage,R.id.ItemText}); //添加并且显示 gridview.setAdapter(saImageItems); //添加消息处理 gridview.setOnItemClickListener(new ItemClickListener()); } //当AdapterView被单击(触摸屏或者键盘),则返回的Item单击事件 class ItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened View arg1,//The view within the AdapterView that was clicked int arg2,//The position of the view in the adapter long arg3//The row id of the item that was clicked ) { //在本例中arg2=arg3 HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2); //显示所选Item的ItemText String str = item.get("ItemText").toString(); location = str.substring(3); if(Integer.parseInt(location)<=Integer.parseInt(number)){ Toast.makeText(SearchActivity.this, "已经盖章啦!", Toast.LENGTH_SHORT).show(); }else{ dialog_gai(); } } } // private Handler mHandler = new Handler() { // public void handleMessage(Message msg) { // saImageItems.notifyDataSetChanged(); // } // }; protected void dialog_gai(){ AlertDialog.Builder builder = new Builder(SearchActivity.this); builder.setMessage("要盖章了么?"); builder.setTitle("提示"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { ContentValues cv = new ContentValues(); cv.put("number", String.valueOf(Integer.parseInt(number)+1)); sqlitedb.update("chz", cv, "name = '" + name + "'", null); if((Integer.parseInt(number)+1)%10 == 0){ Toast.makeText(SearchActivity.this, "恭喜親愛的小夥伴,你滿十次了,可以兌換幾分啦!", Toast.LENGTH_SHORT).show(); SearchActivity.this.finish(); }else{ number = String.valueOf(Integer.parseInt(number)+1); ArrayList<HashMap<String, Object>> lstImageItem2 = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map1 = new HashMap<String, Object>(); // SimpleAdapter saImageItems1; for(int i=0;i<Integer.parseInt(number);i++) { map1 = new HashMap<String, Object>(); map1.put("ItemImage", R.drawable.gai);//添加图像资源的ID map1.put("ItemText", "NO."+String.valueOf(i+1));//按序号做ItemText lstImageItem2.add(map1); } for(int i=Integer.parseInt(number);i<10;i++ ){ map1 = new HashMap<String, Object>(); map1.put("ItemImage", R.drawable.no);//添加图像资源的ID map1.put("ItemText", "NO."+String.valueOf(i+1));//按序号做ItemText lstImageItem2.add(map1); } //生成适配器的ImageItem <====> 动态数组的元素,两者一一对应 lstImageItem = lstImageItem2; saImageItems = new SimpleAdapter(SearchActivity.this, //没什么解释 lstImageItem,//数据来源 R.layout.night_item,//night_item的XML实现 //动态数组与ImageItem对应的子项 new String[] {"ItemImage","ItemText"}, //ImageItem的XML文件里面的一个ImageView,两个TextView ID new int[] {R.id.ItemImage,R.id.ItemText}); //添加并且显示 gridview.setAdapter(saImageItems); } } }); builder.create().show(); } @Override protected void onDestroy() { // TODO Auto-generated method stub this.finish(); super.onDestroy(); } }
标签:android listview gridview 数据库
原文地址:http://blog.csdn.net/jishucai/article/details/39475421