sqlite增删改查 SimpleCursorAdapter 事务
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.cunli.sqlite002.MainActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="姓名" /> <EditText android:id="@+id/age" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/name" android:hint="班级" /> <RadioGroup android:id="@+id/radioGroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/age"> <RadioButton android:id="@+id/male" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="男" /> <RadioButton android:id="@+id/female" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="女" /> </RadioGroup> <Button android:id="@+id/saveButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/radioGroup" android:onClick="saveStudent" android:text="插入数据" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/deleteData" android:onClick="deleteData" android:layout_marginLeft="20dp" android:text="删除全部数据" android:layout_toRightOf="@id/saveButton" android:layout_below="@id/radioGroup"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/sCursor" android:text="simplec" android:onClick="scursor" android:layout_toRightOf="@id/deleteData" android:layout_below="@id/radioGroup" android:layout_marginLeft="10dp"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/saveButton" android:hint="更新" android:id="@+id/updateData"/> <Button android:id="@+id/updateButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/updateData" android:onClick="updateStudent" android:text="更新" android:layout_marginLeft="20dp"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_toRightOf="@id/updateButton" android:layout_below="@id/updateData" android:text="取出数据" android:id="@+id/getData" android:onClick="getData"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="clearData" android:id="@+id/clearData" android:layout_below="@id/updateData" android:layout_toRightOf="@id/getData" android:text="清空表中所有数据" android:layout_marginLeft="10dp"/> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/s1" android:layout_below="@id/getData"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/linerLayout"/> </ScrollView> </RelativeLayout>
package com.example.cunli.sqlite002; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.RadioGroup; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity { EditText nameEt,ageEt; RadioGroup radioGroup; SQLiteDatabase db; boolean gender = true; ContentValues contentValues;//创建ContentValues private List<Long> ids = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contentValues = new ContentValues(); nameEt = (EditText)findViewById(R.id.name); ageEt = (EditText)findViewById(R.id.age); radioGroup = (RadioGroup)findViewById(R.id.radioGroup); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.male){ gender = true; }else { gender = false; } } }); //以刻都写的方式打开或创建一个数据 db = openOrCreateDatabase("school",SQLiteDatabase.OPEN_READWRITE,null); //建表的语句 String createSQL = "CREATE TABLE IF NOT EXISTS Students (_id INTEGER NOT NULL,student_name CHAR(20) NOT NULL,age INTEGER,gender BOOLEAN,PRIMARY KEY(_id))"; //执行建表SQL语句 db.execSQL(createSQL); } //点击按钮事件处理 public void saveStudent(View view){ try{ db.beginTransaction();//开启事务 contentValues.put("student_name",nameEt.getText().toString()); contentValues.put("age",Integer.parseInt(ageEt.getText().toString())); contentValues.put("gender",gender); //执行插入语句 long id = db.insert("Students",null,contentValues); db.setTransactionSuccessful();//提交事务 ids.add(id); //如果返回值为-1,则说明那个插入失败 if (id != -1){ Toast.makeText(this,"插入数据成功",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this,"插入数据 失败",Toast.LENGTH_SHORT).show(); } }catch (Exception e){ e.printStackTrace(); }finally { db.endTransaction();//终止事务 } } @Override protected void onDestroy() { super.onDestroy(); if (db!=null){ db.close();//关闭数据库 } } // 更新数据库 public void updateStudent(View view){ String updateData = ((EditText)findViewById(R.id.updateData)).getText().toString(); contentValues.put("student_name",updateData); //更新数据 int num = db.update("Students",contentValues,"_id=?",new String[]{""+1}); Toast.makeText(MainActivity.this,"更新了"+num+"条数据。",Toast.LENGTH_SHORT).show(); } // 查询数据 public void getData(View view){ LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linerLayout); linearLayout.removeAllViews();//显示当前数据前,清除之前的数据 Cursor cursor = db.query("Students",new String[]{"student_name","age","gender"},null,null,null,null,"age"); if (cursor.getCount() > 0){ //循环获取数据 while (!cursor.isLast()){//退出循环的条件:是否到cursor的末尾 cursor.moveToNext();//向前移动,注意刚开始的时候,指针是在第一行数据之前的 String name = cursor.getString(0); int age = cursor.getInt(1); int gender = cursor.getInt(2); TextView textView = new TextView(MainActivity.this); textView.setText(name+":"+age+":"+(gender==1?"男":"女")); linearLayout.addView(textView); } }else { Toast.makeText(MainActivity.this,"表中没有数据",Toast.LENGTH_SHORT).show(); } } // 删除全部数据 public void deleteData(View view){ String[] arr = new String[ids.size()]; for (int i = 0; i < ids.size(); i++) { int delId = db.delete("Students","_id = ? ",new String[]{ids.get(i).toString()}); Log.e("log","----------------"+delId); } Toast.makeText(MainActivity.this,"全部数据已经删除",Toast.LENGTH_SHORT).show(); } // 清空表中所有数据 public void clearData(View view){ int delId = db.delete("Students",null,null); Log.e("log","----------------"+delId); Toast.makeText(MainActivity.this,"表中全部数据已清空",Toast.LENGTH_SHORT).show(); } public void scursor(View view) { Intent intent = new Intent(this,Main2Activity.class); startActivity(intent); } }
package com.example.cunli.sqlite002; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class Main2Activity extends AppCompatActivity { Cursor cursor7; SQLiteDatabase db; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); listView = (ListView)findViewById(R.id.listView); //以刻都写的方式打开或创建一个数据 db = openOrCreateDatabase("school",SQLiteDatabase.OPEN_READWRITE,null); //建表的语句 String createSQL = "CREATE TABLE IF NOT EXISTS Students (_id INTEGER NOT NULL,student_name CHAR(20) NOT NULL,age INTEGER,gender BOOLEAN,PRIMARY KEY(_id))"; //执行建表SQL语句 db.execSQL(createSQL); cursor7 = db.query("Students",new String[]{"_id","student_name","age","gender"},null,null,null,null,"age"); while (!cursor7.isLast()){ cursor7.moveToNext(); Log.e("log","-----------"+cursor7.getInt(0)+" "+cursor7.getString(1)+" "+cursor7.getInt(2)+" "+cursor7.getInt(3)); } ListAdapter adapter = new SimpleCursorAdapter(this,R.layout.student_item,cursor7,new String[]{"student_name","age","gender"},new int[]{R.id.textView1,R.id.textView2,R.id.textView3},0); // SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this,R.layout.student_item,cursor7,new String[]{"student_name","age","gender"},new int[]{R.id.textView1,R.id.textView2,R.id.textView3},0); Log.e("log","------adapter----getCount------"+adapter.getCount()); listView.setAdapter(adapter); // listView.setAdapter(new Myap(this)); } class Myap extends BaseAdapter { Context context; public Myap(Context context) { this.context = context; } @Override public int getCount() { return 20; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LinearLayout line = new LinearLayout(context); line.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); TextView text = new TextView(context); text.setText("ok"+Math.random()*10); line.addView(text); return line; } } }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main2" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.cunli.sqlite002.Main2Activity"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listView"/> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <!--姓名--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:id="@+id/textView1" android:textAppearance="?android:attr/textAppearanceLarge"/> <!--年龄--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Medium Text" android:id="@+id/textView2" android:textAppearance="?android:attr/textAppearanceMedium"/> <!--性别--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Medium Text" android:id="@+id/textView3" android:textAppearance="?android:attr/textAppearanceMedium"/> </LinearLayout>