PageRenderTime 61ms CodeModel.GetById 11ms app.highlight 44ms RepoModel.GetById 2ms app.codeStats 0ms

/walkytalky/src/com/googlecode/eyesfree/walkytalky/NewLocationActivity.java

http://eyes-free.googlecode.com/
Java | 433 lines | 337 code | 54 blank | 42 comment | 48 complexity | d57c290a53eeb1a48267657112217300 MD5 | raw file
  1/*
  2 * Copyright (C) 2009 Google Inc.
  3 *
  4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5 * use this file except in compliance with the License. You may obtain a copy of
  6 * the License at
  7 *
  8 * http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 13 * License for the specific language governing permissions and limitations under
 14 * the License.
 15 */
 16
 17/**
 18 * UI for launching WalkyTalky.
 19 *
 20 * @author clchen@google.com (Charles L. Chen), hiteshk@google.com (Hitesh Khandelwal)
 21 */
 22
 23package com.googlecode.eyesfree.walkytalky;
 24
 25import android.app.Activity;
 26import android.app.AlertDialog;
 27import android.content.DialogInterface;
 28import android.content.Intent;
 29import android.content.SharedPreferences;
 30import android.content.SharedPreferences.Editor;
 31import android.database.Cursor;
 32import android.net.Uri;
 33import android.os.Bundle;
 34import android.preference.PreferenceManager;
 35import android.provider.ContactsContract.CommonDataKinds.Phone;
 36import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
 37import android.speech.RecognizerIntent;
 38import android.view.KeyEvent;
 39import android.view.View;
 40import android.view.View.OnClickListener;
 41import android.view.View.OnKeyListener;
 42import android.widget.ArrayAdapter;
 43import android.widget.AutoCompleteTextView;
 44import android.widget.Button;
 45import java.util.ArrayList;
 46import java.util.HashMap;
 47import java.util.Iterator;
 48import java.util.Map.Entry;
 49
 50/**
 51 * Allows users to search for new locations. Mark locations as favorite, browse
 52 * recent locations, delete locations from favorite. Returns (Lat, Lon) pair
 53 * corresponding to the searched address, to the caller Activity.
 54 */
 55public class NewLocationActivity extends Activity {
 56    private static final int MAX_RECENT_DEST_COUNT = 10;
 57
 58    public static final String PREFS_NAME = "WalkyTalky";
 59
 60    private static final String RECENT_DESTINATIONS_PREFS_KEY = "RECENT_DESTINATIONS";
 61
 62    private static final String FAVORITE_DESTINATIONS_PREFS_KEY = "FAVORITE_DESTINATIONS";
 63
 64    private NewLocationActivity self;
 65
 66    private SharedPreferences prefs;
 67
 68    private ArrayList<String> recentDestinations;
 69
 70    private ArrayList<String> favoriteDestinations;
 71
 72    private HashMap<String, String> contactDestinations;
 73
 74    private AutoCompleteTextView destinationEditText;
 75
 76    private Button goTextInputButton;
 77
 78    private Button goFavoriteButton;
 79
 80    private Button goRecentButton;
 81
 82    private Button goContactButton;
 83
 84    private Button markFavoriteButton;
 85
 86    private Button removeFavoriteButton;
 87
 88    @Override
 89    public void onCreate(Bundle bundle) {
 90        super.onCreate(bundle);
 91
 92        self = this;
 93        prefs = PreferenceManager.getDefaultSharedPreferences(this);
 94
 95        loadContactAddresses();
 96
 97        setContentView(R.layout.new_loc);
 98
 99        destinationEditText = (AutoCompleteTextView) findViewById(R.id.dest_EditText);
100        destinationEditText.setOnKeyListener(new OnKeyListener() {
101            public boolean onKey(View v, int keyCode, KeyEvent event) {
102                // If the event is a key-down event on the "enter" button
103                if ((event.getAction() == KeyEvent.ACTION_DOWN)
104                        && (keyCode == KeyEvent.KEYCODE_ENTER)) {
105                    // Perform action on key press
106                    String dest = destinationEditText.getText().toString();
107                    if (dest.length() > 0) {
108                        returnToCaller(dest);
109                    }
110                    return true;
111                }
112                return false;
113            }
114        });
115
116        goTextInputButton = (Button) findViewById(R.id.goTextInput_Button);
117        goTextInputButton.setOnClickListener(new OnClickListener() {
118            @Override
119            public void onClick(View v) {
120                String dest = destinationEditText.getText().toString();
121                if (dest.length() > 0) {
122                    returnToCaller(dest);
123                }
124            }
125        });
126
127        goFavoriteButton = (Button) findViewById(R.id.goFavorite_Button);
128        goFavoriteButton.setOnClickListener(new OnClickListener() {
129            @Override
130            public void onClick(View v) {
131                goFavoriteHandler();
132            }
133        });
134
135        goRecentButton = (Button) findViewById(R.id.goRecent_Button);
136        goRecentButton.setOnClickListener(new OnClickListener() {
137            @Override
138            public void onClick(View v) {
139                goRecentHandler();
140            }
141        });
142
143        goContactButton = (Button) findViewById(R.id.goContact_Button);
144        goContactButton.setOnClickListener(new OnClickListener() {
145            @Override
146            public void onClick(View v) {
147                goContactHandler();
148            }
149        });
150
151        markFavoriteButton = (Button) findViewById(R.id.markFavorite_Button);
152        markFavoriteButton.setOnClickListener(new OnClickListener() {
153            @Override
154            public void onClick(View v) {
155                markFavoriteHandler();
156            }
157        });
158
159        removeFavoriteButton = (Button) findViewById(R.id.removeFavorite_Button);
160        removeFavoriteButton.setOnClickListener(new OnClickListener() {
161            @Override
162            public void onClick(View v) {
163                removeFavoriteHandler();
164            }
165        });
166    }
167
168    @Override
169    public void onResume() {
170        super.onResume();
171        recentDestinations = new ArrayList<String>();
172        String[] savedDests = prefs.getString(RECENT_DESTINATIONS_PREFS_KEY, "").split("\n");
173        for (int i = 0; i < savedDests.length && !savedDests[0].equals(""); i++) {
174            recentDestinations.add(savedDests[i]);
175        }
176        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
177                android.R.layout.simple_dropdown_item_1line, recentDestinations);
178        destinationEditText.setAdapter(adapter);
179
180        favoriteDestinations = new ArrayList<String>();
181        savedDests = prefs.getString(FAVORITE_DESTINATIONS_PREFS_KEY, "").split("\n");
182        for (int i = 0; i < savedDests.length && !savedDests[0].equals(""); i++) {
183            favoriteDestinations.add(savedDests[i]);
184        }
185    }
186
187    @Override
188    public boolean onKeyDown(int keyCode, KeyEvent event) {
189        if (keyCode == KeyEvent.KEYCODE_SEARCH) {
190            doReco();
191            return true;
192        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
193            // Back button pressed in NewLocationActivity, caller application
194            // may also exit.
195            setResult(RESULT_FIRST_USER, getIntent());
196            finish();
197            return true;
198        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
199            // Open settings
200            Intent iPrefs = new Intent(this, Settings.class);
201            iPrefs.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
202            startActivity(iPrefs);
203            return true;
204        } else {
205            return super.onKeyDown(keyCode, event);
206        }
207    }
208
209    private void doReco() {
210        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
211        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
212                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
213        startActivityForResult(intent, 0);
214    }
215
216    @Override
217    public void onDestroy() {
218        super.onDestroy();
219    }
220
221    private void addRecentDestination(String dest) {
222        boolean bumpedDestinationUp = false;
223        for (int i = 0; i < recentDestinations.size(); i++) {
224            if (recentDestinations.get(i).equals(dest)) {
225                recentDestinations.remove(i);
226                recentDestinations.add(0, dest);
227                bumpedDestinationUp = true;
228                break;
229            }
230        }
231        while (recentDestinations.size() > MAX_RECENT_DEST_COUNT) {
232            recentDestinations.remove(recentDestinations.size() - 1);
233        }
234        if (!bumpedDestinationUp) {
235            recentDestinations.add(0, dest);
236        }
237        String savedDests = "";
238        for (int i = 0; i < recentDestinations.size(); i++) {
239            savedDests = savedDests + recentDestinations.get(i) + "\n";
240        }
241        Editor editor = prefs.edit();
242        editor.putString(RECENT_DESTINATIONS_PREFS_KEY, savedDests);
243        editor.commit();
244    }
245
246    private void addFavoriteDestination(String dest) {
247        favoriteDestinations.add(0, dest);
248        String savedDests = "";
249        for (int i = 0; i < favoriteDestinations.size(); i++) {
250            savedDests = savedDests + favoriteDestinations.get(i) + "\n";
251        }
252        Editor editor = prefs.edit();
253        editor.putString(FAVORITE_DESTINATIONS_PREFS_KEY, savedDests);
254        editor.commit();
255    }
256
257    private void goFavoriteHandler() {
258        int favoriteDestinationsSize = favoriteDestinations.size();
259        if (favoriteDestinationsSize == 0) {
260            return;
261        }
262
263        AlertDialog.Builder builder = new AlertDialog.Builder(self);
264        final CharSequence[] items = new CharSequence[favoriteDestinationsSize];
265        for (int i = 0; i < favoriteDestinationsSize; i++) {
266            items[i] = favoriteDestinations.get(i);
267        }
268        builder.setItems(items, new DialogInterface.OnClickListener() {
269            @Override
270            public void onClick(DialogInterface dialog, int which) {
271                String dest = (String) items[which];
272                if (dest.length() > 0) {
273                    returnToCaller(dest);
274                }
275            }
276        });
277        AlertDialog dialog = builder.create();
278        dialog.getListView().setTextFilterEnabled(true);
279        dialog.show();
280    }
281
282    private void goRecentHandler() {
283        int recentDestinationsSize = recentDestinations.size();
284        if (recentDestinationsSize == 0) {
285            return;
286        }
287
288        AlertDialog.Builder builder = new AlertDialog.Builder(self);
289        final CharSequence[] items = new CharSequence[recentDestinationsSize];
290        for (int i = 0; i < recentDestinationsSize; i++) {
291            items[i] = recentDestinations.get(i);
292        }
293        builder.setItems(items, new DialogInterface.OnClickListener() {
294            @Override
295            public void onClick(DialogInterface dialog, int which) {
296                String dest = (String) items[which];
297                if (dest.length() > 0) {
298                    returnToCaller(dest);
299                }
300            }
301        });
302        AlertDialog dialog = builder.create();
303        dialog.getListView().setTextFilterEnabled(true);
304        dialog.show();
305    }
306
307    private void markFavoriteHandler() {
308        int recentDestinationsSize = recentDestinations.size();
309        if (recentDestinationsSize == 0) {
310            return;
311        }
312
313        AlertDialog.Builder builder = new AlertDialog.Builder(self);
314        final CharSequence[] items = new CharSequence[recentDestinationsSize];
315        for (int i = 0; i < recentDestinationsSize; i++) {
316            items[i] = recentDestinations.get(i);
317        }
318        builder.setItems(items, new DialogInterface.OnClickListener() {
319            @Override
320            public void onClick(DialogInterface dialog, int which) {
321                String dest = (String) items[which];
322                addFavoriteDestination(dest);
323            }
324        });
325        AlertDialog dialog = builder.create();
326        dialog.getListView().setTextFilterEnabled(true);
327        dialog.show();
328    }
329
330    private void removeFavoriteHandler() {
331        int favoriteDestinationsSize = favoriteDestinations.size();
332        if (favoriteDestinationsSize == 0) {
333            return;
334        }
335
336        AlertDialog.Builder builder = new AlertDialog.Builder(self);
337        final CharSequence[] items = new CharSequence[favoriteDestinationsSize];
338        for (int i = 0; i < favoriteDestinationsSize; i++) {
339            items[i] = favoriteDestinations.get(i);
340        }
341        builder.setItems(items, new DialogInterface.OnClickListener() {
342            @Override
343            public void onClick(DialogInterface dialog, int which) {
344                favoriteDestinations.remove(which);
345                String savedDests = "";
346                for (int i = 0; i < favoriteDestinations.size(); i++) {
347                    savedDests = savedDests + favoriteDestinations.get(i) + "\n";
348                }
349                Editor editor = prefs.edit();
350                editor.putString(FAVORITE_DESTINATIONS_PREFS_KEY, savedDests);
351                editor.commit();
352            }
353        });
354        AlertDialog dialog = builder.create();
355        dialog.getListView().setTextFilterEnabled(true);
356        dialog.show();
357    }
358
359    private void loadContactAddresses() {
360        contactDestinations = new HashMap<String, String>();
361        // Get the base URI for People table in Contacts content provider.
362        // ie. content://contacts/people/
363        Uri mContacts = StructuredPostal.CONTENT_URI;
364
365        // An array specifying which columns to return.
366        String[] projection = new String[] {
367                StructuredPostal.DISPLAY_NAME, StructuredPostal.FORMATTED_ADDRESS
368        };
369
370        // Best way to retrieve a query; returns a managed query.
371        Cursor managedCursor = managedQuery(mContacts, projection, // Which
372                // columns
373                // to return.
374                null, // WHERE clause--we won't specify.
375                null, // no selection args
376                Phone.DISPLAY_NAME + " ASC"); // Order-by clause.
377        boolean moveSucceeded = managedCursor.moveToFirst();
378
379        ArrayList<String> contactNames = new ArrayList<String>();
380        while (moveSucceeded) {
381            contactDestinations.put(managedCursor.getString(0) + " at "
382                    + managedCursor.getString(1), managedCursor.getString(1));
383            moveSucceeded = managedCursor.moveToNext();
384        }
385    }
386
387    private void goContactHandler() {
388        int contactDestinationsSize = contactDestinations.size();
389        if (contactDestinationsSize == 0) {
390            return;
391        }
392
393        AlertDialog.Builder builder = new AlertDialog.Builder(self);
394        final CharSequence[] items = new CharSequence[contactDestinationsSize];
395
396        Iterator<Entry<String, String>> it = contactDestinations.entrySet().iterator();
397        int i = 0;
398        while (it.hasNext()) {
399            Entry<String, String> entry = it.next();
400            items[i] = entry.getKey();
401            i++;
402        }
403
404        builder.setItems(items, new DialogInterface.OnClickListener() {
405            @Override
406            public void onClick(DialogInterface dialog, int which) {
407                String dest = contactDestinations.get(items[which]);
408                if (dest.length() > 0) {
409                    returnToCaller(dest);
410                }
411            }
412        });
413        AlertDialog dialog = builder.create();
414        dialog.getListView().setTextFilterEnabled(true);
415        dialog.show();
416    }
417
418    /**
419     * Returns (Lat, Lon) pair corresponding to the searched address, to the
420     * caller Activity.
421     * 
422     * @param destination Address to search
423     */
424    private void returnToCaller(String destination) {
425        if (destination != null) {
426            setResult(RESULT_OK, getIntent().putExtra("LOC", destination));
427        } else {
428            setResult(RESULT_CANCELED, getIntent());
429        }
430        addRecentDestination(destination);
431        finish();
432    }
433}