【问题标题】:simplecursoradapter/listview to sqlite databasesimplecursoradapter/listview 到 sqlite 数据库
【发布时间】:2015-09-30 11:00:10
【问题描述】:

您好,我对数据库很陌生。我有一个代码可以从手机中检索 SMS 收件箱、发送箱和草稿,并使用 SimpleCursor Adapter 在 ListView 中显示。我想将“Sent Box”的 ListView 项目(一次一个)保存和检索到 SQLite 数据库。目前我可以使用 edittext 值将数据插入数据库。所以基本上我想要的是一种方法来一次选择一个 ListView 项目并将其保存在 String[] 中,然后将 String[] 值插入数据库。任何帮助,将不胜感激。提前致谢。

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);

		}

	}
}

【问题讨论】:

  • 没人知道吗?

标签: android android-listview sms android-sqlite simplecursoradapter


【解决方案1】:

您正在从以下代码获取短信数据

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);

现在您需要做的就是从游标中获取数据并将其插入到您的数据库中,或者使用您正在执行的原始查询或使用 Content Provider。

更多信息请阅读Get inbox messages from android device to show in custom listview

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多