Want to get only current week events from calendar in android? - android

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

Related

How do I get the ID item in the database?

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

How to refresh foreground Activity with incoming SMS?

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)

How to refresh SMS Listview automatically ?

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

How to get events from calendar for particular week in android?

I want to display the events for only one week in the listView,but I got all the events and it is displaying in the listview.
I am using this code to get the events for particular date ,but is not getting any events from calendar.The event count is 0.I am struct with this problem! How to get events for particular date or week?
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;
private static String startString;
private static String endString;
#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) {
ContentResolver contentResolver = context.getContentResolver();
Calendar c_start = Calendar.getInstance();
c_start.set(2014,2,4,0,0); //Note that months start from 0 (January)
Calendar c_end = Calendar.getInstance();
c_end.set(2013,2,11,0,0); //Note that months start from 0 (January)
String selection = "((dtstart >= "+c_start.getTimeInMillis()+") AND (dtend <= "+c_end.getTimeInMillis()+"))";
String[] selectionArgs = new String[] {startString, endString};
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"),
(new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation"})
,null,selectionArgs,selection);
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;
}
}
Any answer will be helpfull for me to proceed.
Replace this code :
ContentResolver contentResolver = context.getContentResolver();
Calendar c_start = Calendar.getInstance();
c_start.set(2014,2,4,0,0); //Note that months start from 0 (January)
Calendar c_end = Calendar.getInstance();
c_end.set(2013,2,11,0,0); //Note that months start from 0 (January)
String selection = "((dtstart >= "+c_start.getTimeInMillis()+") AND (dtend <= "+c_end.getTimeInMillis()+"))";
String[] selectionArgs = new String[] {startString, endString};
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"),
(new String[] { "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation"})
,null,selectionArgs,selection);
With this:
Uri l_eventUri;
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");
}
ContentResolver contentResolver = context.getContentResolver();
String dtstart = "dtstart";
String dtend = "dtend";
String[] l_projection = new String[] { "title", "dtstart", "dtend" };
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
// Date dateCC = formatter.parse("04/27/2013");
Date dateCC = formatter.parse("11/13/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("17/13/2013 23:59:59");
// Date dateCCC = formatterr.parse(startDate + " 23:59:59");
endOfDay.setTime(dateCCC);
cursor= contentResolver.query(l_eventUri, new String[] { "title",
"dtstart", "dtend" }, "(" + dtstart + ">" + after + " and "
+ dtend + "<" + endOfDay.getTimeInMillis() + ")", null,
"dtstart ASC");

Android Calendar Events

I am just making an operation with Calendar Content Provider, now I am failing at the point to display events for the particular date.
I know the Events URI for the < 2.1 version and 2.2 version, as below:
eventsUri = Uri.parse("content://calendar/events"); // < Android 2.1 version
eventsUri = Uri.parse("content://com.android.calendar/events"); // For Android Froyo 2.2 and later version
My doubts are:
How do I Fetch all the events?
How do I fetch events for the particular date?
So please, somebody with knowledge about the Calendar please help me and share your knowledge regarding this.
Thanx
These examples are for <= 2.1 version;
first; find out which calendars exist
Cursor cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
cursor.moveToFirst();
String[] CalNames = new String[cursor.getCount()];
int[] CalIds = new int[cursor.getCount()];
for (int i = 0; i < CalNames.length; i++) {
CalIds[i] = cursor.getInt(0);
CalNames[i] = cursor.getString(1);
cursor.moveToNext();
}
cursor.close();
Fetching all events, and particular event is done by specifying range
ContentResolver contentResolver = getContentResolver();
Uri.Builder builder = Uri.parse(getCalendarUriBase() + "/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.MILLIS_PER_DAY*10000);
ContentUris.appendId(builder, now + DateUtils.MILLIS_PER_DAY * 10000);
and then let's say you wish to log events ID from calendar with ID = 1
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "event_id"}, "Calendars._id=" + 1,
null, "startDay ASC, startMinute ASC");
// For a full list of available columns see http://tinyurl.com/yfbg76w
while (eventCursor.moveToNext()) {
String uid2 = eventCursor.getString(0);
Log.v("eventID : ", uid2);
}
// Here's a way for you to get all the Calendar events list
public static void readCalendarEvent(Context context) {
ContentResolver contentResolver = context.getContentResolver();
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "_id", "title", "organizer", "dtstart", "dtend"}), null, null, null);
List<GoogleCalendar> gCalendar = new ArrayList<GoogleCalendar>();
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
int event_ID = cursor.getInt(0);
googleCalendar.setEvent_id(event_ID);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String mOrganizer = cursor.getString(2);
googleCalendar.setOrganizer(mOrganizer);
String dtStart = cursor.getString(3);
googleCalendar.setDtstart(dtStart);
String dtEnd = cursor.getString(4);
googleCalendar.setDtend(dtEnd);
gCalendar.add(googleCalendar);
Log.d("CaledarM",googleCalendar.getTitle()+" name = "+googleCalendar.getOrganizer()+" dateStart = "+googleCalendar.getDtstart()+" Size = " + gCalendar.size());
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// class GoogleCalendar()
public class GoogleCalendar {
private int event_id;
private String title,
organizer,
dtstart,
dtend;
public GoogleCalendar()
{
}
public int getEvent_id() {
return event_id;
}
public void setEvent_id(int calendar_id) {
event_id = calendar_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOrganizer() {
return organizer;
}
public void setOrganizer(String description) {
this.organizer = description;
}
public String getDtstart() {
return dtstart;
}
public void setDtstart(String dtstart1) {
this.dtstart = dtstart1;
}
public String getDtend() {
return dtend;
}
public void setDtend(String dtend1) {
this.dtend = dtend1;
}
}
Use this code to get daily events,
public static void readCalendarEvent(Context context) throws ParseException {
ContentResolver contentResolver = context.getContentResolver();
Calendar calendar = Calendar.getInstance();
String dtstart = "dtstart";
String dtend = "dtend";
SimpleDateFormat displayFormatter = new SimpleDateFormat("MMMM dd, yyyy (EEEE)");
stime=displayFormatter.format(calendar.getTime());
SimpleDateFormat startFormatter = new SimpleDateFormat("MM/dd/yy");
String dateString = startFormatter.format(calendar.getTime());
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("23:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
/*String[] COLS={"calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation"};
cursor = contentResolver.query(
CalendarContract.Events.CONTENT_URI, COLS,null, null, null);*/
gCalendar = new ArrayList<GoogleCalendar>();
try {
if (cursor.getCount() > 0) {
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 dtstart1 = cursor.getString(3);
dt=convertDate(dtstart1,"hh:mm:ss");
googleCalendar.setDtstart(dt);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventTimeZone=cursor.getString(5);
googleCalendar.setEventTimeZone(eventTimeZone);
String eventlocation = cursor.getString(6);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources