I am creating SMS app. I am sending and receiving SMS with my application and then can show them in ListView. But listview doesn't get updated as soon as I send or receive SMS. I have to press back button , after that if I again go to ListView Activity then new SMS are shown.
How can I make listview refresh automatically as soon as sms arrives or is send ?
Code is :
public class ChatActivity extends ListActivity {
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_main);
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_All(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();
}
});
}
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.btn_send);
}
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;
}
}
you should register a broadcast receiver to get notified upon receiving an SMS and in the onReceive of this receiver you can get new data from cursor and refresh the list view.
To know more about receiver try:
http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87
You have to use notifydatasetchanged. check out following link.
https://stackoverflow.com/a/12229903/2930834
Related
I am new to android development and must take the value of the id in the clicked item database.
Already searched several posts but not found the answer .
Below is my code Listview :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seleciona_jogador_act);
final BancoController bc = new BancoController(this);
final ArrayList<JogadorEntidade> jogadorEntidade = bc.arrayJogador(this);
listView = (ListView) findViewById(R.id.lvSelecionar);
final SelecionaAdapter adapter = new SelecionaAdapter(this, R.layout.adapter_seleciona, jogadorEntidade);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(background));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertInserirJogador(SelecionaJogadorAct.this);
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//I NEED THIS CODE
Context context = getApplicationContext();
CharSequence text = "ID: " + ", Posicao: " + position;
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
//bc.deletaRegistro(id_player);
Intent intent = getIntent();
SelecionaJogadorAct.this.finish();
startActivity(intent);
}
});
}
My Adapter:
public class SelecionaAdapter extends ArrayAdapter<JogadorEntidade> {
Context context;
int layoutID;
ArrayList<JogadorEntidade> alJogador;
public SelecionaAdapter(Context context, int layoutID, ArrayList<JogadorEntidade> alJogador){
super(context, layoutID, alJogador);
this.context = context;
this.alJogador = alJogador;
this.layoutID = layoutID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
PlayerHolder holder = null;
if (row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutID, parent, false);
holder = new PlayerHolder();
holder.txtNome = (TextView)row.findViewById(R.id.txtNomeSelecionar);
holder.txtVitorias = (TextView)row.findViewById(R.id.txtVitóriasSelecionar);
holder.txtDerrotas = (TextView)row.findViewById(R.id.txtDerrotasSelecionar);
row.setTag(holder);
}else {
holder = (PlayerHolder)row.getTag();
}
JogadorEntidade jogadorEntidade = alJogador.get(position);
holder.txtNome.setText(jogadorEntidade.getNome());
holder.txtVitorias.setText("V: " + jogadorEntidade.vitórias);
holder.txtDerrotas.setText("D: " + jogadorEntidade.derrotas);
return row;
}
static class PlayerHolder{
TextView txtNome;
TextView txtVitorias;
TextView txtDerrotas;
}
JogadorEntidade:
public class JogadorEntidade {
public String nome;
public Integer id_jogador;
public String vitórias;
public String derrotas;
public Integer getId_jogador() {
return id_jogador;
}
public void setId_player(int id_player) {
this.id_jogador = id_player;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getVitórias() {
return vitórias;
}
public void setVitórias(String vitórias) {
this.vitórias = vitórias;
}
public String getDerrotas() {
return derrotas;
}
public void setDerrotas(String derrotas) {
this.derrotas = derrotas;
}
public JogadorEntidade(String nome, String vitórias, String derrotas){
super();
this.nome = nome;
this.vitórias = vitórias;
this.derrotas = derrotas;
}
public JogadorEntidade(){}
public void insereJogador(JogadorEntidade jogadorEntidade) {
db = banco.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(banco.NOME_JOGADOR, jogadorEntidade.getNome());
values.put(banco.VITORIAS, jogadorEntidade.getVitórias());
values.put(banco.DERROTAS, jogadorEntidade.getDerrotas());
db.insert(CriaBanco.TABELA_JOGADOR, null, values);
db.close();
}
public Cursor carregaJogador() {
Cursor cursor;
String[] campos = {banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
db = banco.getReadableDatabase();
cursor = db.query(banco.TABELA_JOGADOR, campos, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
db.close();
return cursor;
}
public void deletaRegistro(int id){
String where = CriaBanco.ID_JOGADOR + "=" + id;
db = banco.getReadableDatabase();
db.delete(CriaBanco.TABELA_JOGADOR, where, null);
db.close();
}
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
JogadorEntidade jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
First you need to request the id when making the query (if the id is the one created in the database the column mame is _id or you can use tablename._id or whatever you need):
String[] campos = {"_id", banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
Then you need to add the id to the object when you read the cursor:
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
JogadorEntidade jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
Anyway this is not the way to go in android. You should read all the list and then show it. You should use the viewholder pattern and only load the player when you are going to show it. Also instead of using a list you should move to recyclerviews. Listviews can be consider deprecated at this point. See the tutorial: http://developer.android.com/training/material/lists-cards.html
In my Android application, I have a List of Phone Contacts. I want to add these contacts in private list by selection through CheckBoxe and onButtonClick. What I want here is that if contacts are already present there in database then they should not be added. How can i do so ? Please help.
Here is the code :
private MyListAdapter adapter;
ArrayList<String> item_id = new ArrayList<String>();
ArrayList<String> item_contact_name = new ArrayList<String>();
ArrayList<String> filteredList = new ArrayList<String>();
ArrayList<String> item_contact_number = new ArrayList<String>();
Uri queryUri;
boolean flag = false;
boolean[] selection;
static ArrayList<String> selection_val;
private Button btn_select, btn_remove;
DbManager manager;
String[] contactArray;
Cursor Cursor, cursor1;
public static String[] selectedData;
String phoneNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contacts);
manager = new DbManager(this);
try{
queryUri = ContactsContract.Contacts.CONTENT_URI;
//String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
Cursor Cursor = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
showEvents(Cursor);
cursor1 = manager.Return_All_Contacts();
contactArray = showEvents2(cursor1);
//final ViewHolder holder = new ViewHolder();
selection = new boolean[item_id.size()];
selection_val = new ArrayList<String>();
selectedData=new String[selection.length];
adapter = new MyListAdapter(this);
setListAdapter(adapter);
btn_select = (Button) findViewById(R.id.button1);
btn_select.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
// selectedData[i]=item_msg_body.get(i);
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
try{
addContacts(selectedData);
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(
getApplicationContext(),
"Your have Selected " + cnt + " ids. " + " "+ selectIds, Toast.LENGTH_LONG).show();
}
}
});
}
catch(Exception ex)
{
Log.e("Error in retrieving phone", ex.toString());
}
btn_remove = (Button)findViewById(R.id.remove);
btn_remove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
deleteMultiple(selectedData);
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
} else {
}
}
});
}
public class MyListAdapter extends BaseAdapter{
Context con;
private LayoutInflater layoutinf;
ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
ArrayList<String> items_ = new ArrayList<String>();
public MyListAdapter(
privateContacts sample_MultipleSelectionActivity) {
con = sample_MultipleSelectionActivity;
}
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 convertView, ViewGroup arg2) {
View v = convertView;
ViewHolder holder = null;
if (v == null) {
layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_add_contacts, null);
holder = new ViewHolder();
holder.chk = (CheckBox) v.findViewById(R.id.checkBox);
holder.tv_contact_name = (TextView) v.findViewById(R.id.tvname);
holder.tv_number = (TextView) v.findViewById(R.id.tvphone);
holder.iv_contact = (ImageView) v.findViewById(R.id.iv_contacts);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.chk.setId(position);
holder.tv_contact_name.setId(position);
holder.chk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
CheckBox cb = (CheckBox) v;
int id = cb.getId();
String val = cb.getText().toString();
if (selection[id]) {
cb.setChecked(false);
selection[id] = false;
selection_val.remove("" + item_contact_name.get(id));
} else {
cb.setChecked(true);
selection[id] = true;
selection_val.add("" + item_contact_name.get(id));
}
adapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("error", "" + e.toString());
}
}
});
holder.chk.setChecked(selection[position]);
if(selection[position] == true)
{
//holder.tv_contact_name.setBackgroundColor(Color.GRAY);
}
else
{
holder.tv_contact_name.setBackgroundColor(Color.TRANSPARENT);
}
// for(int i=0;i<contactArray.length;i++){
//
// holder.tv_contact_name.setBackgroundColor(Color.GREEN);
// }
//holder.chk.setText(item_id.get(position));
holder.tv_contact_name.setText("" + item_contact_name.get(position));
holder.tv_number.setText("" + item_contact_number.get(position));
return v;
}
}
public class ViewHolder {
private CheckBox chk;
private TextView tv_contact_name;
private TextView tv_number;
private ImageView iv_contact;
}
private void addContacts(final String[] selectedItems) {
try{
manager.open();
manager.Insert_phone_contact(selectedItems);
manager.close();
moveToLogActivity();
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
}
private void showEvents(Cursor cursor) {
item_id = new ArrayList<String>(cursor.getCount());
item_contact_name = new ArrayList<String>(cursor.getCount());
item_contact_number = new ArrayList<String>(cursor.getCount());
//String ContactNames[] = new String[cursor.getCount()];
String id[]=new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
item_contact_name.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
item_contact_number.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
i++;
}
}
private String[] showEvents2(Cursor cursor) {
String addedContacts[]=new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
addedContacts[i] = cursor.getString(1);
i++;
}
return addedContacts;
}
#Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
private void moveToLogActivity() {
Intent i = new Intent(this, LogActivity.class);
startActivity(i);
finish();
}
private void deleteMultiple(String[]selectedItems) {
manager.deleteContactsMultiselected(selectedItems);
moveToLogActivity();
}
The database code where i am saving data is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
if (contact[i] !=null){
cv.put(CONTACT_NAME, ""+contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}// insert in db
}
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
ContactTable code in database is as :
// define table name
public static final String TABLE_CONTACTS = "CONTACTS_TABLE";
//define column of TABLE_CONTACTS
public static final String KEY_CONTACTID = "_id";
public static final String CONTACT_NAME = "Contact_name";
I am developing SMS application. I have declared receiver in manifest as follows :
<receiver android:name="com.android.discrete.main.IncomingSMS" >
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
class for broadcastReceiver is as follows :
public class IncomingSMS extends BroadcastReceiver {
Context context;
DbManager DBmanager;
private long timestamp;
private String number;
static String body = "";
String msg="";
Cursor cursor;
String display_name;
String flag;
ChatActivity obj_chat;
#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 ,display_name,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();
}
}
This works fine as i can receive SMS and save it in SQLite database.
Now i have another activity having ListView in which i want to update as soon as new SMS is received and activity is in foreground. Code is as follows:
public class ChatActivity extends Activity {
Context context;
DbManager DBmanager;
private long timestamp;
private String number;
static String body = "";
//String msg="";
Cursor cursor;
String display_name;
//String flag;
static MyListAdapter adapter;
static ArrayList<String> item_id;
static ArrayList<String> item_phone_num;
static ArrayList<String> item_msg_body;
static ArrayList<String> item_time;
static ArrayList<String> item_flag;
static ArrayList<String> items;
private Button btn_send;
DbManager manager;
Cursor Cursor,cursor_new;
//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 = "";
ListView lv_chat;
int position;
String[] from = new String[]{"Message_body","Time"};
int[] toIDs = new int[]{R.id.msg_body,R.id.time};
BroadcastReceiver IncomingSMS = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateList();
}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
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();
manager = new DbManager(this);
Cursor = manager.Return_SMS(contact_for_chat);
c = Calendar.getInstance();
sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
time = sdf.format(c.getTime());
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());
findViews();
showList();
//setActionBar();
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SendSMS();
showList();
//updateList() ;
}
});
lv_chat.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
int itemId = Integer.valueOf(String.valueOf(position));
Cursor.moveToPosition(itemId);
int messageId = Cursor.getInt(0);
deleteMessage(messageId);
}});
}
private void showList() {
showEvents(Cursor);
adapter = new MyListAdapter(this,R.layout.activity_chat, Cursor, from,
toIDs);
lv_chat.setAdapter(adapter);
//updateList() ;
}
private void findViews() {
et_chat = (EditText)findViewById(R.id.et_chat);
btn_send = (Button)findViewById(R.id.button1);
lv_chat = (ListView)findViewById(R.id.list);
lv_chat.setDivider(this.getResources().getDrawable(android.R.color.transparent));
}
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_for_chat, message_body,flag);
if(message_body.length()>0)
{
et_chat.setText("");
}
updateList() ;
}
private void showEvents(Cursor cursor) {
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 SimpleCursorAdapter {
Cursor myCursor;
Context myContext;
public MyListAdapter(Context context, int layout,
Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
myCursor = c;
myContext = context;
}
public int getCount() {
return item_msg_body.size();
}
public Object getItem(int position) {
return item_msg_body.get(position);
}
public long getItemId(int position) {
return item_msg_body.get(position).hashCode();
}
public View getView(final int position, View arg1, ViewGroup arg2) {
View v = arg1;
ViewHolder holder = null;
if (v == null) {
LayoutInflater 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"))
{
RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
RelativeLayout.LayoutParams dateparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dateparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
dateparams.addRule(RelativeLayout.BELOW, R.id.msg_body);
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);
holder.tv_sms_body.setLayoutParams(params);
holder.tv_time.setLayoutParams(dateparams);
}
else if(item_flag.get(position).equals("0"))
{
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 void updateList()
{
item_id.clear();
item_time.clear();
item_msg_body.clear();
item_phone_num.clear();
item_flag.clear();
Cursor = manager.Return_SMS(contact_for_chat);
showEvents(Cursor);
adapter = new MyListAdapter(this,R.layout.activity_chat, Cursor, from,
toIDs);
lv_chat.setAdapter(adapter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(IncomingSMS);
}
#Override
protected void onResume() {
//registerReceiver(IncomingSMS, null);
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(IncomingSMS, filter);
updateList();
super.onResume();
}
Problem is that when i receive SMS then ListView is updated automatically but result is not as expected.When SMS is received then it combines previous SMS with new one i.e see in this image fisrt SMS was "Hi" second SMS was "How are you" but its combines both SMS as "Hi How are you". What is the reason ? How it can be fixed ????
Any help will be appreciated .
I would suggest you to use Cursor Loader here are some tutorial :-
http://www.androiddesignpatterns.com/2012/07/understanding-loadermanager.html
http://www.vogella.com/tutorials/AndroidSQLite/article.html
so your app design would be like this :-
(new sms) ----> (broadcast reciever inserts into db) -----> (cursor loader will refresh your foreground activity)
i am try to send sms after fetching contacts from the phone book. My message is fixed(that is have to send) but the number depends on the users choice.
String smsNumber = " " ;
String smsText = "Hello Please";
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
I am using this, but how do i send sms to the selected person/persons .
public class ContactList extends ListActivity {
/** Called when the activity is first created. */
private ArrayList<contact> contact_list = null;
private ProgressDialog mProgressDialog = null;
private contactAdapter mContactAdapter = null;
private Runnable mViewcontacts = null;
private ArrayList<contact> items;
boolean[] isChecked;
Cursor mCursor;
ListView lv;
Button b_alert;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
contact_list = new ArrayList<contact>();
lv = getListView();
mViewcontacts = new Runnable() {
#Override
public void run() {
getContacts();
}
};
Thread thread = new Thread(null, mViewcontacts, "ContactReadBackground");
thread.start();
mProgressDialog = ProgressDialog.show(ContactList.this,
"Please Wait...", "Retriving Contacts...", true);
}
#SuppressWarnings("unused")
private void getContacts() {
try {
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts._ID };
mCursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,
projection, ContactsContract.Contacts.HAS_PHONE_NUMBER
+ "=?", new String[] { "1" },
ContactsContract.Contacts.DISPLAY_NAME);
while (mCursor.moveToNext()) {
contact contact = new contact();
String contactId = mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts._ID));
contact.setContactName(mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contact_list.add(contact);
}
isChecked = new boolean[mCursor.getCount()];
for (int i = 0; i < isChecked.length; i++) {
isChecked[i] = false;
}
this.mContactAdapter = new contactAdapter(this, R.layout.listview,
contact_list);
lv.setAdapter(this.mContactAdapter);
mCursor.close();
runOnUiThread(returnRes);
} catch (Exception e) {
Log.d("getContacts", e.getMessage());
}
}
public class contactAdapter extends ArrayAdapter<contact> {
public contactAdapter(Context context, int textViewResourceId,
ArrayList<contact> items1) {
super(context, textViewResourceId, items1);
items = items1;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder mViewHolder;
mViewHolder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.listview, parent, false);
mViewHolder.cb = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(mViewHolder);
if (isChecked[position] == true)
mViewHolder.cb.setChecked(true);
else
mViewHolder.cb.setChecked(false);
mViewHolder.cb
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean ischecked) {
if (buttonView.isChecked())
isChecked[position] = true;
else
isChecked[position] = false;
}
});
contact contacts = items.get(position);
if (contacts != null) {
if (mViewHolder.cb != null) {
mViewHolder.cb.setText(contacts.getContactName());
}
}
return convertView;
}
}
public class ViewHolder {
CheckBox cb;
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
mContactAdapter.notifyDataSetChanged();
}
};
}
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "Check out this photo:it's via abc:https://www.abc.com/");
sendIntent.setType("vnd.android-dir/mms-sms");
sendIntent.putExtra("address",_phoneNo);//here phoneno is String that contain phone no
startActivity(sendIntent);
I am new to android and creating a ListView that displays a calendar events.By,using the below code it is getting all the events from calendar.But i want only current week events to be displayed in the list view ,Any ideas or answers will be really helpfull for me to proceed in android.
public class Meeting extends Activity {
public ConferenceAdapter adapter;
ListView meetingListView;
static Cursor cursor;
private String description = null;
private String where = null;
public String[] number;
static List<GoogleCalendar> gCalendar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ec_meeting);
adapter = new ConferenceAdapter(this);
readCalendar(this);
meetingListView = (ListView) findViewById(R.id.meetinglistView);
meetingListView.setAdapter(new MeetingListViewAdapter(Meeting.this, adapter, gCalendar));
meetingListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
TextView descriptionId1 = ((TextView) view.findViewById(R.id.descriptionmeeting));
TextView where=((TextView) view.findViewById(R.id.wheretextView));
TextView tittle = ((TextView) view.findViewById(R.id.titlemeeting));
Meeting.this.where=where.getText().toString();
description = descriptionId1.getText().toString();
StringBuffer numbers =new StringBuffer();
String a=Meeting.this.where.replaceAll("-","").replaceAll(" ", "").replaceAll("\\(","").replaceAll("\\)","")+description.replaceAll("-","").replaceAll(" ", "").replaceAll("\\(","").replaceAll("\\)","");
if(a.isEmpty()){
Toast.makeText(getApplicationContext(),"Sorry no conference numbers found", Toast.LENGTH_LONG).show();
}else{
Pattern p = Pattern.compile("[0-9]+[0-9]");
Matcher m = p.matcher(a);
while (m.find()) {
Meeting.this.addComma(numbers,m.group().toString());
}
number = numbers.toString().split(",");
Intent intent = new Intent(Meeting.this,EcConferenceNumber.class);
intent.putExtra("strings", number);
startActivity(intent);
finish();
}
}
});
}
public void addComma(StringBuffer updatedString,String value){
if(updatedString.length() >0 && updatedString != null ){
updatedString.append(",");
}
updatedString.append(value);
}
public static void readCalendar(Context context) {
ConferenceAdapter cAdapter = null;
ContentResolver contentResolver = context.getContentResolver();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String currentDateandTime = sdf.format(new Date());
String presentDate="dtstart.after("+currentDateandTime+")";
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"),
(new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation"})
,null, null,null);
HashSet<String> calendarIds = new HashSet<String>();
gCalendar = new ArrayList<GoogleCalendar>();
try {
System.out.println("Count=" + cursor.getCount());
if (cursor.getCount() > 0) {
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart = cursor.getString(3);
googleCalendar.setDtstart(dtstart);
String dtend = cursor.getString(4);
googleCalendar.setDtend(dtend);
String eventlocation = cursor.getString(5);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// inner class for setting the home screen value to the list view
class MeetingListViewAdapter extends BaseAdapter {
private List<GoogleCalendar> calendars = null;
LayoutInflater inflater = null;
public MeetingListViewAdapter(Activity activity, ConferenceAdapter adapter, List<GoogleCalendar> gCalendar) {
this.calendars = gCalendar;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return calendars.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.calendar_events, null);
TextView titleNameTV = (TextView) vi.findViewById(R.id.titlemeeting);
TextView timeTV = (TextView) vi.findViewById(R.id.profileStepCountTV);
TextView whereTv=(TextView) vi.findViewById(R.id.wheretextView);
TextView descriptionTV = (TextView) vi.findViewById(R.id.descriptionmeeting);
GoogleCalendar calendar = calendars.get(position);
titleNameTV.setText(calendar.getTitle());
descriptionTV.setText(calendar.getDescription());
whereTv.setText(calendar.getEventlocation());
return vi;
}
}
I am having a doubt that,I have to insert all my calendar events in database and get the current week events by using a query or it can be done without inserting calendar events into database.As a beginner any idea will be usefull for me.
I have already answered for that SO i think it might work just pass two dates.
Code:
Calendar calendar = Calendar.getInstance();
if (Build.VERSION.SDK_INT >= 8) {
l_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
l_eventUri = Uri.parse("content://calendar/events");
}
String dtstart = "dtstart";
String dtend = "dtend";
String[] l_projection = new String[] { "title", "dtstart", "dtend" };
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
//StartDate is today 10/28/2013
Date dateCC = formatter.parse("10/28/2013");
calendar.setTime(dateCC);
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("MM/dd/yy hh:mm:ss");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("11/04/2013 23:59:59");
endOfDay.setTime(dateCCC);
Cursor eventCursorr = cr.query(l_eventUri, new String[] { "title",
"dtstart", "dtend" }, "(" + dtstart + ">" + after + " and "
+ dtend + "<" + endOfDay.getTimeInMillis() + ")", null,
"dtstart ASC");