简体   繁体   中英

simplecursoradapter/listview to sqlite database

Hi I'm very new to database. I've a code to retrieve SMS Inbox, Sent Box and Draft from phone and show it in a ListView using SimpleCursor Adapter. I want to save and retrieve ListView items (one at a time) of "Sent Box" to SQLite database. Currently I can insert data into database using edittext values. So basically what I want is a method to select ListView item one at a time and save it in String[] and then insert String[] value to database. Any help would be appreciated. Thanks in advance.

 Code to display database items using "ListActivity" SQLiteDatabase db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { db=openOrCreateDatabase("Student.db", SQLiteDatabase.CREATE_IF_NECESSARY, null); Cursor c=db.rawQuery("select id,name,age from Stud", null); ArrayList<String> list = new ArrayList<String>(); int count=c.getCount(); if(c.getCount()>0) { while(c.moveToNext()) { list.add(c.getString(0)+" , "+c.getString(1)+" , "+c.getString(2)); } c.close(); Toast.makeText(this,"Total Records: "+count, Toast.LENGTH_LONG).show(); ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list); getListView().setAdapter(adapter); } else { Toast.makeText(this, "No Record Found" , Toast.LENGTH_LONG).show(); } } catch(Exception e) { Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show(); } } public void onDestroy() { super.onDestroy(); db.close(); } }
 SQLite database public class MainActivity extends Activity { SQLiteDatabase db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); createDB(); //do insert Button btnInsert=(Button)findViewById(R.id.btnInsert ); btnInsert.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { insert(); } }); Button btnClear=(Button)findViewById(R.id.btnClear ); btnClear.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { clear(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); CreateMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return MenuChoice(item); } private void CreateMenu(Menu menu) { MenuItem mnu1 = menu.add(0, 0, 0, "Insert"); { mnu1.setAlphabeticShortcut('i'); mnu1.setIcon(android.R.drawable.ic_input_add); } MenuItem mnu2 = menu.add(0, 1, 1, "Search"); { mnu2.setAlphabeticShortcut('s'); mnu2.setIcon(android.R.drawable.ic_search_category_default); } MenuItem mnu3 = menu.add(0, 2, 2, "Delete"); { mnu3.setAlphabeticShortcut('d'); mnu3.setIcon(android.R.drawable.ic_delete); } MenuItem mnu4 = menu.add(0, 3, 3, "View"); { mnu4.setAlphabeticShortcut('d'); mnu4.setIcon(android.R.drawable.ic_menu_info_details); } } private boolean MenuChoice(MenuItem item) { Intent intent=new Intent(); switch (item.getItemId()) { case 0: insert(); return true; case 1: intent.setClass(MainActivity.this, Search.class); startActivity(intent); return true; case 2: intent.setClass(MainActivity.this, Search.class); startActivity(intent); return true; case 3: intent.setClass(MainActivity.this, ViewRecord.class); startActivity(intent); return true; } return false; } public void createDB() { db=openOrCreateDatabase("Student.db", SQLiteDatabase.CREATE_IF_NECESSARY, null); db.setLocale(Locale.getDefault()); db.setLockingEnabled(true); db.setVersion(1); String sql="create table if not exists Stud(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"; db.execSQL(sql); } public void insert() { EditText txtName=(EditText)findViewById(R.id.txtName); EditText txtAge=(EditText)findViewById(R.id.txtAge); if(txtName.getText().toString().equals("")) { Toast.makeText(MainActivity.this, "Enter Name.", Toast.LENGTH_SHORT).show(); } else if (txtAge.getText().toString().equals("")) { Toast.makeText(MainActivity.this, "Enter Age.", Toast.LENGTH_SHORT).show(); } else { String sql="insert into Stud(name,age) values('"+ txtName.getText().toString() +"',"+txtAge.getText().toString()+")"; db.execSQL(sql); clear(); Toast.makeText(MainActivity.this, "Record Successfully Inserted.", Toast.LENGTH_SHORT).show(); } } public void clear() { EditText txtName=(EditText)findViewById(R.id.txtName); EditText txtAge=(EditText)findViewById(R.id.txtAge); txtName.setText(""); txtAge.setText(""); txtName.clearFocus(); txtAge.clearFocus(); txtName.requestFocus(); } @Override public void onDestroy() { super.onDestroy(); db.close(); } }
 Code for displaying SMS Inbox, Sent Box and Draft public class MessageBox extends Activity implements OnClickListener { // GUI Widget Button btnSent, btnInbox, btnDraft; TextView lblMsg, lblNo; ListView lvMsg; // Cursor Adapter SimpleCursorAdapter adapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.messagebox); // Init GUI Widget btnInbox = (Button) findViewById(R.id.btnInbox); btnInbox.setOnClickListener(this); btnSent = (Button) findViewById(R.id.btnSentBox); btnSent.setOnClickListener(this); btnDraft = (Button) findViewById(R.id.btnDraft); btnDraft.setOnClickListener(this); lvMsg = (ListView) findViewById(R.id.lvMsg); } @Override public void onClick(View v) { if (v == btnInbox) { // Create Inbox box URI Uri inboxURI = Uri.parse("content://sms/inbox"); // List required columns String[] reqCols = new String[] { "_id", "address", "body" }; // Get Content Resolver object, which will deal with Content // Provider ContentResolver cr = getContentResolver(); // Fetch Inbox SMS Message from Built-in Content Provider Cursor c = cr.query(inboxURI, reqCols, null, null, null); // Attached Cursor with adapter and display in listview adapter = new SimpleCursorAdapter(this, R.layout.row, c, new String[] { "body", "address" }, new int[] { R.id.lblMsg, R.id.lblNumber }); lvMsg.setAdapter(adapter); } if (v == btnSent) { // Create Sent box URI Uri sentURI = Uri.parse("content://sms/sent"); // List required columns String[] reqCols = new String[] { "_id", "address", "body" }; // Get Content Resolver object, which will deal with Content // Provider ContentResolver cr = getContentResolver(); // Fetch Sent SMS Message from Built-in Content Provider Cursor c = cr.query(sentURI, reqCols, null, null, null); // Attached Cursor with adapter and display in listview adapter = new SimpleCursorAdapter(this, R.layout.row, c, new String[] { "body", "address" }, new int[] { R.id.lblMsg, R.id.lblNumber }); lvMsg.setAdapter(adapter); } if (v == btnDraft) { // Create Draft box URI Uri draftURI = Uri.parse("content://sms/draft"); // List required columns String[] reqCols = new String[] { "_id", "address", "body" }; // Get Content Resolver object, which will deal with Content // Provider ContentResolver cr = getContentResolver(); // Fetch Sent SMS Message from Built-in Content Provider Cursor c = cr.query(draftURI, reqCols, null, null, null); // Attached Cursor with adapter and display in listview adapter = new SimpleCursorAdapter(this, R.layout.row, c, new String[] { "body", "address" }, new int[] { R.id.lblMsg, R.id.lblNumber }); lvMsg.setAdapter(adapter); } } }

You are getting the SMS data from the following code

String[] reqCols = new String[] { "_id", "address", "body" };

        // Get Content Resolver object, which will deal with Content
        // Provider
        ContentResolver cr = getContentResolver();

        // Fetch Sent SMS Message from Built-in Content Provider
        Cursor c = cr.query(sentURI, reqCols, null, null, null);

Now all you need to do is get the data from cursor and insert it in your database either using raw query as you are doing or by using Content Provider.

For more information read Get inbox messages from android device to show in custom listview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM