【问题标题】:How to populate listview with SQLite data?如何用 SQLite 数据填充列表视图?
【发布时间】:2014-03-14 08:29:42
【问题描述】:

在我的 Android 短信应用中,我可以发送和接收短信。当我发送 SMS 时,我在 Sqlite DB 中存储一个标志,以指示这是在单击按钮上发送的 SMS,如下所示:

protected void SendSMS() {
    SmsManager sms_manager = SmsManager.getDefault();
    message_body = et_chat.getText().toString();
    ArrayList<String> parts = sms_manager.divideMessage(message_body);
    sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
    flag = "1";
    manager.Insert_sms_data(time, contact_no, message_body,flag);
    msg+= "SMS to :" + contact_for_chat + " \n";
    msg += "having number:" + contact_no + " \n";
    msg += "as" +message_body + " \n";
    msg += "at"+ time + " \n";
    Toast.makeText(getApplicationContext(), ""+msg , Toast.LENGTH_LONG).show();

}

收到短信后,我将标志保存为 0,如下所示:

public class IncomingSMS extends BroadcastReceiver {

Context context;
DbManager DBmanager;
private long timestamp;
private String number;
private String body = "";
String msg="";
Cursor cursor;
String display_name;
String flag;

@Override
public void onReceive(Context context, Intent intent) {
    try {

        final Bundle bundle = intent.getExtras();


            if (bundle != null) {

                //—retrieve the SMS message received—
                Object messages[] = (Object[]) bundle.get("pdus");
                SmsMessage smsMessage[] = new SmsMessage[messages.length];

                for (int n = 0; n < messages.length; n++) {
                    smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
                    timestamp = smsMessage[n].getTimestampMillis();

                    number = smsMessage[n].getOriginatingAddress();
                    body += smsMessage[n].getDisplayMessageBody();
                    display_name = Util.getContactName(context, number);
                    DBmanager = new DbManager(context);
                    cursor = DBmanager.Return_All_Contacts();
                    String [] contactArr = showcontactsInfo(cursor);
                Toast.makeText(context, contactArr[0]+"", 3000).show();
                    if(contactArr.length==0)
                    {}
                    else{
                    for(int i= 0;i<=contactArr.length;i++)
                    {

                        abortBroadcast();

                            }
                    blockMessage(context);

                    }
                        }
                    }

                }
        catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);

        }

            } // end for loop
        // bundle is null




    private String[] showcontactsInfo(Cursor cursor) {
        String[] contact = new String [cursor.getCount()];
        int i= 0;
        while(cursor.moveToNext()){
            contact[i] = cursor.getString(1);
            i++;
        }
        return contact;
    }
    private void blockMessage(Context context) {

        // instantiate DbMNager object to insert sms in database
        //formating receiving time:
        //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");

        SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d  HH:mm:ss a");
        String formatedTime = formatter.format(timestamp);
        flag = "0";
        DBmanager= new DbManager(context);
        DBmanager.open();
        DBmanager.Insert_sms_data(formatedTime ,number,body,flag);
        DBmanager.close();
        msg+= "SMS from " + number + " \n";
        msg += body + " \n";
        msg += formatedTime + " \n";
        msg += flag + " \n";
        Log.i("SmsReceiver", "senderNum: "+ display_name + "; message: " + body);
        Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
        //Toast.makeText(context, "New message received in Discrete", Toast.LENGTH_LONG).show();
    }    
}

数据成功存储在数据库中,之后我想在 ListView 中检索它,如果标志为 1(我们已发送短信)则背景应该不同,如果标志为 0(我们已收到短信)则背景应该是不同的。我能够检索“发送的短信”,但不能检索“收到的短信”。这是代码:

private MyListAdapter adapter;
ArrayList<String> item_id = new ArrayList<String>();
ArrayList<String> item_phone_num = new ArrayList<String>();
ArrayList<String> item_msg_body = new ArrayList<String>();
ArrayList<String> item_time = new ArrayList<String>();
ArrayList<String> item_flag = new ArrayList<String>();
ArrayList<String> items = new ArrayList<String>();
private Button btn_send;
DbManager manager;
Cursor Cursor;
ViewHolder holder12;
String contact_for_chat;
String contact_no;
String message_body = "";
Calendar c;
SimpleDateFormat sdf;
String time;
EditText et_chat;
String flag;
String msg = "";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    try{
    Bundle bundle = getIntent().getExtras();
    contact_for_chat = bundle.getString("contact_name");
    contact_for_chat = contact_for_chat.replace(" ", "");
    contact_no = Util.getContactNumber(contact_for_chat, ChatActivity.this);
    Toast.makeText(getApplicationContext(), contact_no, Toast.LENGTH_LONG).show();
    final ViewHolder holder = new ViewHolder();
    manager = new DbManager(this);
    Cursor = manager.Return_SMS(contact_no);
    showEvents(Cursor);

    c = Calendar.getInstance();
    sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
    time = sdf.format(c.getTime());
    //setActionBar();
    findViewsById();
    adapter = new MyListAdapter(this);
    adapter.notifyDataSetChanged();
    setListAdapter(adapter);

    btn_send = (Button) findViewById(R.id.button1);
    btn_send.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            SendSMS();
        }
    });
    }
    catch(Exception ex)
    {
        Log.e("ERROR", ex.toString());
    }
}

protected void SendSMS() {
    SmsManager sms_manager = SmsManager.getDefault();
    message_body = et_chat.getText().toString();
    ArrayList<String> parts = sms_manager.divideMessage(message_body);
    sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
    flag = "1";
    manager.Insert_sms_data(time, contact_no, message_body,flag);
    msg+= "SMS to :" + contact_for_chat + " \n";
    msg += "having number:" + contact_no + " \n";
    msg += "as" +message_body + " \n";
    msg += "at"+ time + " \n";
    Toast.makeText(getApplicationContext(), ""+msg , Toast.LENGTH_LONG).show();

}

private void setActionBar() {
    ActionBar mActionBar = getActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(this);
    View mCustomView = mInflater.inflate(R.layout.actionbar_chat, null);
    TextView tv_chat = (TextView)mCustomView.findViewById(R.id.title_text);
    tv_chat.setText(contact_for_chat);
    ColorDrawable colorDaawable = new ColorDrawable(Color.parseColor("#CFCFC4"));
    mActionBar.setBackgroundDrawable(colorDaawable);
    mActionBar.setLogo(R.drawable.ic_launcher);
    mActionBar.setDisplayHomeAsUpEnabled(true);
    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);
}

private void findViewsById() {
    et_chat = (EditText)findViewById(R.id.et_chat);
    btn_send = (Button)findViewById(R.id.button1);
}

private void showEvents(Cursor cursor) {

    item_id = new ArrayList<String>(cursor.getCount());
    item_phone_num = new ArrayList<String>(cursor.getCount());
    item_msg_body = new ArrayList<String>(cursor.getCount());
    item_time = new ArrayList<String>(cursor.getCount());
    item_flag = new ArrayList<String>(cursor.getCount());
    int i=0;
    while (cursor.moveToNext()) {
        item_id.add(i+"");
        item_time.add(cursor.getString(1));
        item_msg_body.add(cursor.getString(3));
        item_phone_num.add(cursor.getString(2));
        item_flag.add(cursor.getString(4));
        i++;
    }

  }
public class MyListAdapter extends BaseAdapter {
    Context con;
    private LayoutInflater layoutinf;
    ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
    ArrayList<String> items_ = new ArrayList<String>();

    public MyListAdapter(ChatActivity context) {
        con = context;
    }

    public int getCount() {
        return item_id.size();
    }

    public Object getItem(int position) {
        return item_id.size();
    }

    public long getItemId(int position) {
        return item_id.get(position).hashCode();
    }

    public View getView(final int position, View arg1, ViewGroup arg2) {

        View v = arg1;
        ViewHolder holder = null;
        if (v == null) {
            layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = layoutinf.inflate(R.layout.row_chat, null);
            holder = new ViewHolder();

            holder.tv_contact = (TextView) v.findViewById(R.id.phone_num);
            holder.tv_sms_body = (TextView) v.findViewById(R.id.msg_body);
            holder.tv_time = (TextView) v.findViewById(R.id.time);

            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        if(item_flag.get(position).equals("1"))
        {
            holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);

        }
                    else
                    {
                        holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_yellow);

                    }


        holder.tv_contact.setText("" + item_phone_num.get(position));


        holder.tv_sms_body.setText(item_msg_body.get(position));

        holder.tv_time.setText(item_time.get(position));

        return v;
    }
}

public class ViewHolder {

    private TextView tv_contact;
    private TextView tv_sms_body;
    private TextView tv_time;

}

检索短信的数据库游标如下:

public Cursor Return_SMS(String contact_no)
    {       
        SQLiteDatabase db=this.getReadableDatabase();        
        String[] params=new String[]{contact_no};
        Cursor c=db.rawQuery("SELECT * FROM "+ "SMS_TABLE_RCV"+" WHERE "+ "Phone_number " +"=?",params);
        return c;
    }

我不知道我的代码有什么问题,以及如何检索收到和发送的短信但背景不同。 任何帮助将不胜感激。

【问题讨论】:

    标签: android android-listview android-sqlite ssms


    【解决方案1】:

    我建议你使用LoadersProvider

    有了它们,只要对 DB 的数据进行更改,您的视图就会更新。

    第一次相当困难,但随后在 API 10 之后的所有设备中都很容易且稳定。

    小例子: 在onCreate Fragment extends ListFragment

       getActivity().getSupportLoaderManager().initLoader(MyProvider.LOADER_ID, null, this);
    
       mCursorAdapter = new SimpleCursorAdapter(
                getActivity(),
                R.layout.my_row_layout,
                null,
                new String[]{"DBcolumnName1", "DBcolumnName2"},
                new int[]{
                        R.id.my_textView,
                        R.id.my_textView2},
                SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); //get update
    
        DocumentoCursorAdapter adapter = new DocumentoCursorAdapter(getActivity());
    
        mCursorAdapter.setViewBinder(adapter);
    

    那么片段必须implements LoaderManager.LoaderCallbacks&lt;Cursor&gt;并实现接口:

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        String condition = null;
        String[] args = null;
        if (bundle!=null) {
            final String search = bundle.getString(BUNDLE_SEARCH);
    
            condition = DbMapping.myColumn1.name() + " LIKE ? OR " +
                    DbMapping.myColumn2.name() + " LIKE ?";
            args = new String[]{'%'+search+'%', '%'+search+'%'};
        }
    
        return new CursorLoader(
                getActivity().getApplicationContext(),
                MyProvider.CONTENT_URI,
                new String[]{"DBcolumnName1", "DBcolumnName2"}, // selectable columns
                condition,
                args,
                DbMapping.myColumn1.name() + " DESC");
    }
    
    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        switch (cursorLoader.getId()) {
            case MyProvider.LOADER_ID:
                mCursorAdapter.swapCursor(cursor);
                break;
        }
    }
    
    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        mCursorAdapter.swapCursor(null);
    }
    

    最后你必须写你的数据提供者

    public class MyProvider extends ContentProvider {...}
    

    并重写一些这样的方法:

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        final int uriType = sURIMatcher.match(uri);
        Log.d(TAG, "Richiesto UPDATE "+ selectionArgs[0]);
    
        SQLiteDatabase sqlDB = mDbHelper.getWritableDatabase();
        int updated;
        switch (uriType) {
            case INDICATOR_UPDATE_DOCUMENTO:
                updated = sqlDB.update(DbMapping.MY_TABLE_NAME,
                        values,
                        DbMapping._id.name() +"= ?",
                        selectionArgs);
                break;
    
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        if (updated>=0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
    
        return updated;
    }
    

    神奇的是这条getContext().getContentResolver().notifyChange(uri, null); 通知加载器更新视图。

    所以你必须更新数据库,视图会自动更新!!

    使用这种模式(加载程序和数据提供程序),您将永远不会拥有 db 异常访问权限,并且您永远不必编写额外的代码来更新视图!

    【讨论】:

      【解决方案2】:

      对于android中的这种短信视图..

      您需要在代码中进行更改,例如

      您可以在您的 sqllite 数据库代码的 Return_all() 函数中添加 where 子句。调用 return_all() 时传递 where 的值。

      喜欢

      public Cursor Return_All(Arraylist Where){
      
      SQLiteDatabase db = this.getReadableDatabase();
      String query= "where ";
      For(int i=0;i<where.size;i++)
      {
           query=query+"contact = "+where[i]+ " or "; }
      

      光标 cur = db.rawQuery("SELECT * FROM "+"SMS_TABLE_RCV" + query , null); 返回当前; }

      或者尝试这些以供参考..

      1.android Custom list veiw

      2.Create Custom Listview

      3.Customize list view

      遵循这些参考并将它们用于 SQLite...

      【讨论】:

      【解决方案3】:

      我尝试了很多,终于得到了问题和解决方案。实际上问题在于发件人号码的更改模式。您会注意到,当您在模拟器中保存号码时,它会保存为 1 555-521-5556,而当收到短信时,则保存为 15555215556,这是基本问题。您必须处理它或直接使用联系人姓名来摆脱此解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        • 2018-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多