如何使用SQLite数据填充listview?

时间:2014-03-14 08:29:42

标签: android android-listview android-sqlite ssms

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

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

数据成功存储在DB中,之后我想在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;
    }

我不知道我的代码有什么问题,我怎么能收到并发送两个短信,但背景不同。 任何帮助将不胜感激。

3 个答案:

答案 0 :(得分: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<Cursor>并实现接口:

@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);,它通知加载器更新视图。

所以你必须更新olny db,视图会自动更新!!

使用此模式(loader和dataprovider),您将永远不会有db异常访问权限,您将永远不必编写额外的代码来更新视图!

答案 1 :(得分:0)

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

enter image description here

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

您可以在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 "; }

Cursor cur = db.rawQuery(&#34; SELECT * FROM&#34; +&#34; SMS_TABLE_RCV&#34; + query,null);     返回}

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

1。android Custom list veiw

2。Create Custom Listview

3。Customize list view

按照这些引用并将它们用于SQLite ......

答案 2 :(得分:0)

我已经尝试了很多,最后得到了它的问题和解决方案。实际上,发件人编号的变化模式存在问题。您可以注意到,当您在模拟器中保存数字时,它保存为1 555-521-5556,当接收短信然后15555215556时,这是基本问题。你必须处理它或直接使用联系人名称来摆脱这个解决方案。