Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.chrudgames.stayintouch;
- import java.sql.Date;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import com.google.ads.*;
- import com.google.ads.AdRequest.ErrorCode;
- import android.app.Activity;
- import android.app.AlarmManager;
- import android.app.AlertDialog;
- import android.app.ListActivity;
- import android.app.PendingIntent;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.database.Cursor;
- import android.graphics.drawable.Drawable;
- import android.net.Uri;
- import android.os.Bundle;
- import android.preference.PreferenceManager;
- import android.provider.ContactsContract;
- import android.provider.ContactsContract.CommonDataKinds.Phone;
- import android.provider.ContactsContract.Contacts;
- import android.provider.ContactsContract.Contacts.Data;
- import android.util.Log;
- import android.view.Menu;
- import android.view.MenuInflater;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.Button;
- import android.widget.LinearLayout;
- import android.widget.ListView;
- import android.widget.ProgressBar;
- import android.widget.SimpleCursorAdapter;
- import android.widget.TextView;
- import android.widget.SimpleCursorAdapter.ViewBinder;
- public class StayInTouchActivity extends ListActivity implements AdListener {
- private AdView adView;
- public interface AdListener {
- public void onReceiveAd(Ad ad);
- public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error);
- public void onPresentScreen(Ad ad);
- public void onDismissScreen(Ad ad);
- public void onLeaveApplication(Ad ad);
- }
- private static final int CONTACT_PICKER_RESULT = 1001;
- boolean NotifyPreference;
- String DurationPreference;
- int listIndex;
- boolean bolOwned;
- int intContacts;
- int arrContacts[];
- SimpleCursorAdapter adapter;
- private static Context mContext;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mContext = this;
- // ListView listview=(ListView)findViewById(android.R.id.list);
- //listview.setOnScrollListener(onLstScroll);
- //Create an offset from the current time in which the alarm will go off.
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.HOUR, 24 );
- //Create a new PendingIntent and add it to the AlarmManager
- Intent intent = new Intent(this, AlarmReceiverActivity.class);
- PendingIntent pendingIntent = PendingIntent.getActivity(this,
- 12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
- AlarmManager am =
- (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
- am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
- pendingIntent);
- DatabaseHandler db = new DatabaseHandler(this);
- bolOwned = db.owned();
- db.close();
- //bolOwned=true;
- if(bolOwned==false){
- // Create the adView
- adView = new AdView(this, AdSize.BANNER, "a14fa9a02c91beb");
- // Lookup your LinearLayout assuming it’s been given
- // the attribute android:id="@+id/mainLayout"
- LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);
- // Add the adView to it
- layout.addView(adView);
- // Initiate a generic request to load it with an ad
- AdRequest adRequest = new AdRequest();
- //adRequest.addTestDevice(AdRequest.TEST_EMULATOR); // Emulator
- //adRequest.addTestDevice("HT097HL04633");
- adView.setAdListener(this);
- adView.loadAd(adRequest);
- }else{
- }
- }
- @Override
- public void onReceiveAd(Ad ad){
- fillList();
- }
- @Override
- public void onDestroy() {
- if (adView != null) {
- adView.destroy();
- }
- super.onDestroy();
- }
- /*
- OnScrollListener onLstScroll= new OnScrollListener()
- {
- @Override
- public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
- {
- }
- @Override
- public void onScrollStateChanged(AbsListView view, int scrollState)
- {
- switch (scrollState) {
- case OnScrollListener.SCROLL_STATE_IDLE:
- //adapter.notifyDataSetChanged();
- break;
- case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
- //adapter.notifyDataSetChanged();
- break;
- case OnScrollListener.SCROLL_STATE_FLING:
- //adapter.notifyDataSetChanged();
- break;
- }
- }
- };
- */
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.layout.menu, menu);
- if(bolOwned){
- MenuItem i = menu.findItem(R.id.upgrade);
- i.setVisible(false);
- }
- return true;
- }
- private void getPrefs() {
- SharedPreferences prefs = PreferenceManager
- .getDefaultSharedPreferences(getBaseContext());
- NotifyPreference = prefs.getBoolean("pref_notify", true);
- DurationPreference = prefs.getString("pref_duration", "60");
- if(DurationPreference.length()<1){DurationPreference="0";}
- }
- @Override
- public void onResume()
- {
- DatabaseHandler db = new DatabaseHandler(this);
- bolOwned = db.owned();
- db.close();
- // bolOwned=true;
- super.onResume();
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle item selection
- switch (item.getItemId()) {
- case R.id.options:
- Intent i = new Intent(this, Prefs.class);
- startActivity(i);
- return true;
- case R.id.help:
- Intent i2 = new Intent(this, Help.class);
- startActivity(i2);
- return true;
- case R.id.upgrade:
- Intent i3 = new Intent(this, Upgrade.class);
- startActivity(i3);
- return true;
- default:
- return super.onOptionsItemSelected(item);
- }
- }
- @Override
- public void onWindowFocusChanged(boolean hasFocus) {
- if(hasFocus){
- getPrefs();
- updateDays();
- fillList();
- }
- }
- public void fillList() {
- try{
- DatabaseHandler db = new DatabaseHandler(this);
- String[] fields = new String[] { "name", "frequency", "dDays", "precMax", "precMax", "precMax", "last" };
- int[] views = new int[] { R.id.textView1, R.id.textView3, R.id.textView2, R.id.progressBar1, R.id.progressBar2, R.id.progressBar3 };
- Cursor c = (Cursor) db.getAllContactsCursor();
- // Log.w("onActivityResult", "Count=" + c.getCount());
- //startManagingCursor(c);
- arrContacts=new int[c.getCount()];
- int i=0;
- c.moveToFirst();
- while (c.isAfterLast() == false)
- {
- arrContacts[i] = c.getInt(7);
- i++;
- c.moveToNext();
- }
- TextView mTextView = (TextView) findViewById(R.id.tvInit);
- if(c.getCount()>0){
- mTextView.setVisibility(View.GONE);
- intContacts = c.getCount();
- Button btn = (Button)findViewById(R.id.btnadd);
- if(bolOwned==false && intContacts>4){
- btn.setText(this.getString(R.string.Upgrade));
- Drawable img = this.getResources().getDrawable( R.drawable.happy_bot_small);
- btn.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null );
- }else{
- btn.setText(this.getString(R.string.Add_Contact));
- Drawable img = this.getResources().getDrawable( R.drawable.ic_input_add);
- btn.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null );
- }
- }else{
- mTextView.setVisibility(View.VISIBLE);
- }
- adapter = new SimpleCursorAdapter(
- this,
- R.layout.main_row_view,
- c, fields, views);
- adapter.setViewBinder(new ProductViewBinder());
- setListAdapter(adapter);
- db.close();
- // c.close();
- }catch (Error e){
- alertbox("Oops!", "There was a problem: " + e.getMessage());
- }
- }
- private static class ProductViewBinder implements ViewBinder {
- public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
- if (view.getId()==R.id.textView2) {
- if(cursor.getString(2).contentEquals("1800-01-01")){
- ((TextView)view).setText(mContext.getString(R.string.No_Calls));
- }else{
- ((TextView)view).setText(cursor.getString(6).toString());
- }
- return true;
- }else if (view instanceof ProgressBar) {
- // String result = cursor.getString(2);
- int resInt = cursor.getInt(7);
- if(resInt <= 90) {
- if(view.getId()==R.id.progressBar1){
- ((ProgressBar)view).setVisibility(View.VISIBLE);
- }else{
- ((ProgressBar)view).setVisibility(View.INVISIBLE);
- }
- //d = view.getResources().getDrawable(R.drawable.progress_green);
- //((ProgressBar)view).setProgress(resInt);
- } else {
- if(resInt <= 100) {
- if(view.getId()==R.id.progressBar3){
- ((ProgressBar)view).setVisibility(View.VISIBLE);
- }else{
- ((ProgressBar)view).setVisibility(View.INVISIBLE);
- }
- }else{
- if(view.getId()==R.id.progressBar2){
- ((ProgressBar)view).setVisibility(View.VISIBLE);
- }else{
- ((ProgressBar)view).setVisibility(View.INVISIBLE);
- }
- }
- }
- ((ProgressBar)view).setProgress(resInt);
- return true;
- }
- return false;
- }
- }
- public void doLaunchContactPicker(View view) {
- if(bolOwned||intContacts<5){
- Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
- Contacts.CONTENT_URI);
- startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
- } else {
- Intent i = new Intent(this, Upgrade.class);
- startActivity(i);
- }
- }
- protected void onListItemClick(ListView l, View v, int position, long id) {
- //DatabaseHandler db = new DatabaseHandler(this);
- //db.runQuery("delete from contacts where name = 'Jenny'");
- //db.close();
- super.onListItemClick(l, v, position, id);
- //Object o = this.getListAdapter().getItem(position);
- Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
- c.moveToPosition(position);
- final String lookupKey = c.getString(0);
- final int intFrequency = c.getInt(1);
- final String strPhone = c.getString(4);
- c.close();
- l = null;
- Intent i = new Intent(this, Detail.class);
- Bundle b1 = new Bundle();
- b1.putString("lookupKey", lookupKey);
- b1.putInt("frequency", intFrequency);
- b1.putString("phone", strPhone);
- i.putExtras(b1);
- startActivity(i);
- }
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (resultCode == RESULT_OK) {
- switch (requestCode) {
- case CONTACT_PICKER_RESULT:
- Uri result = data.getData();
- String id = result.getLastPathSegment();
- /*
- Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI
- , new String[]{ Phone.NUMBER
- }
- , Phone.CONTACT_ID + "=? AND " + Data.MIMETYPE + "=? AND " + Data.IS_PRIMARY + "=1"
- , new String[]{ String.valueOf(id),Phone.CONTENT_ITEM_TYPE }, null);
- if(c.moveToFirst()){
- */
- Cursor cursor = getContentResolver().query(
- Phone.CONTENT_URI, null,
- Phone.CONTACT_ID + "=? ",
- new String[]{id}, Data.IS_PRIMARY + " desc");
- if (cursor.moveToFirst()) {
- int phoneIdx = cursor.getColumnIndex(Phone.DATA);
- String phone = cursor.getString(phoneIdx);
- phoneIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
- String name = cursor.getString(phoneIdx);
- phoneIdx = cursor.getColumnIndex(Phone.LOOKUP_KEY);
- String lookup = cursor.getString(phoneIdx);
- phoneIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
- int photo = cursor.getInt(phoneIdx);
- if (phone.length() == 0) {
- alertbox("No Number", "There are no phone numbers listed for this contact, please add at least one and try again.");
- }
- else {
- DatabaseHandler db = new DatabaseHandler(this);
- Contact contact = new Contact();
- contact._frequency = 14;
- contact._id = lookup;
- contact._last = Date.valueOf("1800-01-01");
- contact._name = name;
- contact._phone_number = phone;
- contact._photo = photo;
- db.addContact(contact);
- db.close();
- //db.deleteContact(contact);
- //Log.w("onActivityResult", "Count=" + db.getContactsCount());
- }
- Intent i = new Intent(this, Setup.class);
- Bundle b1 = new Bundle();
- b1.putString("lookupKey", lookup);
- i.putExtras(b1);
- startActivity(i);
- //break;
- }else{
- alertbox("No Number", "There are no phone numbers listed for this contact, please add at least one and try again.");
- }
- cursor.close();
- break;
- }
- } else {
- // gracefully handle failure
- }
- }
- public void updateDays(){
- //try {
- String lookupKey = "";
- String tmpPhone = "";
- String phoneNumbers = "";
- String strName = "";
- final String[] projection = { "date", "duration", "type" };
- String selection = "duration>" + DurationPreference;
- final String selectionArgs[] = null;// phoneNumbers;
- final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
- DatabaseHandler db = new DatabaseHandler(this);
- Cursor contacts = (Cursor) db.getAllContactsCursor();
- while (contacts.moveToNext()) {
- if (contacts.getString(0).equalsIgnoreCase(db.getID().toString())) {
- }else{
- lookupKey = contacts.getString(0);
- Log.d("SIT", "Key=" + lookupKey);
- Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
- Cursor c = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME, Contacts.LAST_TIME_CONTACTED, Contacts.HAS_PHONE_NUMBER},null, null, null);
- if (c.getCount()==0){
- Log.d("Error", "Count=0");
- phoneNumbers="";
- db.runQuery("delete from contacts where _id='" + lookupKey + "'");
- alertbox("Missing Contact", contacts.getString(3) + " is no longer in your people directory and has been removed from StayInTouch");
- }else{
- c.moveToFirst();
- String hasPhone = c.getString(2);
- strName = c.getString(0);
- if (hasPhone.contains("1")) {
- Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY +" = '" + lookupKey + "'", null, null);
- while (phones.moveToNext()) {
- tmpPhone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
- tmpPhone = tmpPhone.replaceAll("[^0-9]","");
- if(tmpPhone.length()>6){tmpPhone = tmpPhone.substring(tmpPhone.length() - 6);}
- phoneNumbers = phoneNumbers + "'" + tmpPhone + "',";
- }
- phones.close();
- // Log.w("onActivityResult", "Phones: " + c.getString(0).toString() + phoneNumbers);
- if(phoneNumbers.length()>1){ phoneNumbers = phoneNumbers.substring(0, phoneNumbers.length() - 1);}
- }
- }
- c.close();
- selection = "duration>" + DurationPreference + " and substr(replace(number, '-',''),-6,6) IN (" + phoneNumbers + ")";
- Cursor calldate = null;
- Long datLatest = null;
- calldate = getContentResolver().query(
- Uri.parse("content://call_log/calls"),
- projection,
- selection,
- selectionArgs,
- sortOrder);
- if (calldate.moveToFirst()) {
- datLatest = calldate.getLong(0);
- db.runQuery("update contacts set last = '" + dateFormat.format(datLatest) + "', name='" + strName + "' where _id='" + lookupKey.toString() + "' and " +
- " datetime(last) < Datetime('" + dateFormat.format(datLatest) + "')");
- }
- calldate.close();
- phoneNumbers = "";
- //db.close();
- }
- }
- contacts.close();
- db.close();
- //} catch (Exception e) {
- // Log.d("SIT", "error=" + e.getMessage());
- // }
- }
- protected void alertbox(String title, String mymessage)
- {
- new AlertDialog.Builder(this)
- .setMessage(mymessage)
- .setTitle(title)
- .setCancelable(true)
- .setNeutralButton(android.R.string.ok,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton){}
- })
- .show();
- }
- @Override
- public void onDismissScreen(Ad arg0) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onLeaveApplication(Ad arg0) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onPresentScreen(Ad arg0) {
- // TODO Auto-generated method stub
- }
- }
Add Comment
Please, Sign In to add comment