0

I want to implement a program which inserts details in database everytime the call is made or sms is sent. Should I use a broadcast receiver or content observer or Service ? what would be appropriate? I am new to android and urgently need help on this.

I have done the following code uptill now. The problem with this is when first time the code is run then for example call log has 8 records so these 8 records are inserted in database. Then if any change in call log is made for example i make another call then 17 records are shown in database instead of 9. Please help where am i going wrong ?

    package com.calllogdb;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;




import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.ContentValues;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

//import static android.provider.BaseColumns._ID;
import static com.calllogdb.Constants.KEY_ContactNum ;
import static com.calllogdb.Constants.KEY_ContactName;
import static com.calllogdb.Constants.KEY_Duration;
import static com.calllogdb.Constants.KEY_Date ;
import static com.calllogdb.Constants.KEY_NumType ;
import static com.calllogdb.Constants.KEY_CurrTime ;
import static com.calllogdb.Constants.TABLE_NAME;

public class MainActivity extends Activity {

    private Helper helper = new Helper(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          this.getApplicationContext()
            .getContentResolver()
            .registerContentObserver(
                    android.provider.CallLog.Calls.CONTENT_URI, true,
                    new CallLogObserver(new Handler())); 



        try {

            addLog();
        }
    finally {

        helper.close();
    } 
    }

    private void addLog() {


        // TODO Auto-generated method stub
        SQLiteDatabase db;

         Cursor cursor = getContentResolver().query(
                    android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
                    android.provider.CallLog.Calls.DATE + " DESC ");

    db = helper.getWritableDatabase();


    startManagingCursor(cursor);
    int numberColumnId = cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
    int durationId = cursor.getColumnIndex(android.provider.CallLog.Calls.DURATION);
    int contactNameId = cursor.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
    int dateId = cursor.getColumnIndex(android.provider.CallLog.Calls.DATE);
   int numTypeId = cursor.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);

    Date dt = new Date();
    int hours = dt.getHours();
    int minutes = dt.getMinutes();
    int seconds = dt.getSeconds();
    String currTime = hours + ":" + minutes + ":" + seconds;



    ArrayList<String> callList = new ArrayList<String>();
    if (cursor.moveToFirst()) {
        do {
            String contactNumber = cursor.getString(numberColumnId);
            String contactName = cursor.getString(contactNameId);
            String duration = cursor.getString(durationId);
            String callDate = DateFormat.getDateInstance().format(dateId);
           String numType = cursor.getString(numTypeId);

            ContentValues values = new ContentValues();
            values.put(KEY_ContactName, contactName);
       values.put(KEY_NumType, numType);
            values.put(KEY_ContactNum, contactNumber);
            values.put(KEY_Duration, duration);
            values.put(KEY_Date, callDate);
            values.put(KEY_CurrTime, currTime);

            db.insert(TABLE_NAME, null, values);


            callList.add("Contact Number: " + contactNumber
                    + "\nContact Name: " + contactName + "\nDuration: "
                    + duration + "\nDate: " + callDate);


        } while (cursor.moveToNext());
}
    Toast.makeText(getBaseContext(), "Inserted!", Toast.LENGTH_LONG).show();


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }




    public class CallLogObserver extends ContentObserver
    {



        public CallLogObserver(Handler handler) {
            super(handler);
            // TODO Auto-generated constructor stub
        }


          @Override
            public boolean deliverSelfNotifications() {
                return true;
            }

            @Override
            public void onChange(boolean selfChange) {
                Log.d("LOG_TAG", "MyContentObserver.onChange( " + selfChange
                        + ")");
                super.onChange(selfChange);
                addLog();

            }





    }
}

Whenever i am making a call it gets notified and inserts whole set of records instead of only the latest one.What should i do to prevent this? Thanks

user2011302
  • 391
  • 1
  • 4
  • 22

1 Answers1

0

You are probably inserting the whole call log into the database again. You can use either content observer or a broadcast listener to know that a call is made, but you need to maintain the time when you last read the complete db of call logs, and only insert calls that are made after that time.

If you use contentobserver, the observer needs to be in a service. Register the observer in the onCreate(). You will use contentProvider in the onChange of the contentObserver. You will need to maintain time when you last read the database using shared preferences. Note the changes of entries after the time stored in shared preferences. Now update the time of shared preferences to current time. Also unregister the content observer in onDestroy().

Aditya
  • 5,509
  • 4
  • 31
  • 51
  • Can you give explain this with an easy example ? – user2011302 Jul 27 '13 at 06:57
  • Suppose you had call logs from numbers x y and z at time 1:00. You read these logs and store the epoch time of 1:00 in shared preference. Next time your observer gets called at 1:40 when a call to a new number x1 is made. You will query for numbers after 1:00 using content provider and this will return x1 as it is the only number after 1:00(which is stored in shared prefernces). You add these values to your db or do whatever you want with them. Now you update the time of shared preference to 1:40(again use epoch times) – Aditya Jul 30 '13 at 13:04