summaryrefslogtreecommitdiff
path: root/samples/ApiDemos/src/com/example/android/apis/content/ChangedContacts.java
blob: 412a3c6dc30187cb7286a6857f5cd2b3a9b2ed20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.example.android.apis.content;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Demonstrates selecting contacts that have changed since a certain time.
 */
public class ChangedContacts extends Activity implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String CLASS = ChangedContacts.class.getSimpleName();

    private static final String PREF_KEY_CHANGE = "timestamp_change";
    private static final String PREF_KEY_DELETE = "timestamp_delete";

    private static final int ID_CHANGE_LOADER = 1;
    private static final int ID_DELETE_LOADER = 2;

    /**
     * To see this in action, "clear data" for the contacts storage app in the system settings.
     * Then come into this app and hit any of the delta buttons.  This will cause the contacts
     * database to be re-created.
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast toast = Toast.makeText(context, "Contacts database created.", Toast.LENGTH_SHORT);
            toast.show();
        }
    };

    private DeleteAdapter mDeleteAdapter;
    private ChangeAdapter mChangeAdapter;
    private long mSearchTime;
    private TextView mDisplayView;
    private ListView mList;
    private Button mDeleteButton;
    private Button mChangeButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mDeleteAdapter = new DeleteAdapter(this, null, 0);
        mChangeAdapter = new ChangeAdapter(this, null, 0);

        LinearLayout main = new LinearLayout(this);
        main.setOrientation(LinearLayout.VERTICAL);

        mChangeButton = new Button(this);
        mChangeButton.setText("Changed since " + getLastTimestamp(0, PREF_KEY_CHANGE));
        mChangeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeClick();
            }
        });

        mDeleteButton = new Button(this);
        mDeleteButton.setText("Deleted since " + getLastTimestamp(0, PREF_KEY_DELETE));
        mDeleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteClick();
            }
        });

        main.addView(mChangeButton);
        main.addView(mDeleteButton);

        mDisplayView = new TextView(this);
        mDisplayView.setPadding(5, 5, 5, 5);
        main.addView(mDisplayView);

        mList = new ListView(this);
        mList.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
        main.addView(mList);

        setContentView(main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ContactsContract.Intents.CONTACTS_DATABASE_CREATED);
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    private void changeClick() {
        mChangeAdapter.swapCursor(null);
        LoaderManager manager = getLoaderManager();
        manager.destroyLoader(ID_DELETE_LOADER);
        manager.restartLoader(ID_CHANGE_LOADER, null, this);
    }

    private void deleteClick() {
        mChangeAdapter.swapCursor(null);
        LoaderManager manager = getLoaderManager();
        manager.destroyLoader(ID_CHANGE_LOADER);
        manager.restartLoader(ID_DELETE_LOADER, null, this);
    }

    private void saveLastTimestamp(long time, String key) {
        SharedPreferences pref = getSharedPreferences(CLASS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putLong(key, time);
        editor.commit();
    }

    private long getLastTimestamp(long time, String key) {
        SharedPreferences pref = getSharedPreferences(CLASS, Context.MODE_PRIVATE);
        return pref.getLong(key, time);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        switch(id) {
            case ID_CHANGE_LOADER:
                return getChangeLoader();
            case ID_DELETE_LOADER:
                return getDeleteLoader();
        }
        return null;
    }

    private CursorLoader getChangeLoader() {
        String[] projection = new String[]{
                ContactsContract.Data._ID,
                ContactsContract.Data.CONTACT_ID,
                ContactsContract.Data.DISPLAY_NAME,
                ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP
        };

        mSearchTime = getLastTimestamp(0, PREF_KEY_CHANGE);

        String selection = ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP + " > ?";
        String[] bindArgs = new String[]{mSearchTime + ""};
        return new CursorLoader(this, ContactsContract.Data.CONTENT_URI, projection,
                selection, bindArgs, ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP
                + " desc, " + ContactsContract.Data.CONTACT_ID + " desc");
    }

    private CursorLoader getDeleteLoader() {
        String[] projection = new String[]{
                ContactsContract.DeletedContacts.CONTACT_ID,
                ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP
        };

        mSearchTime = getLastTimestamp(0, PREF_KEY_DELETE);

        String selection = ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP + " > ?";
        String[] bindArgs = new String[]{mSearchTime + ""};
        return new CursorLoader(this, ContactsContract.DeletedContacts.CONTENT_URI, projection,
                selection, bindArgs, ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP +
                " desc");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor data) {
        long timestamp = 0;


        switch (cursorLoader.getId()) {
            case ID_CHANGE_LOADER:
                mDisplayView.setText(data.getCount() + " change(s) since " + mSearchTime);
                mList.setAdapter(mChangeAdapter);
                mChangeAdapter.swapCursor(data);

                // Save the largest timestamp returned.  Only need the first one due to the sort
                // order.
                if (data.moveToNext()) {
                    timestamp = data.getLong(data.getColumnIndex(
                            ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP));
                    data.moveToPrevious();
                }
                if (timestamp > 0) {
                    saveLastTimestamp(timestamp, PREF_KEY_CHANGE);
                    mChangeButton.setText("Changed since " + timestamp);
                }
                break;
            case ID_DELETE_LOADER:
                mDisplayView.setText(data.getCount() + " delete(s) since " + mSearchTime);
                mList.setAdapter(mDeleteAdapter);
                mDeleteAdapter.swapCursor(new DeleteCursorWrapper(data));
                if (data.moveToNext()) {
                    timestamp = data.getLong(data.getColumnIndex(
                            ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP));
                    data.moveToPrevious();
                }
                if (timestamp > 0) {
                    saveLastTimestamp(timestamp, PREF_KEY_DELETE);
                    mDeleteButton.setText("Deleted since " + timestamp);
                }
                break;
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        mDisplayView.setText("");
        switch (cursorLoader.getId()) {
            case ID_CHANGE_LOADER:
                mChangeAdapter.swapCursor(null);
                break;
            case ID_DELETE_LOADER:
                mDeleteAdapter.swapCursor(null);
                break;
        }
    }

    private class DeleteCursorWrapper extends CursorWrapper {

        /**
         * Creates a cursor wrapper.
         *
         * @param cursor The underlying cursor to wrap.
         */
        public DeleteCursorWrapper(Cursor cursor) {
            super(cursor);
        }

        @Override
        public int getColumnIndexOrThrow(String columnName) {
            if (columnName.equals("_id")) {
                return super.getColumnIndex(ContactsContract.DeletedContacts.CONTACT_ID);
            }
            return super.getColumnIndex(columnName);
        }
    }

    private static class DeleteAdapter extends CursorAdapter {

        private Context mContext;

        public DeleteAdapter(Context context, Cursor c, int flags) {
            super(context, c, flags);
            this.mContext = context;
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            LinearLayout item = new LinearLayout(mContext);
            item.addView(buildText(context));
            item.addView(buildText(context));
            return item;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            LinearLayout item = (LinearLayout) view;
            String id = cursor.getString(cursor.getColumnIndex(
                    ContactsContract.DeletedContacts.CONTACT_ID));
            String timestamp = cursor.getString(cursor.getColumnIndex(
                    ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP));

            setText(item.getChildAt(0), id);
            setText(item.getChildAt(1), timestamp);
        }
    }

    private static class ChangeAdapter extends CursorAdapter {

        private Context mContext;

        public ChangeAdapter(Context context, Cursor c, int flags) {
            super(context, c, flags);
            mContext = context;
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            LinearLayout item = new LinearLayout(mContext);
            item.addView(buildText(context));
            item.addView(buildText(context));
            item.addView(buildText(context));
            return item;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            LinearLayout item = (LinearLayout) view;

            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID));
            String name = cursor.getString(cursor.getColumnIndex(
                    ContactsContract.Data.DISPLAY_NAME));
            String timestamp = cursor.getString(cursor.getColumnIndex(
                    ContactsContract.Data.CONTACT_LAST_UPDATED_TIMESTAMP));

            setText(item.getChildAt(0), id);
            setText(item.getChildAt(1), name);
            setText(item.getChildAt(2), timestamp);
        }
    }

    private static void setText(View view, String value) {
        TextView text = (TextView) view;
        text.setText(value);
    }

    private static TextView buildText(Context context) {
        TextView view = new TextView(context);
        view.setPadding(3, 3, 3, 3);
        return view;
    }
}