2013-10-03 29 views
1

我工作的消息應用程序,並想在新消息到達時更新我的​​自定義listView。我已經嘗試了幾種方法來做到這一點,但不成功...請幫助完整的描述原因新的Android。這裏我的代碼`public class SMSBroadcastReceiver extends BroadcastReceiver {如何更新我的自定義listView顯示?

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

公共無效createNotification(上下文上下文中,消息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(); 
    } 

`

和主活動類是

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

//意圖意圖=新意圖( 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(); 
      } 
      }); 

     } 
    }); 

    // ///////////////////////////////////////////////////// 
    // ////////////////////////////////////////////// 

//嘗試{// 新ProgressTas()執行( 「」)。 (錯誤進度任務==「+ 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( 「類型」)), // 「消息===」 + c.getString(c.getColumnIndexOrThrow( 「身體」))); // 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; 
    // 
} 

enter code here 
+0

+1這是我見過的最長的問題之一! – JJ86

回答

2

使用

listView.invalidate(); 

所做的更改後的名單

EG。你已經添加/刪除/更新listView中的數據。

+0

我已經做到了,但它並沒有更新我的列表查看 –

+0

嘿@umer farooq我已經這樣做了,但在我的廣播接收器類的結尾它捕捉到一個異常空指針異常...請幫助 –

+0

@DeepakGupta請張貼相關的代碼。我們沒有時間去瀏覽所有的代碼。 –

0

只是一個想法:

打電話給你的代碼public CategoryListAdapter1 adapter;全球上課。

使用adapter.notifyDataSetChanged();每當你的清單要刷新。

+0

這是不適用於消息適配器私人CategoryListAdapter1適配器;用於聊天圖像我的信息適配器是公開的 –

+0

Yah可以公開使用它。 – Harpreet

+0

它給了我例外=== java.lang.IllegalStateException:系統服務不可用於onCreate之前的活動() –

相關問題