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);
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 trying to build up a application which has a custom adapter and all ListView row has three Button. I have onClick operation for all Button in custom adapter. I can change the data source when Button clicked however I can not reload the data from custom adapter.
public class CallListViewCustomAdapter extends ArrayAdapter<Person> {
Context context;
SQLiteDatabase sb;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private static final String SAMPLE_TABLE_NAME = "calldetails";
int layoutResourceId;
ArrayList<Person> data = new ArrayList<Person>();
public CallListViewCustomAdapter(Context context, int layoutResourceId, ArrayList<Person> data) {
super(context, layoutResourceId,data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void refresh(ArrayList<Person>list)
{
data = list;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
View row = convertView;
final int fPosition = position;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
final WeatherHolder holder = new WeatherHolder();
holder.phoneNumber = (TextView)row.findViewById(R.id.number);
holder.fname = (TextView)row.findViewById(R.id.fName);
holder.call = (Button)row.findViewById(R.id.callButton);
holder.skip = (Button)row.findViewById(R.id.skip);
holder.called = (Button)row.findViewById(R.id.called);
holder.called.setTag(position);
Person weather = data.get(position);
holder.phoneNumber.setText(weather.number);
holder.fname.setText(weather.fName);
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.called.setVisibility(View.VISIBLE);///error comes
holder.skip.setVisibility(View.VISIBLE);///error comes
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + data.get(fPosition).number));
callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);
}
});
holder.called.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//business logic for data source change
refresh(data);///I want listview change here
sb.close();
Log.v("ONMESSAGE", "HARD");
}
});
// holder.desc= (TextView)row.findViewById(R.id.txtViewDescription);
// holder.switchState = (Switch)row.findViewById(R.id.switch1);
row.setTag(holder);
}
return row;
}
static class WeatherHolder
{
TextView phoneNumber;
TextView fname;
Switch switchState;
Button call,skip,called;
}
}
Fragment where The list is used
public class NewFragment extends Fragment{
View rootView;
ProgressDialog pDialog;
private ListView listView1;
CallListViewCustomAdapter adapter;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private SQLiteDatabase sampleDB;
ArrayList<Person>list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout.newfragment, container, false);
initDB();
list = new ArrayList<Person>();
new CallLogDetails().execute();
return rootView;
}
public int checkTable() {
int return_var = 0;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " + "calldetails", null);
if (cc != null){
if (cc.moveToFirst()) {
do {
return_var = cc.getInt(1);
} while (cc.moveToNext());
}
}
return return_var;
}
public void parseandStoreOpearation()
{
try{
CSVReader reader = new CSVReader(new InputStreamReader(getActivity().getAssets().open("batch2.csv")));
String [] nextLine;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
while ((nextLine = reader.readNext()) != null) {
//Log.v("ONMESSAGE", "YES");
Log.v("ONMESSAGE", "Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
if(!nextLine[0].equals("First Name"))
{
//Person newPerson = new Person(nextLine[0],nextLine[1], nextLine[2], 1);
ContentValues cv = new ContentValues();
cv.put("callNumber", nextLine[2]);
cv.put("fName", nextLine[0]);
cv.put("lName", nextLine[1]);
cv.put("callflag", 1);
sampleDB.insert("calldetails", null, cv);
//list.add(newPerson);
}
}
}
catch(Exception e)
{
Log.v("ONMESSAGE", "EXCEPTION " + e.toString());
}
}
public ArrayList<Person> getList()
{
ArrayList<Person> arr = new ArrayList<Person>();
sampleDB= getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " +"calldetails", null);
if(cc != null)
if(cc.moveToFirst()){
do
{ Log.v("Datas",cc.getString(2)+ " " +cc.getString(3) + " " + cc.getString(1) + " " + cc.getInt(4));
Person ph = new Person(cc.getString(2), cc.getString(3), cc.getString(1),cc.getInt(4),cc.getInt(0));
arr.add(ph);
}while(cc.moveToNext());
}
sampleDB.close();
Log.v("ONMESSAGE", new Integer(arr.size()).toString());
return arr;
}
private void initDB() {
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
"calldetails" +" (callid INTEGER PRIMARY KEY AUTOINCREMENT,"+ "callNumber TEXT," +
" fName TEXT," + "lName TEXT," + "callflag INTEGER);");
}
private class CallLogDetails extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Processing");
pDialog.setMessage("Loading Number List");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected void onPostExecute(Void params){
super.onPostExecute(params);
pDialog.dismiss();
if(list.size() == 0)
{
list.add(new Person("No Data", "NO Data", "No Data", 0,0));
}
Collections.reverse(list);
if(adapter != null)
adapter.clear();
adapter = new CallListViewCustomAdapter(getActivity(),
R.layout.listview_row, list);
listView1 = (ListView)getActivity().findViewById(R.id.lvAlbumList);
listView1.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Delete Record");
builder.setMessage("Do you want to delete the record?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if(list.size() > 0){
sampleDB=getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
//sampleDB.execSQL("DELETE FROM "+ SAMPLE_DB_NAME + " " + "WHERE callDesc= " + desc);
//sampleDB.execSQL("DELETE FROM calldetails WHERE callDesc='"+desc+"';");
Toast.makeText(getActivity(), "Row Deleted", Toast.LENGTH_LONG).show();
sampleDB.close();
new CallLogDetails().execute();
}
else
Toast.makeText(getActivity(), "This is a default object. You can not delete this.", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.cancel();
}
});
builder.show();
return false;
}
});
listView1.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... arg0) {
list.clear();
if(checkTable() == 0)
{
parseandStoreOpearation();
}
list = getList();
Log.v("ONMESSAGE", "Doing");
return null;
}
}
}
For an ArrayAdapter, notifyDataSetChanged() only works if you use the add, insert, remove, and clear functions on the Adapter.
Try following code:
public void refresh(ArrayList<Person>list)
{
data.clear();
data.addAll(list);
this.notifyDataSetChanged();
}
Do something like this inside activity
CallListViewCustomAdapter thadapter=new CallListViewCustomAdapter(MainActivity.this, R.layout.list,numAl);
NumberList.setAdapter(thadapter);
#Override
public void onClick(View v) {
thadapter.notifyDataSetChanged();
}
});
Call notifyDataSetChanged() and recall adapter
Call notifyDataSetChanged() method to the ListView adapter object.
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 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