0

I'm working on a message application and wanna update my custom listView when new message arrive. I have tried several ways to do that but was unsuccessful ...please help with complete description cause m new to android. Here my code

public class SMSBroadcastReceiver extends BroadcastReceiver {
    Messages message1;
    MessageDbHelper db;
    Context context=null;
    SmsInboxList smsInboxList;
    BroadcastReceiver br;
    //  ADapter adap;
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    IntentFilter intentFilter=new IntentFilter(ACTION);

    @SuppressLint("SimpleDateFormat")
    @Override
    public void onReceive(Context context, Intent intent) {

        // Retrieves a map of extended data from the intent.
        Bundle bundle = intent.getExtras();
        message1 = new Messages();
        this.context=context;
        //      context = context.getApplicationContext();
        smsInboxList = new SmsInboxList();
        //      adap=new ADapter(context, R.id.listView_Conversation);
        MessageDbHelper dbMessagedbHelper = new MessageDbHelper(context, null,null, 0);
        db = dbMessagedbHelper;

        try {

            if (bundle != null) {

                Object[] pdusObj = (Object[]) bundle.get("pdus");

                for (int i = 0; i < pdusObj.length; i++) {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();
                    Long localLong = Long.valueOf(currentMessage.getTimestampMillis());
                    String datae = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(localLong.longValue()));

                    /*****************
                     ** @here we getting data for notification
                     **
                     **/
                    try {
                        message1.body(message);
                        message1.number(senderNum);
                        message1.date(datae);
                        message1.type("1");
                        Log.i(""    ,   "body++++++++++++++++" + message1.body);
                        Log.i(""    ,   "num+++++++++++" + message1.number);
                        Log.i(""    ,   "date+++++++++++" + message1.date);
                        Log.i(""    ,   "typeeee++++++++++++" + message1.type);
                        db.insertDataInMsgTable(message1);
                        createNotification(context, message1);

                    } catch (Exception e) {
                        Log.i("", "except" + e);

                    }
                    Log.i("SmsReceiver", "senderNum: " + senderNum
                            + "; message: " + message);
                }
            }
        }
    }

    public void createNotification(Context context, Messages message1) {

        Log.i("", "get body====" + message1.body + "---" + message1.number);
        Intent intent = new Intent(context, SmsInboxList.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
        Notification notification = new NotificationCompat.Builder(context)
                .setContentTitle("From: " + message1.number)
                .setContentText(message1.body).setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.app_icon).build();

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        notification.flags |= Notification.DEFAULT_LIGHTS;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        manager.notify(0, notification);

        try
        {
        smsInboxList.adap.notifyDataSetChanged();
        }
        catch(Exception e)
        {
            Log.i("", "error in addd==="+e);
            e.printStackTrace();
        }
    }   
}       

And main activity class is

public class SmsInboxList extends Activity {

    public ListView listView;
    public SmsInboxListAdapter adap ;
    Contact con;
    MessageDbHelper dbhelper;
    ProgressBar prob;
    LinearLayout rell;
    public static TextView newMsg;
    ImageView imgv;
    ImageView imgv1;
    ProgressBar pd;
    Dialog dialog;

    ArrayList<Messages> arrList = new ArrayList<Messages>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_sms_inbox_list);
        pd = new ProgressBar(SmsInboxList.this);

        pd = (ProgressBar) findViewById(R.id.progressBar_Inbox);

        dbhelper = new MessageDbHelper(this, null, null, 0);
        dbhelper.cleartable();
        Log.i("", "qwertyu==" + dbhelper.getAllreceive().size());
        listView = (ListView) findViewById(R.id.listView_Conversation);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position,
                    long arg3) {

                // TextView number=(TextView)findViewById(R.id.textViewName);

                String addr = arrList.get(position).number; // number.getText().toString();
                Log.i("" + position, "intent no==" + addr);
                Intent intent = new Intent(getApplicationContext(),ConversationChat.class);

                try {
                    String key_num = "numbrr";
                    intent.putExtra(key_num, addr);
                    Log.i("", "in intent put===" + addr);
                } catch (Exception e) {
                    Log.i("", "putExtra==" + e);
                }
                startActivity(intent);

            }
        });
        // prob=(ProgressBar)findViewById(R.id.progressBarInbox);
        rell = (LinearLayout) findViewById(R.id.relativeLayout_sent);
        imgv = (ImageView) findViewById(R.id.imageView_Setting);
        imgv1 = (ImageView) findViewById(R.id.imageView_Compose);
        newMsg = (TextView) findViewById(R.id.textView_Compose_new_message);
        imgv1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),
                        SendMessage.class);
                startActivity(intent);

            }
        });
        newMsg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),
                        SendMessage.class);
                startActivity(intent);

            }
        });
        // ////////////////////////////////////
        // /////////////////////////////////////////////////////////////////////////////////
        imgv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //              Intent intent = new Intent(getApplicationContext(),FilterAct.class);
                //              startActivity(intent);
                 dialog=new Dialog(SmsInboxList.this);
                 dialog.setContentView(R.layout.activity_chat_theme);
                 dialog.setTitle("List");
                 ListView
                 listView=(ListView)dialog.findViewById(R.id.listView_chatTheme);

                 ArrayList<Messagesss> arr=new ArrayList<Messagesss>();
                 ArrayList<Messagesss> arr_sent=new ArrayList<Messagesss>();
                 final int
                 image_rec[]={R.drawable.recieve,R.drawable.receive_rec,R.drawable.rec_recei};
                 final int
                 image_sent[]={R.drawable.sentbubble,R.drawable.sent_rec,R.drawable.rec_sent};
                 for(int j=0;j<image_sent.length;j++)
                 {
                 Messagesss msg1=new Messagesss();
                 msg1.resid=image_sent[j];
                 arr_sent.add(msg1);
                 }
                 for(int i=0;i<image_rec.length;i++)
                 {
                 Messagesss msg=new Messagesss();
                 msg.resid=image_rec[i];
                 arr.add(msg);

                 }


                 final CategoryListAdapter1 adapter=new
                 CategoryListAdapter1(SmsInboxList.this,
                 R.id.listView_chatTheme,arr);
                 try{
                 listView.setAdapter(adapter);
                 }
                 catch(Exception e){
                 Log.i("", "error in adapter call"+e);
                 }
                 dialog.show();


                 listView.setOnItemClickListener(new
                 AdapterView.OnItemClickListener() {

                 @Override
                 public void onItemClick(AdapterView<?> arg0, View arg1,
                 int position, long arg3) {


                 int val=adapter.getItem(position).resid;
                 Log.i("", ""+val);




                 Log.i("",
                 "adapter value======"+adapter.getItem(position).resid);
                 SharedPreferences mPrefs;
                 SharedPreferences.Editor editor;
                 mPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                 editor = mPrefs.edit();


                 editor.putInt("hell_receive", image_rec[position]);
                 editor.putInt("hell_sent", image_sent[position]);
                 editor.commit();

                 dialog.dismiss();
                 }
                 });

            }
        });

        // /////////////////////////////////////////////////////
        // //////////////////////////////////////////////
        //      try {
        //          new ProgressTas().execute("");
        //      } catch (Exception e) {
        //          Log.i("", "error Progress Task==" + e);
        //      }

         try{ 
             getSMSInbox(); 
             } 
         catch(Exception e)
         {
         Log.i("","getSMSInboxttry"+e);

          }


        ArrayList<Messages> mymsg = new ArrayList<Messages>(
                dbhelper.getAllreceive());

        dbhelper.insertDataInMsgTablePrimaryKey(mymsg);
        dbhelper.getAllreceiveCommon();

        for (int i = 0; i < mymsg.size(); i++) {
            Log.i("" + i, "my dataaaa mymsg=====" + mymsg.get(i).number + "---"
                    + mymsg.get(i).body + "---" + mymsg.get(i).type);

        }
        try{
            addItem(listView);
        }
        catch(Exception e)
        {
            Log.i("", "error in call of addItem in smsInbox"+e);
        }

        /*
         * Log.i("", "size my msg =="+mymsg.size()); ArrayList<Messages>
         * testArr=new ArrayList<Messages>(dbhelper.getAllreceiveCommon());
         * 
         * for(int i=0;i<testArr.size();i++) { Log.i(""+i,
         * "my dataaaa mymsg test====="
         * +testArr.get(i).number+"---"+testArr.get(i
         * ).body+"---"+testArr.get(i).type);
         * 
         * }
         */
        //      setup();
        //      updateUi(mymsg);
    }

    public void chatTheme(){

    }

    @SuppressWarnings({ "deprecation" })
    public List<String> getSMSInbox() {

        List<String> sms2 = new ArrayList<String>();

        Uri uri = Uri.parse("content://sms");
        Cursor c = getContentResolver().query(uri, null, null, null, null);
        startManagingCursor(c);
        arrList.clear();
        // Read the msg data and store it in the list
        if (c.moveToFirst()) {

            for (int i = 0; i < c.getCount(); i++) {

                Messages mssg = new Messages();
                mssg.set_type("" + c.getString(c.getColumnIndexOrThrow("type")));
                mssg.set_person(""
                        + c.getString(c.getColumnIndexOrThrow("person")));
                mssg.set_number(""
                        + c.getString(c.getColumnIndexOrThrow("address")));
                mssg.set_body("" + c.getString(c.getColumnIndexOrThrow("body")));
                mssg.set_date(""
                        + Functions.getTimefromMS(c.getString(c
                                .getColumnIndexOrThrow("date"))));
                //  Log.i(""+c.getString(c.getColumnIndexOrThrow("type")),
                //  "message==="+c.getString(c.getColumnIndexOrThrow("body")));
                // Log.i(""+c.getString(c.getColumnIndexOrThrow("_id")),
                // "reply path==="+c.getString(c.getColumnIndexOrThrow("reply_path_present")));

                Log.i("SmsInboxList method part ",
                                  "type===="+ c.getString(c.getColumnIndexOrThrow("type"))
                                + "name===="+ c.getString(c.getColumnIndexOrThrow("person"))
                                + "number=="+ c.getString(c.getColumnIndexOrThrow("address"))
                                + "body===="+ c.getString(c.getColumnIndexOrThrow("body"))
                                + "date===="+ c.getString(4));

                dbhelper.insertDataInMsgTable(mssg);

                c.moveToNext();
            }
        }
        /*
         * this is very important to dont close cursor if u dont wanna perform
         * next activity and backtrack to previous activity
         */
        // c.close();

        // Set smsList in the arrList
            adap = new SmsInboxListAdapter(getApplicationContext(), R.id.listView_Conversation);
            dbhelper.insertDataInMsgTablePrimaryKey(dbhelper.getAllreceive()); 
            arrList=new ArrayList<Messages>(dbhelper.getAllreceiveCommon());
            Log.i("", "size cmn=="+arrList.size());
         //   listView.removeAllViews();
            try {
                    try{
                    adap.notifyDataSetChanged();
                    }
                    catch(Exception e)
                    {
                        Log.i("", "error in notify dataset"+e);
                    }
                listView.setAdapter(adap);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
                } 
                catch (Exception e) {
                    Log.i("", "listView" + e);
                }
                for (int i = 0; i < arrList.size(); i++)
                {
                    adap.add(arrList.get(i));
                    Log.i("", "oyee!!!");
                        try{
                        adap.notifyDataSetChanged();
                        }
                        catch(Exception e)
                        {
                            Log.i("", "error in notify in smsInboxList=="+e);
                        }
                }
            Button button=(Button)findViewById(R.id.btn_notify);
            button.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                        getSMSInbox();
                        Log.i("", "getSmsInbox size of array list=="+arrList.size());
                    }catch(Exception e)
                    {
                        Log.i("", "error in notify click");
                        e.printStackTrace();
                    }

                }
            });

        return sms2;
        //
    }
}
4

2 回答 2

3

利用

listView.invalidate();

在您对列表进行更改后

例如。您在 listView 中添加/删除/更新了数据。

于 2013-10-03T13:30:57.477 回答
0

只是一个想法:

将您的代码public CategoryListAdapter1 adapter;称为全局代码。

adapter.notifyDataSetChanged();每当您的列表要刷新时使用。

于 2013-10-04T05:59:25.673 回答