code
stringlengths
3
1.18M
language
stringclasses
1 value
/** Automatically generated file. DO NOT MODIFY */ package com.google.android.gms; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package com.example.tabtest; import java.util.Locale; import android.app.ActionBar; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MainActivity extends FragmentActivity implements ActionBar.TabListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which * will keep every loaded fragment in memory. If this becomes too memory * intensive, it may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter( getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab(actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a DummySectionFragment (defined as a static inner class // below) with the page number as its lone argument. Fragment fragment = new DummySectionFragment(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); fragment.setArguments(args); return fragment; } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; } } /** * A dummy fragment representing a section of the app, but that simply * displays dummy text. */ public static class DummySectionFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ public static final String ARG_SECTION_NUMBER = "section_number"; public DummySectionFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false); TextView dummyTextView = (TextView) rootView .findViewById(R.id.section_label); dummyTextView.setText(Integer.toString(getArguments().getInt( ARG_SECTION_NUMBER))); return rootView; } } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.example.getpost; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package com.example.getpost; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; public class GetAndPost extends Activity { TextView tv; String text; private Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this.getLayoutInflater().getContext(); tv = (TextView)findViewById(R.id.textview); text = ""; // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://jeremiesamson-portfolio.com/wp-content/uploads/takeaphotoforme/post.php"); try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("id", "9999")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); int responseCode = response.getStatusLine().getStatusCode(); switch(responseCode) { case 200: HttpEntity entity = response.getEntity(); if(entity != null) { String responseBody = EntityUtils.toString(entity); message(responseBody); } break; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } } public void message(String message) { Toast toast = Toast.makeText(context, message, 4); toast.show(); } }
Java
package com.android.map; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; public class HelloGoogleMapActivity extends MapActivity { private MapView mapView; private MapController mc; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView) this.findViewById(R.id.mapView); mapView.setBuiltInZoomControls(true); mc = mapView.getController(); mc.setZoom(5); } @Override protected boolean isRouteDisplayed() { return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { mapView.setSatellite(true); return true; } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { mapView.setSatellite(false); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.takeaphoto.activity; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package com.takeaphoto.activity; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; public class CustomViewPager extends ViewPager { private boolean enabled; public CustomViewPager(Context context, AttributeSet attrs) { super(context, attrs); this.enabled = true; } @Override public boolean onTouchEvent(MotionEvent event) { if (this.enabled) { return super.onTouchEvent(event); } return false; } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (this.enabled) { return super.onInterceptTouchEvent(event); } return false; } public void setPagingEnabled(boolean enabled) { this.enabled = enabled; } }
Java
package com.takeaphoto.activity; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.takeaphoto.model.Demande; import com.takeaphoto.model.User; import com.takeaphoto.server.DemandeServeur; import com.takeaphoto.server.PhotoServeur; import com.takeaphoto.server.UserServeur; public class ManagerActivity extends ListFragment { final String EXTRA_ID_USER = "ID_User"; private ArrayList<Demande> demandes ; private User currentUser ; private ArrayList<Bitmap> photos = null ; private int nbPhotosCurrent, nbPhotos ; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); int id = getActivity().getIntent().getIntExtra(EXTRA_ID_USER, -1) ; currentUser = new UserServeur().getUser(getActivity(), id) ; if(demandes == null){ updateDemandes() ; } } private void updateDemandes() { if(currentUser != null){ new DemandeServeur().updateMyDemandesLocal(getActivity(), currentUser); actualiserListeDemande() ; }else setListAdapter(null) ; } public void actualiserListeDemande(){ if(currentUser != null){ demandes = new DemandeServeur().getMyDemandesLocal(getActivity(), currentUser) ; if(demandes != null){ // Each row in the list stores country name, currency and flag List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>(); String[] Descriptions = new String[demandes.size()] ; int[] images = new int[demandes.size()] ; for(int i = 0 ; i < demandes.size(); i++){ Descriptions[i] = demandes.get(i).getDescription() ; switch (demandes.get(i).getEtat()) { case 0: images[i] = R.drawable.vert ; break; case 1: images[i] = R.drawable.jaune ; break; case 2: images[i] = R.drawable.rouge ; break; default: break; } } for(int i=0;i<demandes.size();i++){ HashMap<String, String> hm = new HashMap<String,String>(); hm.put("txt", Descriptions[i]); hm.put("image", Integer.toString(images[i]) ); aList.add(hm); } // Keys used in Hashmap String[] from = { "image","txt" }; // Ids of views in listview_layout int[] to = { R.id.image, R.id.txt}; // Instantiating an adapter to store each items // R.layout.listview_layout defines the layout of each item SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview, from, to); setListAdapter(adapter); } else setListAdapter(null) ; }else setListAdapter(null) ; } public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // TODO Add your menu entries here super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.refresh, menu) ; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh : updateDemandes() ; break ; } return true ; } @Override public void onListItemClick(ListView l, View v, final int position, long id) { final int id_demande = demandes.get(position).getId() ; AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); int etat = demandes.get(position).getEtat() ; if(etat == 0){ alert.setTitle("Demande : " + demandes.get(position).getDescription()); alert.setPositiveButton("Modifier Description", new OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { renomerDemande(position) ; } }); alert.setNeutralButton("Supprimer Demande", new OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { supprimerDemande(id_demande) ; } }); alert.setNegativeButton("Annuler", new OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {} }); alert.show(); }else if(etat == 1 || etat == 2){ ArrayList<Object> result = new PhotoServeur().getUrls(currentUser, id_demande) ; if(result != null){ photos = new ArrayList<Bitmap>() ; nbPhotos = result.size() ; nbPhotosCurrent = 0 ; for(Object url : result){ new getPhoto().execute((String)url, id_demande+"") ; } } } } public class getPhoto extends AsyncTask<String, Integer, Bitmap> { volatile int id_demande ; @Override protected Bitmap doInBackground(String ... args ) { id_demande = Integer.parseInt(args[1]) ; String url = "http://jeremiesamson-portfolio.com/wp-content/uploads/takeaphotoforme/" + args[0] ; Bitmap bmp = null ; try { URLConnection conn = null; URL u = new URL(url) ; conn = u.openConnection() ; HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("GET"); httpConn.connect(); InputStream is = null; if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { is = httpConn.getInputStream(); int thisLine; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((thisLine = is.read()) != -1) { bos.write(thisLine); } bos.flush(); byte [] data = bos.toByteArray(); if (bos != null){ bos.close(); } bmp=BitmapFactory.decodeByteArray(data,0,data.length); return bmp; } httpConn.disconnect() ; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bmp ; } protected void onPostExecute(Bitmap bmp) { photos.add(bmp) ; nbPhotosCurrent ++ ; if(nbPhotos == nbPhotosCurrent){ nbPhotosCurrent = 0 ; afficherPhotos(id_demande) ; } } } private void afficherPhotos(final int id_demande){ if(photos != null && nbPhotosCurrent < nbPhotos){ AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()) ; ImageView iv = new ImageView(getActivity()) ; iv.setImageBitmap(photos.get(nbPhotosCurrent)) ; alert.setView(iv) ; alert.setTitle("photo " + (nbPhotosCurrent+1) + "/" + nbPhotos) ; if(nbPhotosCurrent < nbPhotos -1){ alert.setPositiveButton("Suivant", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { nbPhotosCurrent ++ ; afficherPhotos(id_demande) ; } }) ; } alert.setNegativeButton("Ok", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { photos = null ; nbPhotos = 0 ; nbPhotosCurrent = 0 ; afficherPhotos(id_demande) ; } }) ; alert.show() ; }else choixEtat(id_demande) ; } private void choixEtat(final int id_demande){ Demande demande = new DemandeServeur().getLocalDemandeWithId(getActivity(), id_demande) ; if(demande.getEtat() == 1){ AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()) ; ImageView iv = new ImageView(getActivity()) ; alert.setView(iv) ; alert.setTitle("Voulez-vous d'autres photos pour cette demande ?") ; alert.setPositiveButton("Oui", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) ; alert.setNegativeButton("Non", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new DemandeServeur().updateDemande(getActivity(), currentUser, id_demande, "etat", "2") ; actualiserListeDemande() ; } }) ; alert.show() ; } } private void renomerDemande(final int position){ AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle("Description de la photo voulue :"); // Set an EditText view to get user input final EditText input = new EditText(getActivity()); input.setText(demandes.get(position).getDescription()) ; alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String desc = input.getText().toString() ; String result = new DemandeServeur().updateDemande(getActivity(), currentUser, demandes.get(position).getId(), "description", desc) ; if(result != null) Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show(); else Toast.makeText(getActivity(), R.string.erreur_connextion, Toast.LENGTH_SHORT).show(); actualiserListeDemande() ; } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); alert.show(); } private void supprimerDemande(final int id_demande){ String result = new DemandeServeur().removeDemande(getActivity(), currentUser, id_demande) ; if(result != null) Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show(); else Toast.makeText(getActivity(), R.string.erreur_connextion, Toast.LENGTH_SHORT).show(); actualiserListeDemande() ; } }
Java
package com.takeaphoto.activity; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.takeaphoto.database.Demande; import com.takeaphoto.database.DemandesBDD; public class MapReponse extends SupportMapFragment { final String EXTRA_LOGIN = "user_login"; private GoogleMap gMap; private Activity mainActivity ; private DemandesBDD demandeBdd ; private ArrayList<MarkerOptions> markers ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); markers = new ArrayList<MarkerOptions>() ; } public void setMainActivity(Activity main) { mainActivity = main ; } public void setDemandeBdd(DemandesBDD demandeBdd){ this.demandeBdd = demandeBdd ; } @Override public void onResume() { super.onResume(); setUpMapIfNeeded(); updateDemandes() ; } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (gMap == null) { // Try to obtain the map from the SupportMapFragment. gMap = getMap(); gMap.setMyLocationEnabled(true); } } private void updateDemandes(){ demandeBdd.open() ; ArrayList<Demande> demandes = demandeBdd.getDemandeWithoutLogin(mainActivity.getIntent().getStringExtra(EXTRA_LOGIN)) ; demandeBdd.close() ; if(demandes != null){ for(Demande d : demandes){ MarkerOptions m = new MarkerOptions() ; m.title(d.getLogin()) ; m.position(new LatLng(d.getLat(), d.getLng())) ; m.snippet(d.getDescription()) ; markers.add(m) ; } } for(MarkerOptions m : markers){ gMap.addMarker(m); } } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View myFragmentView = super.onCreateView(inflater, container, savedInstanceState) ; return myFragmentView; } }
Java
package com.takeaphoto.activity; import java.util.Locale; import android.app.ActionBar; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import com.takeaphoto.utils.CustomViewPager; public class MainActivity extends FragmentActivity implements ActionBar.TabListener { private SectionsPagerAdapter mSectionsPagerAdapter; private CustomViewPager mViewPager; private ManagerActivity manager = new ManagerActivity() ; private MapAddActivity mapAdd = new MapAddActivity() ; private MapReponseActivity mapRep = new MapReponseActivity() ; final int NB_ONGLET = 3 ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (CustomViewPager) findViewById(R.id.photosViewPager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab(actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } mViewPager.setPagingEnabled(false) ; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.main, menu); return true; } public void onResume() { super.onResume(); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {} @Override public void onTabReselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {} /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { Fragment frag = new Fragment() ; switch (position) { case 0: frag = mapAdd ; break; case 1: frag = mapRep ; break ; case 2: frag = manager ; break; } return frag ; } @Override public int getCount() { // Show 3 total pages. return NB_ONGLET; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; } } }
Java
package com.takeaphoto.model; public class Demande { private int id ; private int id_user ; private Double lat ; private Double lng ; private String description ; private int etat ; public Demande(){} public Demande(int id_user, Double lat, Double lng, String description) { this.id_user = id_user; this.lat = lat ; this.lng = lng ; this.description = description; this.etat = 0 ; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getId_user() { return id_user; } public void setId_user(int id_user) { this.id_user = id_user; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getEtat() { return etat; } public void setEtat(int etat) { this.etat = etat; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } @Override public String toString() { return "Demande [id=" + id + ", id_user=" + id_user + ", lat=" + lat + ", lng=" + lng + ", description=" + description + ", etat=" + etat + "]"; } }
Java
package com.takeaphoto.model; public class User { private int id ; private String login ; private String pass ; public User() { } public User(int id, String login, String pass) { this.id=id ; this.login = login; this.pass = pass; } public void setId(int id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public int getId() { return id; } @Override public String toString() { return "User [id=" + id + ", login=" + login + ", pass=" + pass + "]"; } }
Java
package com.takeaphoto.server; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import com.takeaphoto.database.UserBDD; import com.takeaphoto.model.User; public class UserServeur extends Serveur{ static UserBDD userbdd = null; private void userBddIsSet(Context context){ if(userbdd == null) userbdd = new UserBDD(context) ; } public User getUser(Context context, int idUser){ userBddIsSet(context); User user = null ; userbdd.open() ; user = userbdd.getUserWithId(idUser) ; userbdd.close() ; return user ; } public HashMap<String, Object> authentification(Context context, String login, String pass){ userBddIsSet(context); //HashMap<String, Object> resultTmp = null ; ArrayList<String> args = new ArrayList<String>() ; args.add("authentification.php") ; args.add("login="+login); args.add("pass="+pass) ; /*JSONObject joMap = new JSONObject(); JSONArray jArray = new JSONArray(); JSONObject jo = new JSONObject(); try { jo.put("url", "authentification.php"); jo.put("login", login); jo.put("pass", pass); jArray.put(jo); joMap.put("POST", jArray); Log.i("JSONObject ", joMap.toString()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //sendJson(joMap) ; // resultTmp = Serveur.sendJson("authentification.php", args); sendJson(args) ; while(isRunning()){} if(getResultArray() != null){ if(getResultArray().containsKey("id")){ userbdd.open() ; userbdd.clear() ; userbdd.close() ; int id = Integer.parseInt((String)getResultArray().get("id")) ; User u = new User(id, login, pass); userbdd.open() ; userbdd.insertUser(u); userbdd.close() ; } } HashMap<String, Object> tmpMap = getResultArray() ; setResultToFalse() ; return tmpMap ; } public HashMap<String, Object> createUser(Context context, String login, String pass){ userBddIsSet(context); ArrayList<String> args = new ArrayList<String>() ; args.add("create_user.php") ; args.add("login="+login); args.add("pass="+pass) ; sendJson(args) ; while(isRunning()){} HashMap<String, Object> tmpMap = getResultArray() ; setResultToFalse() ; return tmpMap ; } public User getOnlyUser(Context context) { userBddIsSet(context); User user = null ; userbdd.open() ; ArrayList<User> users = userbdd.getALLUser() ; userbdd.close() ; if(users != null && users.size() == 1) user = users.get(0) ; return user ; } }
Java
package com.takeaphoto.server ; import java.util.ArrayList; import java.util.HashMap; public abstract class Serveur { private boolean running = true ; private HashMap<String, Object> resultArray ; @SuppressWarnings("unchecked") public void sendJson(ArrayList<String> args){ setResultToFalse() ; new ServeurAsync(this).execute(args); } public HashMap<String, Object> getResultArray() { return resultArray; } public boolean isRunning() { return running; } public void setResult(HashMap<String, Object> resultArray ){ this.resultArray = resultArray ; } public void setRunning(boolean b){ running = b ; } public void setResultToFalse(){ resultArray = new HashMap<String, Object>() ; resultArray.put("result", "FALSE") ; } }
Java
package com.takeaphoto.server; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import android.util.Log; import com.takeaphoto.model.User; import com.takeaphoto.utils.MCrypt; public class PhotoServeur extends Serveur { public int uploadFile(String sourceFilePath, User currentUser, int id_demande) throws Exception { int serverResponseCode = 0; String upLoadServerUri = "http://jeremiesamson-portfolio.com/wp-content/uploads/takeaphotoforme/upload_media.php"; String params = "?login="+ currentUser.getLogin() + "&pass=" + MCrypt.bytesToHex( new MCrypt().encrypt(currentUser.getPass())) + "&id_demande=" + id_demande; upLoadServerUri += params ; System.out.println(upLoadServerUri); HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFilePath); File f = new File(""); if (!sourceFile.isFile()) { Log.e("uploadFile", "Source File Does not exist : " + sourceFilePath + ", path :" + f.getAbsolutePath()); return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", sourceFilePath); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ sourceFilePath + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); //Toast.makeText(PhotoActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show(); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); //Toast.makeText(PhotoActivity.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show(); Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); } return serverResponseCode; } public ArrayList<Object> getUrls(User currentUser, int id_demande){ ArrayList<Object> resultTmp = null ; ArrayList<String> args = new ArrayList<String>() ; args.add("get_photos.php") ; args.add("login="+currentUser.getLogin()); args.add("pass="+currentUser.getPass()) ; args.add("id_demande="+id_demande); sendJson(args); while(isRunning()){} if(getResultArray() != null){ if(getResultArray() != null){ resultTmp = new ArrayList<Object>() ; for (String mapKey : getResultArray().keySet()) { resultTmp.add(getResultArray().get(mapKey)) ; } } } return resultTmp ; } }
Java
package com.takeaphoto.database; public class Demande { private int id ; private String login ; private Double lat ; private Double lng ; private String description ; private int etat ; public Demande(){} public Demande(String login, Double lat, Double lng, String description) { this.login = login; this.lat = lat ; this.lng = lng ; this.description = description; this.etat = 0 ; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getEtat() { return etat; } public void setEtat(int etat) { this.etat = etat; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } @Override public String toString() { return "Demande [id=" + id + ", login=" + login + ", lat=" + lat + ", lng=" + lng + ", description=" + description + ", etat=" + etat + "]"; } }
Java
package com.takeaphoto.utils; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; public class CustomViewPager extends ViewPager { private boolean enabled; public CustomViewPager(Context context, AttributeSet attrs) { super(context, attrs); this.enabled = true; } @Override public boolean onTouchEvent(MotionEvent event) { if (this.enabled) { return super.onTouchEvent(event); } return false; } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (this.enabled) { return super.onInterceptTouchEvent(event); } return false; } public void setPagingEnabled(boolean enabled) { this.enabled = enabled; } }
Java
package com.takeaphoto.utils; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class MCrypt { private String iv = "securitykey99999";//Dummy iv (CHANGE IT!) private IvParameterSpec ivspec; private SecretKeySpec keyspec; private Cipher cipher; private String SecretKey = "99999keysecurity";//Dummy secretKey (CHANGE IT!) public MCrypt() { ivspec = new IvParameterSpec(iv.getBytes()); keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES"); try { cipher = Cipher.getInstance("AES/CBC/NoPadding"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public byte[] encrypt(String text) throws Exception { if(text == null || text.length() == 0) throw new Exception("Empty string"); byte[] encrypted = null; try { cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { throw new Exception("[encrypt] " + e.getMessage()); } return encrypted; } public byte[] decrypt(String code) throws Exception { if(code == null || code.length() == 0) throw new Exception("Empty string"); byte[] decrypted = null; try { cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); decrypted = cipher.doFinal(hexToBytes(code)); } catch (Exception e) { throw new Exception("[decrypt] " + e.getMessage()); } return decrypted; } public static String bytesToHex(byte[] data) { if (data==null) { return null; } int len = data.length; String str = ""; for (int i=0; i<len; i++) { if ((data[i]&0xFF)<16) str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF); else str = str + java.lang.Integer.toHexString(data[i]&0xFF); } return str; } public static byte[] hexToBytes(String str) { if (str==null) { return null; } else if (str.length() < 2) { return null; } else { int len = str.length() / 2; byte[] buffer = new byte[len]; for (int i=0; i<len; i++) { buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16); } return buffer; } } private static String padString(String source) { char paddingChar = ' '; int size = 16; int x = source.length() % size; int padLength = size - x; for (int i = 0; i < padLength; i++) { source += paddingChar; } return source; } }
Java
public class HelloWorldApp { public static void main(String[] args) { int n=0; System.out.println("I Love Java"); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.test; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.VenueActivity; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.SmallTest; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueActivityInstrumentationTestCase extends ActivityInstrumentationTestCase2<VenueActivity> { public VenueActivityInstrumentationTestCase() { super("com.joelapenna.foursquared", VenueActivity.class); } @SmallTest public void testOnCreate() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.putExtra(Foursquared.EXTRA_VENUE_ID, "40450"); setActivityIntent(intent); VenueActivity activity = getActivity(); activity.openOptionsMenu(); activity.closeOptionsMenu(); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.test; import com.joelapenna.foursquared.Foursquared; import android.test.ApplicationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> { public FoursquaredAppTestCase() { super(Foursquared.class); } @MediumTest public void testLocationMethods() { createApplication(); getApplication().getLastKnownLocation(); getApplication().getLocationListener(); } @SmallTest public void testPreferences() { createApplication(); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareCredentialsException extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareCredentialsException(String message) { super(message); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareError extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareError(String message) { super(message); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareParseException extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareParseException(String message) { super(message); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareException extends Exception { private static final long serialVersionUID = 1L; private String mExtra; public FoursquareException(String message) { super(message); } public FoursquareException(String message, String extra) { super(message); mExtra = extra; } public String getExtra() { return mExtra; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.http.AbstractHttpApi; import com.joelapenna.foursquare.http.HttpApi; import com.joelapenna.foursquare.http.HttpApiWithBasicAuth; import com.joelapenna.foursquare.http.HttpApiWithOAuth; import com.joelapenna.foursquare.parsers.json.CategoryParser; import com.joelapenna.foursquare.parsers.json.CheckinParser; import com.joelapenna.foursquare.parsers.json.CheckinResultParser; import com.joelapenna.foursquare.parsers.json.CityParser; import com.joelapenna.foursquare.parsers.json.CredentialsParser; import com.joelapenna.foursquare.parsers.json.FriendInvitesResultParser; import com.joelapenna.foursquare.parsers.json.GroupParser; import com.joelapenna.foursquare.parsers.json.ResponseParser; import com.joelapenna.foursquare.parsers.json.SettingsParser; import com.joelapenna.foursquare.parsers.json.TipParser; import com.joelapenna.foursquare.parsers.json.TodoParser; import com.joelapenna.foursquare.parsers.json.UserParser; import com.joelapenna.foursquare.parsers.json.VenueParser; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.City; import com.joelapenna.foursquare.types.Credentials; import com.joelapenna.foursquare.types.FriendInvitesResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Settings; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.JSONUtils; import com.joelapenna.foursquared.util.Base64Coder; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ class FoursquareHttpApiV1 { private static final Logger LOG = Logger .getLogger(FoursquareHttpApiV1.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.DEBUG; private static final String DATATYPE = ".json"; private static final String URL_API_AUTHEXCHANGE = "/authexchange"; private static final String URL_API_ADDVENUE = "/addvenue"; private static final String URL_API_ADDTIP = "/addtip"; private static final String URL_API_CITIES = "/cities"; private static final String URL_API_CHECKINS = "/checkins"; private static final String URL_API_CHECKIN = "/checkin"; private static final String URL_API_USER = "/user"; private static final String URL_API_VENUE = "/venue"; private static final String URL_API_VENUES = "/venues"; private static final String URL_API_TIPS = "/tips"; private static final String URL_API_TODOS = "/todos"; private static final String URL_API_FRIEND_REQUESTS = "/friend/requests"; private static final String URL_API_FRIEND_APPROVE = "/friend/approve"; private static final String URL_API_FRIEND_DENY = "/friend/deny"; private static final String URL_API_FRIEND_SENDREQUEST = "/friend/sendrequest"; private static final String URL_API_FRIENDS = "/friends"; private static final String URL_API_FIND_FRIENDS_BY_NAME = "/findfriends/byname"; private static final String URL_API_FIND_FRIENDS_BY_PHONE = "/findfriends/byphone"; private static final String URL_API_FIND_FRIENDS_BY_FACEBOOK = "/findfriends/byfacebook"; private static final String URL_API_FIND_FRIENDS_BY_TWITTER = "/findfriends/bytwitter"; private static final String URL_API_CATEGORIES = "/categories"; private static final String URL_API_HISTORY = "/history"; private static final String URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL = "/findfriends/byphoneoremail"; private static final String URL_API_INVITE_BY_EMAIL = "/invite/byemail"; private static final String URL_API_SETPINGS = "/settings/setpings"; private static final String URL_API_VENUE_FLAG_CLOSED = "/venue/flagclosed"; private static final String URL_API_VENUE_FLAG_MISLOCATED = "/venue/flagmislocated"; private static final String URL_API_VENUE_FLAG_DUPLICATE = "/venue/flagduplicate"; private static final String URL_API_VENUE_PROPOSE_EDIT = "/venue/proposeedit"; private static final String URL_API_USER_UPDATE = "/user/update"; private static final String URL_API_MARK_TODO = "/mark/todo"; private static final String URL_API_MARK_IGNORE = "/mark/ignore"; private static final String URL_API_MARK_DONE = "/mark/done"; private static final String URL_API_UNMARK_TODO = "/unmark/todo"; private static final String URL_API_UNMARK_DONE = "/unmark/done"; private static final String URL_API_TIP_DETAIL = "/tip/detail"; private final DefaultHttpClient mHttpClient = AbstractHttpApi.createHttpClient(); private HttpApi mHttpApi; private final String mApiBaseUrl; private final AuthScope mAuthScope; public FoursquareHttpApiV1(String domain, String clientVersion, boolean useOAuth) { mApiBaseUrl = "https://" + domain + "/v1"; mAuthScope = new AuthScope(domain, 80); if (useOAuth) { mHttpApi = new HttpApiWithOAuth(mHttpClient, clientVersion); } else { mHttpApi = new HttpApiWithBasicAuth(mHttpClient, clientVersion); } } void setCredentials(String phone, String password) { if (phone == null || phone.length() == 0 || password == null || password.length() == 0) { if (DEBUG) LOG.log(Level.FINE, "Clearing Credentials"); mHttpClient.getCredentialsProvider().clear(); } else { if (DEBUG) LOG.log(Level.FINE, "Setting Phone/Password: " + phone + "/******"); mHttpClient.getCredentialsProvider().setCredentials(mAuthScope, new UsernamePasswordCredentials(phone, password)); } } public boolean hasCredentials() { return mHttpClient.getCredentialsProvider().getCredentials(mAuthScope) != null; } public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) { if (DEBUG) { LOG.log(Level.FINE, "Setting consumer key/secret: " + oAuthConsumerKey + " " + oAuthConsumerSecret); } ((HttpApiWithOAuth) mHttpApi).setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret); } public void setOAuthTokenWithSecret(String token, String secret) { if (DEBUG) LOG.log(Level.FINE, "Setting oauth token/secret: " + token + " " + secret); ((HttpApiWithOAuth) mHttpApi).setOAuthTokenWithSecret(token, secret); } public boolean hasOAuthTokenWithSecret() { return ((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret(); } /* * /authexchange?oauth_consumer_key=d123...a1bffb5&oauth_consumer_secret=fec... * 18 */ public Credentials authExchange(String phone, String password) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { if (((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret()) { throw new IllegalStateException("Cannot do authExchange with OAuthToken already set"); } HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_AUTHEXCHANGE), // new BasicNameValuePair("fs_username", phone), // new BasicNameValuePair("fs_password", password)); return (Credentials) mHttpApi.doHttpRequest(httpPost, new CredentialsParser()); } /* * /addtip?vid=1234&text=I%20added%20a%20tip&type=todo (type defaults "tip") */ Tip addtip(String vid, String text, String type, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDTIP), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("text", text), // new BasicNameValuePair("type", type), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * @param name the name of the venue * @param address the address of the venue (e.g., "202 1st Avenue") * @param crossstreet the cross streets (e.g., "btw Grand & Broome") * @param city the city name where this venue is * @param state the state where the city is * @param zip (optional) the ZIP code for the venue * @param phone (optional) the phone number for the venue * @return * @throws FoursquareException * @throws FoursquareCredentialsException * @throws FoursquareError * @throws IOException */ Venue addvenue(String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDVENUE), // new BasicNameValuePair("name", name), // new BasicNameValuePair("address", address), // new BasicNameValuePair("crossstreet", crossstreet), // new BasicNameValuePair("city", city), // new BasicNameValuePair("state", state), // new BasicNameValuePair("zip", zip), // new BasicNameValuePair("phone", phone), // new BasicNameValuePair("primarycategoryid", categoryId), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Venue) mHttpApi.doHttpRequest(httpPost, new VenueParser()); } /* * /cities */ @SuppressWarnings("unchecked") Group<City> cities() throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CITIES)); return (Group<City>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CityParser())); } /* * /checkins? */ @SuppressWarnings("unchecked") Group<Checkin> checkins(String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CHECKINS), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt)); return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser())); } /* * /checkin?vid=1234&venue=Noc%20Noc&shout=Come%20here&private=0&twitter=1 */ CheckinResult checkin(String vid, String venue, String geolat, String geolong, String geohacc, String geovacc, String geoalt, String shout, boolean isPrivate, boolean tellFollowers, boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_CHECKIN), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("venue", venue), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("shout", shout), // new BasicNameValuePair("private", (isPrivate) ? "1" : "0"), // new BasicNameValuePair("followers", (tellFollowers) ? "1" : "0"), // new BasicNameValuePair("twitter", (twitter) ? "1" : "0"), // new BasicNameValuePair("facebook", (facebook) ? "1" : "0"), // new BasicNameValuePair("markup", "android")); // used only by android for checkin result 'extras'. return (CheckinResult) mHttpApi.doHttpRequest(httpPost, new CheckinResultParser()); } /** * /user?uid=9937 */ User user(String uid, boolean mayor, boolean badges, boolean stats, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_USER), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("mayor", (mayor) ? "1" : "0"), // new BasicNameValuePair("badges", (badges) ? "1" : "0"), // new BasicNameValuePair("stats", (stats) ? "1" : "0"), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (User) mHttpApi.doHttpRequest(httpGet, new UserParser()); } /** * /venues?geolat=37.770900&geolong=-122.43698 */ @SuppressWarnings("unchecked") Group<Group<Venue>> venues(String geolat, String geolong, String geohacc, String geovacc, String geoalt, String query, int limit) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUES), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("q", query), // new BasicNameValuePair("l", String.valueOf(limit))); return (Group<Group<Venue>>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new GroupParser(new VenueParser()))); } /** * /venue?vid=1234 */ Venue venue(String vid, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUE), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Venue) mHttpApi.doHttpRequest(httpGet, new VenueParser()); } /** * /tips?geolat=37.770900&geolong=-122.436987&l=1 */ @SuppressWarnings("unchecked") Group<Tip> tips(String geolat, String geolong, String geohacc, String geovacc, String geoalt, String uid, String filter, String sort, int limit) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIPS), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("filter", filter), // new BasicNameValuePair("sort", sort), // new BasicNameValuePair("l", String.valueOf(limit)) // ); return (Group<Tip>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new TipParser())); } /** * /todos?geolat=37.770900&geolong=-122.436987&l=1&sort=[recent|nearby] */ @SuppressWarnings("unchecked") Group<Todo> todos(String uid, String geolat, String geolong, String geohacc, String geovacc, String geoalt, boolean recent, boolean nearby, int limit) throws FoursquareException, FoursquareError, IOException { String sort = null; if (recent) { sort = "recent"; } else if (nearby) { sort = "nearby"; } HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TODOS), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("sort", sort), // new BasicNameValuePair("l", String.valueOf(limit)) // ); return (Group<Todo>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new TodoParser())); } /* * /friends?uid=9937 */ @SuppressWarnings("unchecked") Group<User> friends(String uid, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIENDS), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /* * /friend/requests */ @SuppressWarnings("unchecked") Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIEND_REQUESTS)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /* * /friend/approve?uid=9937 */ User friendApprove(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_APPROVE), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /* * /friend/deny?uid=9937 */ User friendDeny(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_DENY), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /* * /friend/sendrequest?uid=9937 */ User friendSendrequest(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_SENDREQUEST), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /** * /findfriends/byname?q=john doe, mary smith */ @SuppressWarnings("unchecked") public Group<User> findFriendsByName(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_NAME), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /** * /findfriends/byphone?q=555-5555,555-5556 */ @SuppressWarnings("unchecked") public Group<User> findFriendsByPhone(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser())); } /** * /findfriends/byfacebook?q=friendid,friendid,friendid */ @SuppressWarnings("unchecked") public Group<User> findFriendsByFacebook(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_FACEBOOK), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser())); } /** * /findfriends/bytwitter?q=yourtwittername */ @SuppressWarnings("unchecked") public Group<User> findFriendsByTwitter(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_TWITTER), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /** * /categories */ @SuppressWarnings("unchecked") public Group<Category> categories() throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CATEGORIES)); return (Group<Category>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CategoryParser())); } /** * /history */ @SuppressWarnings("unchecked") public Group<Checkin> history(String limit, String sinceid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_HISTORY), new BasicNameValuePair("l", limit), new BasicNameValuePair("sinceid", sinceid)); return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser())); } /** * /mark/todo */ public Todo markTodo(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), // new BasicNameValuePair("tid", tid)); return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser()); } /** * This is a hacky special case, hopefully the api will be updated in v2 for this. * /mark/todo */ public Todo markTodoVenue(String vid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), // new BasicNameValuePair("vid", vid)); return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser()); } /** * /mark/ignore */ public Tip markIgnore(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_IGNORE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /mark/done */ public Tip markDone(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_DONE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /unmark/todo */ public Tip unmarkTodo(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_TODO), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /unmark/done */ public Tip unmarkDone(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_DONE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /tip/detail?tid=1234 */ public Tip tipDetail(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIP_DETAIL), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpGet, new TipParser()); } /** * /findfriends/byphoneoremail?p=comma-sep-list-of-phones&e=comma-sep-list-of-emails */ public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL), // new BasicNameValuePair("p", phones), new BasicNameValuePair("e", emails)); return (FriendInvitesResult) mHttpApi.doHttpRequest(httpPost, new FriendInvitesResultParser()); } /** * /invite/byemail?q=comma-sep-list-of-emails */ public Response inviteByEmail(String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_INVITE_BY_EMAIL), // new BasicNameValuePair("q", emails)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /settings/setpings?self=[on|off] */ public Settings setpings(boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), // new BasicNameValuePair("self", on ? "on" : "off")); return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser()); } /** * /settings/setpings?uid=userid */ public Settings setpings(String userid, boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), // new BasicNameValuePair(userid, on ? "on" : "off")); return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser()); } /** * /venue/flagclosed?vid=venueid */ public Response flagclosed(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_CLOSED), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/flagmislocated?vid=venueid */ public Response flagmislocated(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_MISLOCATED), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/flagduplicate?vid=venueid */ public Response flagduplicate(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_DUPLICATE), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/prposeedit?vid=venueid&name=... */ public Response proposeedit(String venueId, String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_PROPOSE_EDIT), // new BasicNameValuePair("vid", venueId), // new BasicNameValuePair("name", name), // new BasicNameValuePair("address", address), // new BasicNameValuePair("crossstreet", crossstreet), // new BasicNameValuePair("city", city), // new BasicNameValuePair("state", state), // new BasicNameValuePair("zip", zip), // new BasicNameValuePair("phone", phone), // new BasicNameValuePair("primarycategoryid", categoryId), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } private String fullUrl(String url) { return mApiBaseUrl + url + DATATYPE; } /** * /user/update * Need to bring this method under control like the rest of the api methods. Leaving it * in this state as authorization will probably switch from basic auth in the near future * anyway, will have to be updated. Also unlike the other methods, we're sending up data * which aren't basic name/value pairs. */ public User userUpdate(String imagePathToJpg, String username, String password) throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException { String BOUNDARY = "------------------319831265358979362846"; String lineEnd = "\r\n"; String twoHyphens = "--"; int maxBufferSize = 8192; File file = new File(imagePathToJpg); FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(fullUrl(URL_API_USER_UPDATE)); HttpURLConnection conn = mHttpApi.createHttpURLConnectionPost(url, BOUNDARY); conn.setRequestProperty("Authorization", "Basic " + Base64Coder.encodeString(username + ":" + password)); // We are always saving the image to a jpg so we can use .jpg as the extension below. DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + BOUNDARY + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"image,jpeg\";filename=\"" + "image.jpeg" +"\"" + lineEnd); dos.writeBytes("Content-Type: " + "image/jpeg" + lineEnd); dos.writeBytes(lineEnd); int bytesAvailable = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); int totalBytesRead = bytesRead; while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); totalBytesRead = totalBytesRead + bytesRead; } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + BOUNDARY + twoHyphens + lineEnd); fileInputStream.close(); dos.flush(); dos.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String responseLine = ""; while ((responseLine = in.readLine()) != null) { response.append(responseLine); } in.close(); try { return (User)JSONUtils.consume(new UserParser(), response.toString()); } catch (Exception ex) { throw new FoursquareParseException( "Error parsing user photo upload response, invalid json."); } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * @author Joe LaPenna (joe@joelapenna.com) */ public interface HttpApi { abstract public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException; abstract public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException; abstract public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs); abstract public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs); abstract public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException; }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import oauth.signpost.OAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.signature.SignatureMethod; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class HttpApiWithOAuth extends AbstractHttpApi { protected static final Logger LOG = Logger.getLogger(HttpApiWithOAuth.class.getCanonicalName()); protected static final boolean DEBUG = Foursquare.DEBUG; private OAuthConsumer mConsumer; public HttpApiWithOAuth(DefaultHttpClient httpClient, String clientVersion) { super(httpClient, clientVersion); } public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI()); try { if (DEBUG) LOG.log(Level.FINE, "Signing request: " + httpRequest.getURI()); if (DEBUG) LOG.log(Level.FINE, "Consumer: " + mConsumer.getConsumerKey() + ", " + mConsumer.getConsumerSecret()); if (DEBUG) LOG.log(Level.FINE, "Token: " + mConsumer.getToken() + ", " + mConsumer.getTokenSecret()); mConsumer.sign(httpRequest); } catch (OAuthMessageSignerException e) { if (DEBUG) LOG.log(Level.FINE, "OAuthMessageSignerException", e); throw new RuntimeException(e); } catch (OAuthExpectationFailedException e) { if (DEBUG) LOG.log(Level.FINE, "OAuthExpectationFailedException", e); throw new RuntimeException(e); } return executeHttpRequest(httpRequest, parser); } public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareError, FoursquareParseException, IOException, FoursquareCredentialsException { throw new RuntimeException("Haven't written this method yet."); } public void setOAuthConsumerCredentials(String key, String secret) { mConsumer = new CommonsHttpOAuthConsumer(key, secret, SignatureMethod.HMAC_SHA1); } public void setOAuthTokenWithSecret(String token, String tokenSecret) { verifyConsumer(); if (token == null && tokenSecret == null) { if (DEBUG) LOG.log(Level.FINE, "Resetting consumer due to null token/secret."); String consumerKey = mConsumer.getConsumerKey(); String consumerSecret = mConsumer.getConsumerSecret(); mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1); } else { mConsumer.setTokenWithSecret(token, tokenSecret); } } public boolean hasOAuthTokenWithSecret() { verifyConsumer(); return (mConsumer.getToken() != null) && (mConsumer.getTokenSecret() != null); } private void verifyConsumer() { if (mConsumer == null) { throw new IllegalStateException( "Cannot call method without setting consumer credentials."); } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.ClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import java.io.IOException; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class HttpApiWithBasicAuth extends AbstractHttpApi { private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider)context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; public HttpApiWithBasicAuth(DefaultHttpClient httpClient, String clientVersion) { super(httpClient, clientVersion); httpClient.addRequestInterceptor(preemptiveAuth, 0); } public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { return executeHttpRequest(httpRequest, parser); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.util.JSONUtils; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.params.HttpClientParams; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract public class AbstractHttpApi implements HttpApi { protected static final Logger LOG = Logger.getLogger(AbstractHttpApi.class.getCanonicalName()); protected static final boolean DEBUG = Foursquare.DEBUG; private static final String DEFAULT_CLIENT_VERSION = "com.joelapenna.foursquare"; private static final String CLIENT_VERSION_HEADER = "User-Agent"; private static final int TIMEOUT = 60; private final DefaultHttpClient mHttpClient; private final String mClientVersion; public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) { mHttpClient = httpClient; if (clientVersion != null) { mClientVersion = clientVersion; } else { mClientVersion = DEFAULT_CLIENT_VERSION; } } public FoursquareType executeHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI()); HttpResponse response = executeHttpRequest(httpRequest); if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: " + httpRequest.getURI().toString()); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case 200: String content = EntityUtils.toString(response.getEntity()); return JSONUtils.consume(parser, content); case 400: if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 400"); throw new FoursquareException( response.getStatusLine().toString(), EntityUtils.toString(response.getEntity())); case 401: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 401"); throw new FoursquareCredentialsException(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 404"); throw new FoursquareException(response.getStatusLine().toString()); case 500: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 500"); throw new FoursquareException("Foursquare is down. Try again later."); default: if (DEBUG) LOG.log(Level.FINE, "Default case for status code reached: " + response.getStatusLine().toString()); response.getEntity().consumeContent(); throw new FoursquareException("Error connecting to Foursquare: " + statusCode + ". Try again later."); } } public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpPost: " + url); HttpPost httpPost = createHttpPost(url, nameValuePairs); HttpResponse response = executeHttpRequest(httpPost); if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: " + httpPost.getURI().toString()); switch (response.getStatusLine().getStatusCode()) { case 200: try { return EntityUtils.toString(response.getEntity()); } catch (ParseException e) { throw new FoursquareParseException(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new FoursquareCredentialsException(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new FoursquareException(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new FoursquareException(response.getStatusLine().toString()); } } /** * execute() an httpRequest catching exceptions and returning null instead. * * @param httpRequest * @return * @throws IOException */ public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException { if (DEBUG) LOG.log(Level.FINE, "executing HttpRequest for: " + httpRequest.getURI().toString()); try { mHttpClient.getConnectionManager().closeExpiredConnections(); return mHttpClient.execute(httpRequest); } catch (IOException e) { httpRequest.abort(); throw e; } } public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) { if (DEBUG) LOG.log(Level.FINE, "creating HttpGet for: " + url); String query = URLEncodedUtils.format(stripNulls(nameValuePairs), HTTP.UTF_8); HttpGet httpGet = new HttpGet(url + "?" + query); httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion); if (DEBUG) LOG.log(Level.FINE, "Created: " + httpGet.getURI()); return httpGet; } public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs) { if (DEBUG) LOG.log(Level.FINE, "creating HttpPost for: " + url); HttpPost httpPost = new HttpPost(url); httpPost.addHeader(CLIENT_VERSION_HEADER, mClientVersion); try { httpPost.setEntity(new UrlEncodedFormEntity(stripNulls(nameValuePairs), HTTP.UTF_8)); } catch (UnsupportedEncodingException e1) { throw new IllegalArgumentException("Unable to encode http parameters."); } if (DEBUG) LOG.log(Level.FINE, "Created: " + httpPost); return httpPost; } public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(TIMEOUT * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty(CLIENT_VERSION_HEADER, mClientVersion); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); return conn; } private List<NameValuePair> stripNulls(NameValuePair... nameValuePairs) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (int i = 0; i < nameValuePairs.length; i++) { NameValuePair param = nameValuePairs[i]; if (param.getValue() != null) { if (DEBUG) LOG.log(Level.FINE, "Param: " + param); params.add(param); } } return params; } /** * Create a thread-safe client. This client does not do redirecting, to allow us to capture * correct "error" codes. * * @return HttpClient */ public static final DefaultHttpClient createHttpClient() { // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Set some client http client parameter defaults. final HttpParams httpParams = createHttpParams(); HttpClientParams.setRedirecting(httpParams, false); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); } /** * Create the default HTTP protocol parameters. */ private static final HttpParams createHttpParams() { final HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); return params; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import com.joelapenna.foursquare.util.ParcelUtils; import android.os.Parcel; import android.os.Parcelable; /** * @date March 6, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Category implements FoursquareType, Parcelable { /** The category's id. */ private String mId; /** Full category path name, like Nightlife:Bars. */ private String mFullPathName; /** Simple name of the category. */ private String mNodeName; /** Url of the icon associated with this category. */ private String mIconUrl; /** Categories can be nested within one another too. */ private Group<Category> mChildCategories; public Category() { mChildCategories = new Group<Category>(); } private Category(Parcel in) { mChildCategories = new Group<Category>(); mId = ParcelUtils.readStringFromParcel(in); mFullPathName = ParcelUtils.readStringFromParcel(in); mNodeName = ParcelUtils.readStringFromParcel(in); mIconUrl = ParcelUtils.readStringFromParcel(in); int numCategories = in.readInt(); for (int i = 0; i < numCategories; i++) { Category category = in.readParcelable(Category.class.getClassLoader()); mChildCategories.add(category); } } public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() { public Category createFromParcel(Parcel in) { return new Category(in); } @Override public Category[] newArray(int size) { return new Category[size]; } }; public String getId() { return mId; } public void setId(String id) { mId = id; } public String getFullPathName() { return mFullPathName; } public void setFullPathName(String fullPathName) { mFullPathName = fullPathName; } public String getNodeName() { return mNodeName; } public void setNodeName(String nodeName) { mNodeName = nodeName; } public String getIconUrl() { return mIconUrl; } public void setIconUrl(String iconUrl) { mIconUrl = iconUrl; } public Group<Category> getChildCategories() { return mChildCategories; } public void setChildCategories(Group<Category> categories) { mChildCategories = categories; } @Override public void writeToParcel(Parcel out, int flags) { ParcelUtils.writeStringToParcel(out, mId); ParcelUtils.writeStringToParcel(out, mFullPathName); ParcelUtils.writeStringToParcel(out, mNodeName); ParcelUtils.writeStringToParcel(out, mIconUrl); out.writeInt(mChildCategories.size()); for (Category it : mChildCategories) { out.writeParcelable(it, flags); } } @Override public int describeContents() { return 0; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import java.util.ArrayList; /** * @date 2010-05-05 * @author Mark Wyszomierski (markww@gmail.com) */ public class Emails extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; /** * @author Joe LaPenna (joe@joelapenna.com) */ public interface FoursquareType { }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; import java.util.Collection; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Group<T extends FoursquareType> extends ArrayList<T> implements FoursquareType { private static final long serialVersionUID = 1L; private String mType; public Group() { super(); } public Group(Collection<T> collection) { super(collection); } public void setType(String type) { mType = type; } public String getType() { return mType; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; /** * @date 2010-05-05 * @author Mark Wyszomierski (markww@gmail.com) */ public class FriendInvitesResult implements FoursquareType { /** * Users that are in our contact book by email or phone, are already on foursquare, * but are not our friends. */ private Group<User> mContactsOnFoursquare; /** * Users not on foursquare, but in our contact book by email or phone. These are * users we have not already sent an email invite to. */ private Emails mContactEmailsNotOnFoursquare; /** * A list of email addresses we've already sent email invites to. */ private Emails mContactEmailsNotOnFoursquareAlreadyInvited; public FriendInvitesResult() { mContactsOnFoursquare = new Group<User>(); mContactEmailsNotOnFoursquare = new Emails(); mContactEmailsNotOnFoursquareAlreadyInvited = new Emails(); } public Group<User> getContactsOnFoursquare() { return mContactsOnFoursquare; } public void setContactsOnFoursquare(Group<User> contactsOnFoursquare) { mContactsOnFoursquare = contactsOnFoursquare; } public Emails getContactEmailsNotOnFoursquare() { return mContactEmailsNotOnFoursquare; } public void setContactEmailsOnNotOnFoursquare(Emails emails) { mContactEmailsNotOnFoursquare = emails; } public Emails getContactEmailsNotOnFoursquareAlreadyInvited() { return mContactEmailsNotOnFoursquareAlreadyInvited; } public void setContactEmailsOnNotOnFoursquareAlreadyInvited(Emails emails) { mContactEmailsNotOnFoursquareAlreadyInvited = emails; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; /** * @date April 14, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Types extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; /** * @date April 28, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Response implements FoursquareType { private String mValue; public Response() { } public String getValue() { return mValue; } public void setValue(String value) { mValue = value; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; import java.util.List; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Tags extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; public Tags() { super(); } public Tags(List<String> values) { super(); addAll(values); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import com.joelapenna.foursquare.util.ParcelUtils; import android.os.Parcel; import android.os.Parcelable; /** * @date September 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Todo implements FoursquareType, Parcelable { private String mCreated; private String mId; private Tip mTip; public Todo() { } private Todo(Parcel in) { mCreated = ParcelUtils.readStringFromParcel(in); mId = ParcelUtils.readStringFromParcel(in); if (in.readInt() == 1) { mTip = in.readParcelable(Tip.class.getClassLoader()); } } public static final Parcelable.Creator<Todo> CREATOR = new Parcelable.Creator<Todo>() { public Todo createFromParcel(Parcel in) { return new Todo(in); } @Override public Todo[] newArray(int size) { return new Todo[size]; } }; public String getCreated() { return mCreated; } public void setCreated(String created) { mCreated = created; } public String getId() { return mId; } public void setId(String id) { mId = id; } public Tip getTip() { return mTip; } public void setTip(Tip tip) { mTip = tip; } @Override public void writeToParcel(Parcel out, int flags) { ParcelUtils.writeStringToParcel(out, mCreated); ParcelUtils.writeStringToParcel(out, mId); if (mTip != null) { out.writeInt(1); out.writeParcelable(mTip, flags); } else { out.writeInt(0); } } @Override public int describeContents() { return 0; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; import android.os.Parcel; /** * @date March 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ParcelUtils { public static void writeStringToParcel(Parcel out, String str) { if (str != null) { out.writeInt(1); out.writeString(str); } else { out.writeInt(0); } } public static String readStringFromParcel(Parcel in) { int flag = in.readInt(); if (flag == 1) { return in.readString(); } else { return null; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.util; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class MayorUtils { public static final String TYPE_NOCHANGE = "nochange"; public static final String TYPE_NEW = "new"; public static final String TYPE_STOLEN = "stolen"; }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.util; import com.joelapenna.foursquare.types.Venue; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueUtils { public static final boolean isValid(Venue venue) { return !(venue == null || venue.getId() == null || venue.getId().length() == 0); } public static final boolean hasValidLocation(Venue venue) { boolean valid = false; if (venue != null) { String geoLat = venue.getGeolat(); String geoLong = venue.getGeolong(); if (!(geoLat == null || geoLat.length() == 0 || geoLong == null || geoLong.length() == 0)) { if (geoLat != "0" || geoLong != "0") { valid = true; } } } return valid; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; /** * This is not ideal. * * @date July 1, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class IconUtils { private static IconUtils mInstance; private boolean mRequestHighDensityIcons; private IconUtils() { mRequestHighDensityIcons = false; } public static IconUtils get() { if (mInstance == null) { mInstance = new IconUtils(); } return mInstance; } public boolean getRequestHighDensityIcons() { return mRequestHighDensityIcons; } public void setRequestHighDensityIcons(boolean requestHighDensityIcons) { mRequestHighDensityIcons = requestHighDensityIcons; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.parsers.json.TipParser; import com.joelapenna.foursquare.types.FoursquareType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; public class JSONUtils { private static final boolean DEBUG = Foursquare.DEBUG; private static final Logger LOG = Logger.getLogger(TipParser.class.getCanonicalName()); /** * Takes a parser, a json string, and returns a foursquare type. */ public static FoursquareType consume(Parser<? extends FoursquareType> parser, String content) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) { LOG.log(Level.FINE, "http response: " + content); } try { // The v1 API returns the response raw with no wrapper. Depending on the // type of API call, the content might be a JSONObject or a JSONArray. // Since JSONArray does not derive from JSONObject, we need to check for // either of these cases to parse correctly. JSONObject json = new JSONObject(content); Iterator<String> it = (Iterator<String>)json.keys(); if (it.hasNext()) { String key = (String)it.next(); if (key.equals("error")) { throw new FoursquareException(json.getString(key)); } else { Object obj = json.get(key); if (obj instanceof JSONArray) { return parser.parse((JSONArray)obj); } else { return parser.parse((JSONObject)obj); } } } else { throw new FoursquareException("Error parsing JSON response, object had no single child key."); } } catch (JSONException ex) { throw new FoursquareException("Error parsing JSON response: " + ex.getMessage()); } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.Credentials; import com.joelapenna.foursquare.types.FriendInvitesResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Settings; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import android.net.Uri; import android.text.TextUtils; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Foursquare { private static final Logger LOG = Logger.getLogger("com.joelapenna.foursquare"); public static final boolean DEBUG = false; public static final boolean PARSER_DEBUG = false; public static final String FOURSQUARE_API_DOMAIN = "api.foursquare.com"; public static final String FOURSQUARE_MOBILE_ADDFRIENDS = "http://m.foursquare.com/addfriends"; public static final String FOURSQUARE_MOBILE_FRIENDS = "http://m.foursquare.com/friends"; public static final String FOURSQUARE_MOBILE_SIGNUP = "http://m.foursquare.com/signup"; public static final String FOURSQUARE_PREFERENCES = "http://foursquare.com/settings"; public static final String MALE = "male"; public static final String FEMALE = "female"; private String mPhone; private String mPassword; private FoursquareHttpApiV1 mFoursquareV1; @V1 public Foursquare(FoursquareHttpApiV1 httpApi) { mFoursquareV1 = httpApi; } public void setCredentials(String phone, String password) { mPhone = phone; mPassword = password; mFoursquareV1.setCredentials(phone, password); } @V1 public void setOAuthToken(String token, String secret) { mFoursquareV1.setOAuthTokenWithSecret(token, secret); } @V1 public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) { mFoursquareV1.setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret); } public void clearAllCredentials() { setCredentials(null, null); setOAuthToken(null, null); } @V1 public boolean hasCredentials() { return mFoursquareV1.hasCredentials() && mFoursquareV1.hasOAuthTokenWithSecret(); } @V1 public boolean hasLoginAndPassword() { return mFoursquareV1.hasCredentials(); } @V1 public Credentials authExchange() throws FoursquareException, FoursquareError, FoursquareCredentialsException, IOException { if (mFoursquareV1 == null) { throw new NoSuchMethodError( "authExchange is unavailable without a consumer key/secret."); } return mFoursquareV1.authExchange(mPhone, mPassword); } @V1 public Tip addTip(String vid, String text, String type, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.addtip(vid, text, type, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Tip tipDetail(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.tipDetail(tid); } @V1 @LocationRequired public Venue addVenue(String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.addvenue(name, address, crossstreet, city, state, zip, phone, categoryId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public CheckinResult checkin(String venueId, String venueName, Location location, String shout, boolean isPrivate, boolean tellFollowers, boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.checkin(venueId, venueName, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, shout, isPrivate, tellFollowers, twitter, facebook); } @V1 public Group<Checkin> checkins(Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.checkins(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Group<User> friends(String userId, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.friends(userId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.friendRequests(); } @V1 public User friendApprove(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendApprove(userId); } @V1 public User friendDeny(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendDeny(userId); } @V1 public User friendSendrequest(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendSendrequest(userId); } @V1 public Group<Tip> tips(Location location, String uid, String filter, String sort, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.tips(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, uid, filter, sort, limit); } @V1 public Group<Todo> todos(Location location, String uid, boolean recent, boolean nearby, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.todos(uid, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, recent, nearby, limit); } @V1 public User user(String user, boolean mayor, boolean badges, boolean stats, Location location) throws FoursquareException, FoursquareError, IOException { if (location != null) { return mFoursquareV1.user(user, mayor, badges, stats, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } else { return mFoursquareV1.user(user, mayor, badges, stats, null, null, null, null, null); } } @V1 public Venue venue(String id, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.venue(id, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 @LocationRequired public Group<Group<Venue>> venues(Location location, String query, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.venues(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, query, limit); } @V1 public Group<User> findFriendsByName(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByName(text); } @V1 public Group<User> findFriendsByPhone(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByPhone(text); } @V1 public Group<User> findFriendsByFacebook(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByFacebook(text); } @V1 public Group<User> findFriendsByTwitter(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByTwitter(text); } @V1 public Group<Category> categories() throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.categories(); } @V1 public Group<Checkin> history(String limit, String sinceid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.history(limit, sinceid); } @V1 public Todo markTodo(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markTodo(tid); } @V1 public Todo markTodoVenue(String vid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markTodoVenue(vid); } @V1 public Tip markIgnore(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markIgnore(tid); } @V1 public Tip markDone(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markDone(tid); } @V1 public Tip unmarkTodo(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.unmarkTodo(tid); } @V1 public Tip unmarkDone(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.unmarkDone(tid); } @V1 public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.findFriendsByPhoneOrEmail(phones, emails); } @V1 public Response inviteByEmail(String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.inviteByEmail(emails); } @V1 public Settings setpings(boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.setpings(on); } @V1 public Settings setpings(String userid, boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.setpings(userid, on); } @V1 public Response flagclosed(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagclosed(venueid); } @V1 public Response flagmislocated(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagmislocated(venueid); } @V1 public Response flagduplicate(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagduplicate(venueid); } @V1 public Response proposeedit(String venueId, String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, Location location) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.proposeedit(venueId, name, address, crossstreet, city, state, zip, phone, categoryId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public User userUpdate(String imagePathToJpg, String username, String password) throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException { return mFoursquareV1.userUpdate(imagePathToJpg, username, password); } public static final FoursquareHttpApiV1 createHttpApi(String domain, String clientVersion, boolean useOAuth) { LOG.log(Level.INFO, "Using foursquare.com for requests."); return new FoursquareHttpApiV1(domain, clientVersion, useOAuth); } public static final FoursquareHttpApiV1 createHttpApi(String clientVersion, boolean useOAuth) { return createHttpApi(FOURSQUARE_API_DOMAIN, clientVersion, useOAuth); } public static final String createLeaderboardUrl(String userId, Location location) { Uri.Builder builder = new Uri.Builder() // .scheme("http") // .authority("foursquare.com") // .appendEncodedPath("/iphone/me") // .appendQueryParameter("view", "all") // .appendQueryParameter("scope", "friends") // .appendQueryParameter("uid", userId); if (!TextUtils.isEmpty(location.geolat)) { builder.appendQueryParameter("geolat", location.geolat); } if (!TextUtils.isEmpty(location.geolong)) { builder.appendQueryParameter("geolong", location.geolong); } if (!TextUtils.isEmpty(location.geohacc)) { builder.appendQueryParameter("geohacc", location.geohacc); } if (!TextUtils.isEmpty(location.geovacc)) { builder.appendQueryParameter("geovacc", location.geovacc); } return builder.build().toString(); } /** * This api is supported in the V1 API documented at: * http://groups.google.com/group/foursquare-api/web/api-documentation */ @interface V1 { } /** * This api call requires a location. */ @interface LocationRequired { } public static class Location { String geolat = null; String geolong = null; String geohacc = null; String geovacc = null; String geoalt = null; public Location() { } public Location(final String geolat, final String geolong, final String geohacc, final String geovacc, final String geoalt) { this.geolat = geolat; this.geolong = geolong; this.geohacc = geohacc; this.geovacc = geovacc; this.geoalt = geovacc; } public Location(final String geolat, final String geolong) { this(geolat, geolong, null, null, null); } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Emails; import com.joelapenna.foursquare.types.FriendInvitesResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class FriendInvitesResultParser extends AbstractParser<FriendInvitesResult> { @Override public FriendInvitesResult parse(JSONObject json) throws JSONException { FriendInvitesResult obj = new FriendInvitesResult(); if (json.has("users")) { obj.setContactsOnFoursquare( new GroupParser( new UserParser()).parse(json.getJSONArray("users"))); } if (json.has("emails")) { Emails emails = new Emails(); if (json.optJSONObject("emails") != null) { JSONObject emailsAsObject = json.getJSONObject("emails"); emails.add(emailsAsObject.getString("email")); } else if (json.optJSONArray("emails") != null) { JSONArray emailsAsArray = json.getJSONArray("emails"); for (int i = 0; i < emailsAsArray.length(); i++) { emails.add(emailsAsArray.getString(i)); } } obj.setContactEmailsOnNotOnFoursquare(emails); } if (json.has("invited")) { Emails emails = new Emails(); JSONArray array = json.getJSONArray("invited"); for (int i = 0; i < array.length(); i++) { emails.add(array.getString(i)); } obj.setContactEmailsOnNotOnFoursquareAlreadyInvited(emails); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.User; import org.json.JSONException; import org.json.JSONObject; import java.util.logging.Level; import java.util.logging.Logger; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserParser extends AbstractParser<User> { @Override public User parse(JSONObject json) throws JSONException { User user = new User(); if (json.has("badges")) { user.setBadges( new GroupParser( new BadgeParser()).parse(json.getJSONArray("badges"))); } if (json.has("badgecount")) { user.setBadgeCount(json.getInt("badgecount")); } if (json.has("checkin")) { user.setCheckin(new CheckinParser().parse(json.getJSONObject("checkin"))); } if (json.has("checkincount")) { user.setCheckinCount(json.getInt("checkincount")); } if (json.has("created")) { user.setCreated(json.getString("created")); } if (json.has("email")) { user.setEmail(json.getString("email")); } if (json.has("facebook")) { user.setFacebook(json.getString("facebook")); } if (json.has("firstname")) { user.setFirstname(json.getString("firstname")); } if (json.has("followercount")) { user.setFollowerCount(json.getInt("followercount")); } if (json.has("friendcount")) { user.setFriendCount(json.getInt("friendcount")); } if (json.has("friendsincommon")) { user.setFriendsInCommon( new GroupParser( new UserParser()).parse(json.getJSONArray("friendsincommon"))); } if (json.has("friendstatus")) { user.setFriendstatus(json.getString("friendstatus")); } if (json.has("gender")) { user.setGender(json.getString("gender")); } if (json.has("hometown")) { user.setHometown(json.getString("hometown")); } if (json.has("id")) { user.setId(json.getString("id")); } if (json.has("lastname")) { user.setLastname(json.getString("lastname")); } if (json.has("mayor")) { user.setMayorships( new GroupParser( new VenueParser()).parse(json.getJSONArray("mayor"))); } if (json.has("mayorcount")) { user.setMayorCount(json.getInt("mayorcount")); } if (json.has("phone")) { user.setPhone(json.getString("phone")); } if (json.has("photo")) { user.setPhoto(json.getString("photo")); } if (json.has("settings")) { user.setSettings(new SettingsParser().parse(json.getJSONObject("settings"))); } if (json.has("tipcount")) { user.setTipCount(json.getInt("tipcount")); } if (json.has("todocount")) { user.setTodoCount(json.getInt("todocount")); } if (json.has("twitter")) { user.setTwitter(json.getString("twitter")); } if (json.has("types")) { user.setTypes(new TypesParser().parseAsJSONArray(json.getJSONArray("types"))); } return user; } //@Override //public String getObjectName() { // return "user"; //} }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Mayor; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class MayorParser extends AbstractParser<Mayor> { @Override public Mayor parse(JSONObject json) throws JSONException { Mayor obj = new Mayor(); if (json.has("checkins")) { obj.setCheckins(json.getString("checkins")); } if (json.has("count")) { obj.setCount(json.getString("count")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("type")) { obj.setType(json.getString("type")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Tip; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TipParser extends AbstractParser<Tip> { @Override public Tip parse(JSONObject json) throws JSONException { Tip obj = new Tip(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("stats")) { obj.setStats(new TipParser.StatsParser().parse(json.getJSONObject("stats"))); } if (json.has("status")) { obj.setStatus(json.getString("status")); } if (json.has("text")) { obj.setText(json.getString("text")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } public static class StatsParser extends AbstractParser<Tip.Stats> { @Override public Tip.Stats parse(JSONObject json) throws JSONException { Tip.Stats stats = new Tip.Stats(); if (json.has("donecount")) { stats.setDoneCount(json.getInt("donecount")); } if (json.has("todocount")) { stats.setTodoCount(json.getInt("todocount")); } return stats; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Badge; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class BadgeParser extends AbstractParser<Badge> { @Override public Badge parse(JSONObject json) throws JSONException { Badge obj = new Badge(); if (json.has("description")) { obj.setDescription(json.getString("description")); } if (json.has("icon")) { obj.setIcon(json.getString("icon")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Response; import org.json.JSONException; import org.json.JSONObject; /** * @date April 28, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ResponseParser extends AbstractParser<Response> { @Override public Response parse(JSONObject json) throws JSONException { Response response = new Response(); response.setValue(json.getString("response")); return response; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Settings; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class SettingsParser extends AbstractParser<Settings> { @Override public Settings parse(JSONObject json) throws JSONException { Settings obj = new Settings(); if (json.has("feeds_key")) { obj.setFeedsKey(json.getString("feeds_key")); } if (json.has("get_pings")) { obj.setGetPings(json.getBoolean("get_pings")); } if (json.has("pings")) { obj.setPings(json.getString("pings")); } if (json.has("sendtofacebook")) { obj.setSendtofacebook(json.getBoolean("sendtofacebook")); } if (json.has("sendtotwitter")) { obj.setSendtotwitter(json.getBoolean("sendtotwitter")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Types; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TypesParser extends AbstractParser<Types> { @Override public Types parse(JSONObject json) throws JSONException { Types obj = new Types(); if (json.has("type")) { obj.add(json.getString("type")); } return obj; } public Types parseAsJSONArray(JSONArray array) throws JSONException { Types obj = new Types(); for (int i = 0, m = array.length(); i < m; i++) { obj.add(array.getString(i)); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Data; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class DataParser extends AbstractParser<Data> { @Override public Data parse(JSONObject json) throws JSONException { Data obj = new Data(); if (json.has("cityid")) { obj.setCityid(json.getString("cityid")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("status")) { obj.setStatus("1".equals(json.getString("status"))); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.CheckinResult; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CheckinResultParser extends AbstractParser<CheckinResult> { @Override public CheckinResult parse(JSONObject json) throws JSONException { CheckinResult obj = new CheckinResult(); if (json.has("badges")) { obj.setBadges( new GroupParser( new BadgeParser()).parse(json.getJSONArray("badges"))); } if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("markup")) { obj.setMarkup(json.getString("markup")); } if (json.has("mayor")) { obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor"))); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("scores")) { obj.setScoring( new GroupParser( new ScoreParser()).parse(json.getJSONArray("scores"))); } if (json.has("specials")) { obj.setSpecials( new GroupParser( new SpecialParser()).parse(json.getJSONArray("specials"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Beenhere; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class BeenhereParser extends AbstractParser<Beenhere> { @Override public Beenhere parse(JSONObject json) throws JSONException { Beenhere obj = new Beenhere(); if (json.has("friends")) { obj.setFriends(json.getBoolean("friends")); } if (json.has("me")) { obj.setMe(json.getBoolean("me")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Iterator; import java.util.logging.Level; /** * Reference: * http://www.json.org/javadoc/org/json/JSONObject.html * http://www.json.org/javadoc/org/json/JSONArray.html * * @author Mark Wyszomierski (markww@gmail.com) * @param <T> */ public class GroupParser extends AbstractParser<Group> { private Parser<? extends FoursquareType> mSubParser; public GroupParser(Parser<? extends FoursquareType> subParser) { mSubParser = subParser; } /** * When we encounter a JSONObject in a GroupParser, we expect one attribute * named 'type', and then another JSONArray attribute. */ public Group<FoursquareType> parse(JSONObject json) throws JSONException { Group<FoursquareType> group = new Group<FoursquareType>(); Iterator<String> it = (Iterator<String>)json.keys(); while (it.hasNext()) { String key = it.next(); if (key.equals("type")) { group.setType(json.getString(key)); } else { Object obj = json.get(key); if (obj instanceof JSONArray) { parse(group, (JSONArray)obj); } else { throw new JSONException("Could not parse data."); } } } return group; } /** * Here we are getting a straight JSONArray and do not expect the 'type' attribute. */ @Override public Group parse(JSONArray array) throws JSONException { Group<FoursquareType> group = new Group<FoursquareType>(); parse(group, array); return group; } private void parse(Group group, JSONArray array) throws JSONException { for (int i = 0, m = array.length(); i < m; i++) { Object element = array.get(i); FoursquareType item = null; if (element instanceof JSONArray) { item = mSubParser.parse((JSONArray)element); } else { item = mSubParser.parse((JSONObject)element); } group.add(item); } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Score; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class ScoreParser extends AbstractParser<Score> { @Override public Score parse(JSONObject json) throws JSONException { Score obj = new Score(); if (json.has("icon")) { obj.setIcon(json.getString("icon")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("points")) { obj.setPoints(json.getString("points")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.parsers.json.CategoryParser; import com.joelapenna.foursquare.parsers.json.GroupParser; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.util.IconUtils; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CategoryParser extends AbstractParser<Category> { @Override public Category parse(JSONObject json) throws JSONException { Category obj = new Category(); if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("fullpathname")) { obj.setFullPathName(json.getString("fullpathname")); } if (json.has("nodename")) { obj.setNodeName(json.getString("nodename")); } if (json.has("iconurl")) { // TODO: Remove this once api v2 allows icon request. String iconUrl = json.getString("iconurl"); if (IconUtils.get().getRequestHighDensityIcons()) { iconUrl = iconUrl.replace(".png", "_64.png"); } obj.setIconUrl(iconUrl); } if (json.has("categories")) { obj.setChildCategories( new GroupParser( new CategoryParser()).parse(json.getJSONArray("categories"))); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Stats; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class StatsParser extends AbstractParser<Stats> { @Override public Stats parse(JSONObject json) throws JSONException { Stats obj = new Stats(); if (json.has("beenhere")) { obj.setBeenhere(new BeenhereParser().parse(json.getJSONObject("beenhere"))); } if (json.has("checkins")) { obj.setCheckins(json.getString("checkins")); } if (json.has("herenow")) { obj.setHereNow(json.getString("herenow")); } if (json.has("mayor")) { obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor"))); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Special; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class SpecialParser extends AbstractParser<Special> { @Override public Special parse(JSONObject json) throws JSONException { Special obj = new Special(); if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("type")) { obj.setType(json.getString("type")); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Todo; import org.json.JSONException; import org.json.JSONObject; /** * @date September 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TodoParser extends AbstractParser<Todo> { @Override public Todo parse(JSONObject json) throws JSONException { Todo obj = new Todo(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("tip")) { obj.setTip(new TipParser().parse(json.getJSONObject("tip"))); } if (json.has("todoid")) { obj.setId(json.getString("todoid")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Rank; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class RankParser extends AbstractParser<Rank> { @Override public Rank parse(JSONObject json) throws JSONException { Rank obj = new Rank(); if (json.has("city")) { obj.setCity(json.getString("city")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("position")) { obj.setPosition(json.getString("position")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public abstract class AbstractParser<T extends FoursquareType> implements Parser<T> { /** * All derived parsers must implement parsing a JSONObject instance of themselves. */ public abstract T parse(JSONObject json) throws JSONException; /** * Only the GroupParser needs to implement this. */ public Group parse(JSONArray array) throws JSONException { throw new JSONException("Unexpected JSONArray parse type encountered."); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Tags; import com.joelapenna.foursquare.types.Venue; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class VenueParser extends AbstractParser<Venue> { @Override public Venue parse(JSONObject json) throws JSONException { Venue obj = new Venue(); if (json.has("address")) { obj.setAddress(json.getString("address")); } if (json.has("checkins")) { obj.setCheckins( new GroupParser( new CheckinParser()).parse(json.getJSONArray("checkins"))); } if (json.has("city")) { obj.setCity(json.getString("city")); } if (json.has("cityid")) { obj.setCityid(json.getString("cityid")); } if (json.has("crossstreet")) { obj.setCrossstreet(json.getString("crossstreet")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("geolat")) { obj.setGeolat(json.getString("geolat")); } if (json.has("geolong")) { obj.setGeolong(json.getString("geolong")); } if (json.has("hasTodo")) { obj.setHasTodo(json.getBoolean("hasTodo")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } if (json.has("phone")) { obj.setPhone(json.getString("phone")); } if (json.has("primarycategory")) { obj.setCategory(new CategoryParser().parse(json.getJSONObject("primarycategory"))); } if (json.has("specials")) { obj.setSpecials( new GroupParser( new SpecialParser()).parse(json.getJSONArray("specials"))); } if (json.has("state")) { obj.setState(json.getString("state")); } if (json.has("stats")) { obj.setStats(new StatsParser().parse(json.getJSONObject("stats"))); } if (json.has("tags")) { obj.setTags( new Tags(StringArrayParser.parse(json.getJSONArray("tags")))); } if (json.has("tips")) { obj.setTips( new GroupParser( new TipParser()).parse(json.getJSONArray("tips"))); } if (json.has("todos")) { obj.setTodos( new GroupParser( new TodoParser()).parse(json.getJSONArray("todos"))); } if (json.has("twitter")) { obj.setTwitter(json.getString("twitter")); } if (json.has("zip")) { obj.setZip(json.getString("zip")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.List; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class StringArrayParser { public static List<String> parse(JSONArray json) throws JSONException { List<String> array = new ArrayList<String>(); for (int i = 0, m = json.length(); i < m; i++) { array.add(json.getString(i)); } return array; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Credentials; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CredentialsParser extends AbstractParser<Credentials> { @Override public Credentials parse(JSONObject json) throws JSONException { Credentials obj = new Credentials(); if (json.has("oauth_token")) { obj.setOauthToken(json.getString("oauth_token")); } if (json.has("oauth_token_secret")) { obj.setOauthTokenSecret(json.getString("oauth_token_secret")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.City; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CityParser extends AbstractParser<City> { @Override public City parse(JSONObject json) throws JSONException { City obj = new City(); if (json.has("geolat")) { obj.setGeolat(json.getString("geolat")); } if (json.has("geolong")) { obj.setGeolong(json.getString("geolong")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } if (json.has("shortname")) { obj.setShortname(json.getString("shortname")); } if (json.has("timezone")) { obj.setTimezone(json.getString("timezone")); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Checkin; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CheckinParser extends AbstractParser<Checkin> { @Override public Checkin parse(JSONObject json) throws JSONException { Checkin obj = new Checkin(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("display")) { obj.setDisplay(json.getString("display")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("ismayor")) { obj.setIsmayor(json.getBoolean("ismayor")); } if (json.has("ping")) { obj.setPing(json.getBoolean("ping")); } if (json.has("shout")) { obj.setShout(json.getString("shout")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public interface Parser<T extends FoursquareType> { public abstract T parse(JSONObject json) throws JSONException; public Group parse(JSONArray array) throws JSONException; }
Java
/** * Copyright 2010 Tauno Talimaa */ package com.joelapenna.foursquared.providers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.error.LocationException; import com.joelapenna.foursquared.location.BestLocationListener; import com.joelapenna.foursquared.location.LocationUtils; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.MatrixCursor; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.util.Log; import java.io.IOException; /** * A ContentProvider for Foursquare search results. * * @author Tauno Talimaa (tauntz@gmail.com) */ public class GlobalSearchProvider extends ContentProvider { // TODO: Implement search for friends by name/phone number/twitter ID when // API is implemented in Foursquare.java private static final String TAG = GlobalSearchProvider.class.getSimpleName(); private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final String[] QSB_COLUMNS = { "_id", SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING, SearchManager.SUGGEST_COLUMN_INTENT_DATA, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID }; private static final int URI_TYPE_QUERY = 1; private static final int URI_TYPE_SHORTCUT = 2; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI(Foursquared.PACKAGE_NAME, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_TYPE_QUERY); sUriMatcher.addURI(Foursquared.PACKAGE_NAME, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", URI_TYPE_SHORTCUT); } public static final String VENUE_DIRECTORY = "venue"; public static final String FRIEND_DIRECTORY = "friend"; // TODO: Use the argument from SUGGEST_PARAMETER_LIMIT from the Uri passed // to query() instead of the hardcoded value (this is available starting // from API level 5) private static final int VENUE_QUERY_LIMIT = 30; private Foursquare mFoursquare; @Override public boolean onCreate() { synchronized (this) { if (mFoursquare == null) mFoursquare = Foursquared.createFoursquare(getContext()); } return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String query = uri.getLastPathSegment(); MatrixCursor cursor = new MatrixCursor(QSB_COLUMNS); switch (sUriMatcher.match(uri)) { case URI_TYPE_QUERY: if (DEBUG) { Log.d(TAG, "Global search for venue name: " + query); } Group<Group<Venue>> venueGroups; try { venueGroups = mFoursquare.venues(LocationUtils .createFoursquareLocation(getBestRecentLocation()), query, VENUE_QUERY_LIMIT); } catch (FoursquareError e) { if (DEBUG) Log.e(TAG, "Could not get venue list for query: " + query, e); return cursor; } catch (FoursquareException e) { if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e); return cursor; } catch (LocationException e) { if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e); return cursor; } catch (IOException e) { if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e); return cursor; } for (int groupIndex = 0; groupIndex < venueGroups.size(); groupIndex++) { Group<Venue> venueGroup = venueGroups.get(groupIndex); if (DEBUG) { Log.d(TAG, venueGroup.size() + " results for group: " + venueGroup.getType()); } for (int venueIndex = 0; venueIndex < venueGroup.size(); venueIndex++) { Venue venue = venueGroup.get(venueIndex); if (DEBUG) { Log.d(TAG, "Venue " + venueIndex + ": " + venue.getName() + " (" + venue.getAddress() + ")"); } cursor.addRow(new Object[] { venue.getId(), com.joelapenna.foursquared.R.drawable.venue_shortcut_icon, venue.getName(), venue.getAddress(), venue.getName(), venue.getId(), "true", VENUE_DIRECTORY, venue.getId() }); } } break; case URI_TYPE_SHORTCUT: if (DEBUG) { Log.d(TAG, "Global search for venue ID: " + query); } Venue venue; try { venue = mFoursquare.venue(query, LocationUtils .createFoursquareLocation(getBestRecentLocation())); } catch (FoursquareError e) { if (DEBUG) Log.e(TAG, "Could not get venue details for venue ID: " + query, e); return cursor; } catch (LocationException e) { if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e); return cursor; } catch (FoursquareException e) { if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e); return cursor; } catch (IOException e) { if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e); return cursor; } if (DEBUG) { Log.d(TAG, "Updated venue details: " + venue.getName() + " (" + venue.getAddress() + ")"); } cursor.addRow(new Object[] { venue.getId(), com.joelapenna.foursquared.R.drawable.venue_shortcut_icon, venue.getName(), venue.getAddress(), venue.getName(), venue.getId(), "true", VENUE_DIRECTORY, venue.getId() }); break; case UriMatcher.NO_MATCH: if (DEBUG) { Log.d(TAG, "No matching URI for: " + uri); } break; } return cursor; } @Override public String getType(Uri uri) { return SearchManager.SUGGEST_MIME_TYPE; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException(); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } /** * Convenience method for getting the most recent Location * * @return the most recent Locations * @throws LocationException when no recent Location could be determined */ private Location getBestRecentLocation() throws LocationException { BestLocationListener locationListener = new BestLocationListener(); locationListener.updateLastKnownLocation((LocationManager) getContext().getSystemService( Context.LOCATION_SERVICE)); Location location = locationListener.getLastKnownLocation(); if (location != null) { return location; } throw new LocationException(); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.providers; import android.content.SearchRecentSuggestionsProvider; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueQuerySuggestionsProvider extends SearchRecentSuggestionsProvider { public static final String AUTHORITY = "com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider"; public static final int MODE = DATABASE_MODE_QUERIES; public VenueQuerySuggestionsProvider() { super(); setupSuggestions(AUTHORITY, MODE); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ class FoursquaredException extends Exception { private static final long serialVersionUID = 1L; public FoursquaredException(String message) { super(message); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LocationException extends FoursquaredException { public LocationException() { super("Unable to determine your location."); } public LocationException(String message) { super(message); } private static final long serialVersionUID = 1L; }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.widget.CategoryPickerAdapter; import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.ViewFlipper; import android.widget.AdapterView.OnItemClickListener; import java.io.IOException; /** * Presents the user with a list of all available categories from foursquare * that they can use to label a new venue. * * @date March 7, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class CategoryPickerDialog extends Dialog { private static final String TAG = "FriendRequestsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private Foursquared mApplication; private Group<Category> mCategories; private ViewFlipper mViewFlipper; private Category mChosenCategory; private int mFirstDialogHeight; public CategoryPickerDialog(Context context, Group<Category> categories, Foursquared application) { super(context); mApplication = application; mCategories = categories; mChosenCategory = null; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.category_picker_dialog); setTitle(getContext().getResources().getString(R.string.category_picket_dialog_title)); mViewFlipper = (ViewFlipper) findViewById(R.id.categoryPickerViewFlipper); mFirstDialogHeight = -1; // By default we always have a top-level page. Category root = new Category(); root.setNodeName("root"); root.setChildCategories(mCategories); mViewFlipper.addView(makePage(root)); } private View makePage(Category category) { LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.category_picker_page, null); CategoryPickerPage page = new CategoryPickerPage(); page.ensureUI(view, mPageListItemSelected, category, mApplication .getRemoteResourceManager()); view.setTag(page); if (mViewFlipper.getChildCount() == 1 && mFirstDialogHeight == -1) { mFirstDialogHeight = mViewFlipper.getChildAt(0).getHeight(); } if (mViewFlipper.getChildCount() > 0) { view.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, mFirstDialogHeight)); } return view; } @Override protected void onStop() { super.onStop(); cleanupPageAdapters(); } private void cleanupPageAdapters() { for (int i = 0; i < mViewFlipper.getChildCount(); i++) { CategoryPickerPage page = (CategoryPickerPage) mViewFlipper.getChildAt(i).getTag(); page.cleanup(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mViewFlipper.getChildCount() > 1) { mViewFlipper.removeViewAt(mViewFlipper.getChildCount() - 1); return true; } break; } return super.onKeyDown(keyCode, event); } /** * After the user has dismissed the dialog, the parent activity can use this * to see which category they picked, if any. Will return null if no * category was picked. */ public Category getChosenCategory() { return mChosenCategory; } private static class CategoryPickerPage { private CategoryPickerAdapter mListAdapter; private Category mCategory; private PageListItemSelected mClickListener; public void ensureUI(View view, PageListItemSelected clickListener, Category category, RemoteResourceManager rrm) { mCategory = category; mClickListener = clickListener; mListAdapter = new CategoryPickerAdapter(view.getContext(), rrm, category); ListView listview = (ListView) view.findViewById(R.id.categoryPickerListView); listview.setAdapter(mListAdapter); listview.setOnItemClickListener(mOnItemClickListener); LinearLayout llRootCategory = (LinearLayout) view .findViewById(R.id.categoryPickerRootCategoryButton); if (category.getNodeName().equals("root") == false) { ImageView iv = (ImageView) view.findViewById(R.id.categoryPickerIcon); try { Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(Uri .parse(category.getIconUrl()))); iv.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.e(TAG, "Error loading category icon from disk.", e); } TextView tv = (TextView) view.findViewById(R.id.categoryPickerName); tv.setText(category.getNodeName()); llRootCategory.setClickable(true); llRootCategory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mClickListener.onCategorySelected(mCategory); } }); } else { llRootCategory.setVisibility(View.GONE); } } public void cleanup() { mListAdapter.removeObserver(); } private OnItemClickListener mOnItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { mClickListener.onPageListItemSelcected((Category) mListAdapter.getItem(position)); } }; } private PageListItemSelected mPageListItemSelected = new PageListItemSelected() { @Override public void onPageListItemSelcected(Category category) { // If the item has children, create a new page for it. if (category.getChildCategories() != null && category.getChildCategories().size() > 0) { mViewFlipper.addView(makePage(category)); mViewFlipper.showNext(); } else { // This is a leaf node, finally the user's selection. Record the // category // then cancel ourselves, parent activity should pick us up // after that. mChosenCategory = category; cancel(); } } @Override public void onCategorySelected(Category category) { // The user has chosen the category parent listed at the top of the // current page. mChosenCategory = category; cancel(); } }; private interface PageListItemSelected { public void onPageListItemSelcected(Category category); public void onCategorySelected(Category category); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.widget.CheckinListAdapter; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -refactored for display of straight checkins list (September 16, 2010). * */ public class VenueCheckinsActivity extends LoadableListActivity { public static final String TAG = "VenueCheckinsActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueCheckinsActivity.INTENT_EXTRA_VENUE"; private SeparatedListAdapter mListAdapter; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder = new StateHolder( (Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE), ((Foursquared) getApplication()).getUserId()); } else { Log.e(TAG, "VenueCheckinsActivity requires a venue parcel its intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } private void ensureUi() { mListAdapter = new SeparatedListAdapter(this); if (mStateHolder.getCheckinsYou().size() > 0) { String title = getResources().getString(R.string.venue_activity_people_count_you); CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getCheckinsYou()); mListAdapter.addSection(title, adapter); } if (mStateHolder.getCheckinsFriends().size() > 0) { String title = getResources().getString( mStateHolder.getCheckinsOthers().size() == 1 ? R.string.venue_activity_checkins_count_friends_single : R.string.venue_activity_checkins_count_friends_plural, mStateHolder.getCheckinsFriends().size()); CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getCheckinsFriends()); mListAdapter.addSection(title, adapter); } if (mStateHolder.getCheckinsOthers().size() > 0) { boolean others = mStateHolder.getCheckinsYou().size() + mStateHolder.getCheckinsFriends().size() > 0; String title = getResources().getString( mStateHolder.getCheckinsOthers().size() == 1 ? (others ? R.string.venue_activity_checkins_count_others_single : R.string.venue_activity_checkins_count_others_alone_single) : (others ? R.string.venue_activity_checkins_count_others_plural : R.string.venue_activity_checkins_count_others_alone_plural), mStateHolder.getCheckinsOthers().size()); CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getCheckinsOthers()); mListAdapter.addSection(title, adapter); } ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(true); listView.setDividerHeight(0); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Checkin checkin = (Checkin) parent.getAdapter().getItem(position); Intent intent = new Intent(VenueCheckinsActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, checkin.getUser()); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); startActivity(intent); } }); setTitle(getString(R.string.venue_checkins_activity_title, mStateHolder.getVenueName())); } private static class StateHolder { private String mVenueName; private Group<Checkin> mYou; private Group<Checkin> mFriends; private Group<Checkin> mOthers; public StateHolder(Venue venue, String loggedInUserId) { mVenueName = venue.getName(); mYou = new Group<Checkin>(); mFriends = new Group<Checkin>(); mOthers = new Group<Checkin>(); mYou.clear(); mFriends.clear(); mOthers.clear(); for (Checkin it : venue.getCheckins()) { User user = it.getUser(); if (UserUtils.isFriend(user)) { mFriends.add(it); } else if (loggedInUserId.equals(user.getId())) { mYou.add(it); } else { mOthers.add(it); } } } public String getVenueName() { return mVenueName; } public Group<Checkin> getCheckinsYou() { return mYou; } public Group<Checkin> getCheckinsFriends() { return mFriends; } public Group<Checkin> getCheckinsOthers() { return mOthers; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.List; /** * Allows the user to add a new venue. This activity can also be used to submit * edits to an existing venue. Pass a venue parcelable using the EXTRA_VENUE_TO_EDIT * key to put the activity into edit mode. * * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Added support for using this activity to edit existing venues (June 8, 2010). */ public class AddVenueActivity extends Activity { private static final String TAG = "AddVenueActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_VENUE_TO_EDIT = "com.joelapenna.foursquared.VenueParcel"; private static final double MINIMUM_ACCURACY_FOR_ADDRESS = 100.0; private static final int DIALOG_PICK_CATEGORY = 1; private static final int DIALOG_ERROR = 2; private StateHolder mStateHolder; private EditText mNameEditText; private EditText mAddressEditText; private EditText mCrossstreetEditText; private EditText mCityEditText; private EditText mStateEditText; private EditText mZipEditText; private EditText mPhoneEditText; private Button mAddOrEditVenueButton; private LinearLayout mCategoryLayout; private ImageView mCategoryImageView; private TextView mCategoryTextView; private ProgressBar mCategoryProgressBar; private ProgressDialog mDlgProgress; private TextWatcher mNameFieldWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mAddOrEditVenueButton.setEnabled(canEnableSaveButton()); } }; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.add_venue_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mAddOrEditVenueButton = (Button) findViewById(R.id.addVenueButton); mNameEditText = (EditText) findViewById(R.id.nameEditText); mAddressEditText = (EditText) findViewById(R.id.addressEditText); mCrossstreetEditText = (EditText) findViewById(R.id.crossstreetEditText); mCityEditText = (EditText) findViewById(R.id.cityEditText); mStateEditText = (EditText) findViewById(R.id.stateEditText); mZipEditText = (EditText) findViewById(R.id.zipEditText); mPhoneEditText = (EditText) findViewById(R.id.phoneEditText); mCategoryLayout = (LinearLayout) findViewById(R.id.addVenueCategoryLayout); mCategoryImageView = (ImageView) findViewById(R.id.addVenueCategoryIcon); mCategoryTextView = (TextView) findViewById(R.id.addVenueCategoryTextView); mCategoryProgressBar = (ProgressBar) findViewById(R.id.addVenueCategoryProgressBar); mCategoryLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { showDialog(DIALOG_PICK_CATEGORY); } }); mCategoryLayout.setEnabled(false); mAddOrEditVenueButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String name = mNameEditText.getText().toString(); String address = mAddressEditText.getText().toString(); String crossstreet = mCrossstreetEditText.getText().toString(); String city = mCityEditText.getText().toString(); String state = mStateEditText.getText().toString(); String zip = mZipEditText.getText().toString(); String phone = mPhoneEditText.getText().toString(); if (mStateHolder.getVenueBeingEdited() != null) { if (TextUtils.isEmpty(name)) { showDialogError(getResources().getString( R.string.add_venue_activity_error_no_venue_name)); return; } else if (TextUtils.isEmpty(address)) { showDialogError(getResources().getString( R.string.add_venue_activity_error_no_venue_address)); return; } else if (TextUtils.isEmpty(city)) { showDialogError(getResources().getString( R.string.add_venue_activity_error_no_venue_city)); return; } else if (TextUtils.isEmpty(state)) { showDialogError(getResources().getString( R.string.add_venue_activity_error_no_venue_state)); return; } } mStateHolder.startTaskAddOrEditVenue( AddVenueActivity.this, new String[] { name, address, crossstreet, city, state, zip, phone, mStateHolder.getChosenCategory() != null ? mStateHolder.getChosenCategory().getId() : "" }, // If editing a venue, pass in its id. mStateHolder.getVenueBeingEdited() != null ? mStateHolder.getVenueBeingEdited().getId() : null); } }); mNameEditText.addTextChangedListener(mNameFieldWatcher); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); setFields(mStateHolder.getAddressLookup()); setChosenCategory(mStateHolder.getChosenCategory()); if (mStateHolder.getCategories() != null && mStateHolder.getCategories().size() > 0) { mCategoryLayout.setEnabled(true); mCategoryProgressBar.setVisibility(View.GONE); } } else { mStateHolder = new StateHolder(); mStateHolder.startTaskGetCategories(this); // If passed the venue parcelable, then we are in 'edit' mode. if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_VENUE_TO_EDIT)) { Venue venue = getIntent().getExtras().getParcelable(EXTRA_VENUE_TO_EDIT); if (venue != null) { mStateHolder.setVenueBeingEdited(venue); setFields(venue); setTitle(getResources().getString(R.string.add_venue_activity_label_edit_venue)); mAddOrEditVenueButton.setText(getResources().getString( R.string.add_venue_activity_btn_submit_edits)); } else { Log.e(TAG, "Null venue parcelable supplied at startup, will finish immediately."); finish(); } } else { mStateHolder.startTaskAddressLookup(this); } } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(true); if (mStateHolder.getIsRunningTaskAddOrEditVenue()) { startProgressBar(); } } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(); stopProgressBar(); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void showDialogError(String message) { mStateHolder.setError(message); showDialog(DIALOG_ERROR); } /** * Set fields from an address lookup, only used when adding a venue. This is done * to prepopulate some fields for the user. */ private void setFields(AddressLookup addressLookup) { if (mStateHolder.getVenueBeingEdited() == null && addressLookup != null && addressLookup.getAddress() != null) { // Don't fill in the street unless we're reasonably confident we // know where the user is. String address = addressLookup.getAddress().getAddressLine(0); double accuracy = addressLookup.getLocation().getAccuracy(); if (address != null && (accuracy > 0.0 && accuracy < MINIMUM_ACCURACY_FOR_ADDRESS)) { if (DEBUG) Log.d(TAG, "Accuracy good enough, setting address field."); mAddressEditText.setText(address); } String city = addressLookup.getAddress().getLocality(); if (city != null) { mCityEditText.setText(city); } String state = addressLookup.getAddress().getAdminArea(); if (state != null) { mStateEditText.setText(state); } String zip = addressLookup.getAddress().getPostalCode(); if (zip != null) { mZipEditText.setText(zip); } String phone = addressLookup.getAddress().getPhone(); if (phone != null) { mPhoneEditText.setText(phone); } } } /** * Set fields from an existing venue, this is only used when editing a venue. */ private void setFields(Venue venue) { mNameEditText.setText(venue.getName()); mCrossstreetEditText.setText(venue.getCrossstreet()); mAddressEditText.setText(venue.getAddress()); mCityEditText.setText(venue.getCity()); mStateEditText.setText(venue.getState()); mZipEditText.setText(venue.getZip()); mPhoneEditText.setText(venue.getPhone()); } private void startProgressBar() { startProgressBar( getResources().getString( mStateHolder.getVenueBeingEdited() == null ? R.string.add_venue_progress_bar_message_add_venue : R.string.add_venue_progress_bar_message_edit_venue)); } private void startProgressBar(String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, null, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } private void onGetCategoriesTaskComplete(Group<Category> categories, Exception ex) { mStateHolder.setIsRunningTaskGetCategories(false); try { // Populate the categories list now. if (categories != null) { mStateHolder.setCategories(categories); mCategoryLayout.setEnabled(true); mCategoryTextView.setText(getResources().getString(R.string.add_venue_activity_pick_category_label)); mCategoryProgressBar.setVisibility(View.GONE); // If we are editing a venue, set its category here. if (mStateHolder.getVenueBeingEdited() != null) { Venue venue = mStateHolder.getVenueBeingEdited(); if (venue.getCategory() != null) { setChosenCategory(venue.getCategory()); } } } else { // If error, feed list adapter empty user group. mStateHolder.setCategories(new Group<Category>()); NotificationsUtil.ToastReasonForFailure(this, ex); } } finally { } stopIndeterminateProgressBar(); } private void ooGetAddressLookupTaskComplete(AddressLookup addressLookup, Exception ex) { mStateHolder.setIsRunningTaskAddressLookup(false); stopIndeterminateProgressBar(); if (addressLookup != null) { mStateHolder.setAddressLookup(addressLookup); setFields(addressLookup); } else { // Nothing to do on failure, don't need to report. } } private void onAddOrEditVenueTaskComplete(Venue venue, String venueIdIfEditing, Exception ex) { mStateHolder.setIsRunningTaskAddOrEditVenue(false); stopProgressBar(); if (venueIdIfEditing == null) { if (venue != null) { // If they added the venue ok, then send them to an activity displaying it // so they can play around with it. Intent intent = new Intent(AddVenueActivity.this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); startActivity(intent); finish(); } else { // Error, let them hang out here. NotificationsUtil.ToastReasonForFailure(this, ex); } } else { if (venue != null) { // Editing the venue worked ok, just return to caller. Toast.makeText(this, getResources().getString( R.string.add_venue_activity_edit_venue_success), Toast.LENGTH_SHORT).show(); finish(); } else { // Error, let them hang out here. NotificationsUtil.ToastReasonForFailure(this, ex); } } } private void stopIndeterminateProgressBar() { if (mStateHolder.getIsRunningTaskAddressLookup() == false && mStateHolder.getIsRunningTaskGetCategories() == false) { setProgressBarIndeterminateVisibility(false); } } private static class AddOrEditVenueTask extends AsyncTask<Void, Void, Venue> { private AddVenueActivity mActivity; private String[] mParams; private String mVenueIdIfEditing; private Exception mReason; private Foursquared mFoursquared; private String mErrorMsgForEditVenue; public AddOrEditVenueTask(AddVenueActivity activity, String[] params, String venueIdIfEditing) { mActivity = activity; mParams = params; mVenueIdIfEditing = venueIdIfEditing; mFoursquared = (Foursquared) activity.getApplication(); mErrorMsgForEditVenue = activity.getResources().getString( R.string.add_venue_activity_edit_venue_fail); } public void setActivity(AddVenueActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(); } @Override protected Venue doInBackground(Void... params) { try { Foursquare foursquare = mFoursquared.getFoursquare(); Location location = mFoursquared.getLastKnownLocationOrThrow(); if (mVenueIdIfEditing == null) { return foursquare.addVenue( mParams[0], // name mParams[1], // address mParams[2], // cross street mParams[3], // city mParams[4], // state, mParams[5], // zip mParams[6], // phone mParams[7], // category id LocationUtils.createFoursquareLocation(location)); } else { Response response = foursquare.proposeedit( mVenueIdIfEditing, mParams[0], // name mParams[1], // address mParams[2], // cross street mParams[3], // city mParams[4], // state, mParams[5], // zip mParams[6], // phone mParams[7], // category id LocationUtils.createFoursquareLocation(location)); if (response != null && response.getValue().equals("ok")) { // TODO: Come up with a better method than returning an empty venue on success. return new Venue(); } else { throw new Exception(mErrorMsgForEditVenue); } } } catch (Exception e) { Log.e(TAG, "Exception during add or edit venue.", e); mReason = e; } return null; } @Override protected void onPostExecute(Venue venue) { if (DEBUG) Log.d(TAG, "onPostExecute()"); if (mActivity != null) { mActivity.onAddOrEditVenueTaskComplete(venue, mVenueIdIfEditing, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onAddOrEditVenueTaskComplete(null, mVenueIdIfEditing, mReason); } } } private static class AddressLookupTask extends AsyncTask<Void, Void, AddressLookup> { private AddVenueActivity mActivity; private Exception mReason; public AddressLookupTask(AddVenueActivity activity) { mActivity = activity; } public void setActivity(AddVenueActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.setProgressBarIndeterminateVisibility(true); } @Override protected AddressLookup doInBackground(Void... params) { try { Location location = ((Foursquared)mActivity.getApplication()).getLastKnownLocationOrThrow(); Geocoder geocoder = new Geocoder(mActivity); List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); if (addresses != null && addresses.size() > 0) { Log.i(TAG, "Address found: " + addresses.toString()); return new AddressLookup(location, addresses.get(0)); } else { Log.i(TAG, "No address could be found for current location."); throw new FoursquareException("No address could be found for the current geolocation."); } } catch (Exception ex) { Log.e(TAG, "Error during address lookup.", ex); mReason = ex; } return null; } @Override protected void onPostExecute(AddressLookup address) { if (mActivity != null) { mActivity.ooGetAddressLookupTaskComplete(address, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.ooGetAddressLookupTaskComplete(null, mReason); } } } private static class GetCategoriesTask extends AsyncTask<Void, Void, Group<Category>> { private AddVenueActivity mActivity; private Exception mReason; public GetCategoriesTask(AddVenueActivity activity) { mActivity = activity; } public void setActivity(AddVenueActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.setProgressBarIndeterminateVisibility(true); } @Override protected Group<Category> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.categories(); } catch (Exception e) { if (DEBUG) Log.d(TAG, "GetCategoriesTask: Exception doing send friend request.", e); mReason = e; } return null; } @Override protected void onPostExecute(Group<Category> categories) { if (DEBUG) Log.d(TAG, "GetCategoriesTask: onPostExecute()"); if (mActivity != null) { mActivity.onGetCategoriesTaskComplete(categories, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onGetCategoriesTaskComplete(null, new Exception("Get categories task request cancelled.")); } } } private static class StateHolder { private AddressLookupTask mTaskGetAddress; private AddressLookup mAddressLookup; private boolean mIsRunningTaskAddressLookup; private GetCategoriesTask mTaskGetCategories; private Group<Category> mCategories; private boolean mIsRunningTaskGetCategories; private AddOrEditVenueTask mTaskAddOrEditVenue; private boolean mIsRunningTaskAddOrEditVenue; private Category mChosenCategory; private Venue mVenueBeingEdited; private String mError; public StateHolder() { mCategories = new Group<Category>(); mIsRunningTaskAddressLookup = false; mIsRunningTaskGetCategories = false; mIsRunningTaskAddOrEditVenue = false; mVenueBeingEdited = null; } public void setCategories(Group<Category> categories) { mCategories = categories; } public void setAddressLookup(AddressLookup addressLookup) { mAddressLookup = addressLookup; } public Group<Category> getCategories() { return mCategories; } public AddressLookup getAddressLookup() { return mAddressLookup; } public Venue getVenueBeingEdited() { return mVenueBeingEdited; } public void setVenueBeingEdited(Venue venue) { mVenueBeingEdited = venue; } public void startTaskGetCategories(AddVenueActivity activity) { mIsRunningTaskGetCategories = true; mTaskGetCategories = new GetCategoriesTask(activity); mTaskGetCategories.execute(); } public void startTaskAddressLookup(AddVenueActivity activity) { mIsRunningTaskAddressLookup = true; mTaskGetAddress = new AddressLookupTask(activity); mTaskGetAddress.execute(); } public void startTaskAddOrEditVenue(AddVenueActivity activity, String[] params, String venueIdIfEditing) { mIsRunningTaskAddOrEditVenue = true; mTaskAddOrEditVenue = new AddOrEditVenueTask(activity, params, venueIdIfEditing); mTaskAddOrEditVenue.execute(); } public void setActivity(AddVenueActivity activity) { if (mTaskGetCategories != null) { mTaskGetCategories.setActivity(activity); } if (mTaskGetAddress != null) { mTaskGetAddress.setActivity(activity); } if (mTaskAddOrEditVenue != null) { mTaskAddOrEditVenue.setActivity(activity); } } public void setIsRunningTaskAddressLookup(boolean isRunning) { mIsRunningTaskAddressLookup = isRunning; } public void setIsRunningTaskGetCategories(boolean isRunning) { mIsRunningTaskGetCategories = isRunning; } public void setIsRunningTaskAddOrEditVenue(boolean isRunning) { mIsRunningTaskAddOrEditVenue = isRunning; } public boolean getIsRunningTaskAddressLookup() { return mIsRunningTaskAddressLookup; } public boolean getIsRunningTaskGetCategories() { return mIsRunningTaskGetCategories; } public boolean getIsRunningTaskAddOrEditVenue() { return mIsRunningTaskAddOrEditVenue; } public Category getChosenCategory() { return mChosenCategory; } public void setChosenCategory(Category category) { mChosenCategory = category; } public String getError() { return mError; } public void setError(String error) { mError = error; } } private static class AddressLookup { private Location mLocation; private Address mAddress; public AddressLookup(Location location, Address address) { mLocation = location; mAddress = address; } public Location getLocation() { return mLocation; } public Address getAddress() { return mAddress; } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PICK_CATEGORY: // When the user cancels the dialog (by hitting the 'back' key), we // finish this activity. We don't listen to onDismiss() for this // action, because a device rotation will fire onDismiss(), and our // dialog would not be re-displayed after the rotation is complete. CategoryPickerDialog dlg = new CategoryPickerDialog( this, mStateHolder.getCategories(), ((Foursquared)getApplication())); dlg.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CategoryPickerDialog dlg = (CategoryPickerDialog)dialog; setChosenCategory(dlg.getChosenCategory()); removeDialog(DIALOG_PICK_CATEGORY); } }); return dlg; case DIALOG_ERROR: AlertDialog dlgInfo = new AlertDialog.Builder(this) .setIcon(0) .setTitle(getResources().getString(R.string.add_venue_progress_bar_title_edit_venue)) .setMessage(mStateHolder.getError()).create(); dlgInfo.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(DIALOG_ERROR); } }); return dlgInfo; } return null; } private void setChosenCategory(Category category) { if (category == null) { mCategoryTextView.setText(getResources().getString( R.string.add_venue_activity_pick_category_label)); return; } try { Bitmap bitmap = BitmapFactory.decodeStream( ((Foursquared)getApplication()).getRemoteResourceManager().getInputStream( Uri.parse(category.getIconUrl()))); mCategoryImageView.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.e(TAG, "Error loading category icon.", e); } mCategoryTextView.setText(category.getNodeName()); // Record the chosen category. mStateHolder.setChosenCategory(category); if (canEnableSaveButton()) { mAddOrEditVenueButton.setEnabled(canEnableSaveButton()); } } private boolean canEnableSaveButton() { return mNameEditText.getText().length() > 0; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Badge; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Mayor; import com.joelapenna.foursquare.types.Score; import com.joelapenna.foursquare.types.Special; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.util.Base64Coder; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.widget.BadgeWithIconListAdapter; import com.joelapenna.foursquared.widget.ScoreListAdapter; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import com.joelapenna.foursquared.widget.SpecialListAdapter; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * Renders the result of a checkin using a CheckinResult object. This is called * from CheckinExecuteActivity. It would be nicer to put this in another activity, * but right now the CheckinResult is quite large and would require a good amount * of work to add serializers for all its inner classes. This wouldn't be a huge * problem, but maintaining it as the classes evolve could more trouble than it's * worth. * * The only way the user can dismiss this dialog is by hitting the 'back' key. * CheckingExecuteActivity depends on this so it knows when to finish() itself. * * @date March 3, 2010. * @author Mark Wyszomierski (markww@gmail.com), foursquare. * */ public class CheckinResultDialog extends Dialog { private static final String TAG = "CheckinResultDialog"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private CheckinResult mCheckinResult; private Handler mHandler; private RemoteResourceManagerObserver mObserverMayorPhoto; private Foursquared mApplication; private String mExtrasDecoded; private WebViewDialog mDlgWebViewExtras; public CheckinResultDialog(Context context, CheckinResult result, Foursquared application) { super(context, R.style.ThemeCustomDlgBase_ThemeCustomDlg); mCheckinResult = result; mApplication = application; mHandler = new Handler(); mObserverMayorPhoto = null; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.checkin_result_dialog); setTitle(getContext().getResources().getString(R.string.checkin_title_result)); TextView tvMessage = (TextView)findViewById(R.id.textViewCheckinMessage); if (mCheckinResult != null) { tvMessage.setText(mCheckinResult.getMessage()); SeparatedListAdapter adapter = new SeparatedListAdapter(getContext()); // Add any badges the user unlocked as a result of this checkin. addBadges(mCheckinResult.getBadges(), adapter, mApplication.getRemoteResourceManager()); // Add whatever points they got as a result of this checkin. addScores(mCheckinResult.getScoring(), adapter, mApplication.getRemoteResourceManager()); // Add any specials that are nearby. addSpecials(mCheckinResult.getSpecials(), adapter); // Add a button below the mayor section which will launch a new webview if // we have additional content from the server. This is base64 encoded and // is supposed to be just dumped into a webview. addExtras(mCheckinResult.getMarkup()); // List items construction complete. ListView listview = (ListView)findViewById(R.id.listViewCheckinBadgesAndScores); listview.setAdapter(adapter); listview.setOnItemClickListener(mOnItemClickListener); // Show mayor info if any. addMayor(mCheckinResult.getMayor(), mApplication.getRemoteResourceManager()); } else { // This shouldn't be possible but we've gotten a few crash reports showing that // mCheckinResult is null on entry of this method. Log.e(TAG, "Checkin result object was null on dialog creation."); tvMessage.setText("Checked-in!"); } } @Override protected void onStop() { super.onStop(); if (mDlgWebViewExtras != null && mDlgWebViewExtras.isShowing()) { mDlgWebViewExtras.dismiss(); } if (mObserverMayorPhoto != null) { mApplication.getRemoteResourceManager().deleteObserver(mObserverMayorPhoto); } } private void addBadges(Group<Badge> badges, SeparatedListAdapter adapterMain, RemoteResourceManager rrm) { if (badges == null || badges.size() < 1) { return; } BadgeWithIconListAdapter adapter = new BadgeWithIconListAdapter( getContext(), rrm, R.layout.badge_list_item); adapter.setGroup(badges); adapterMain.addSection(getContext().getResources().getString(R.string.checkin_result_dialog_badges), adapter); } private void addScores(Group<Score> scores, SeparatedListAdapter adapterMain, RemoteResourceManager rrm) { if (scores == null || scores.size() < 1) { return; } // We make our own local score group because we'll inject the total as // a new dummy score element. Group<Score> scoresWithTotal = new Group<Score>(); // Total up the scoring. int total = 0; for (Score score : scores) { total += Integer.parseInt(score.getPoints()); scoresWithTotal.add(score); } // Add a dummy score element to the group which is just the total. Score scoreTotal = new Score(); scoreTotal.setIcon(""); scoreTotal.setMessage(getContext().getResources().getString( R.string.checkin_result_dialog_score_total)); scoreTotal.setPoints(String.valueOf(total)); scoresWithTotal.add(scoreTotal); // Give it all to the adapter now. ScoreListAdapter adapter = new ScoreListAdapter(getContext(), rrm); adapter.setGroup(scoresWithTotal); adapterMain.addSection(getContext().getResources().getString(R.string.checkin_score), adapter); } private void addMayor(Mayor mayor, RemoteResourceManager rrm) { LinearLayout llMayor = (LinearLayout)findViewById(R.id.llCheckinMayorInfo); if (mayor == null) { llMayor.setVisibility(View.GONE); return; } else { llMayor.setVisibility(View.VISIBLE); } // Set the mayor message. TextView tvMayorMessage = (TextView)findViewById(R.id.textViewCheckinMayorMessage); tvMayorMessage.setText(mayor.getMessage()); // A few cases here for the image to display. ImageView ivMayor = (ImageView)findViewById(R.id.imageViewCheckinMayor); if (mCheckinResult.getMayor().getUser() == null) { // I am still the mayor. // Just show the crown icon. ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown)); } else if (mCheckinResult.getMayor().getType().equals("nochange")) { // Someone else is mayor. // Show that user's photo from the network. If not already on disk, // we need to start a fetch for it. Uri photoUri = populateMayorImageFromNetwork(); if (photoUri != null) { mApplication.getRemoteResourceManager().request(photoUri); mObserverMayorPhoto = new RemoteResourceManagerObserver(); rrm.addObserver(mObserverMayorPhoto); } addClickHandlerForMayorImage(ivMayor, mayor.getUser().getId()); } else if (mCheckinResult.getMayor().getType().equals("new")) { // I just became the new mayor as a result of this checkin. // Just show the crown icon. ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown)); } else if (mCheckinResult.getMayor().getType().equals("stolen")) { // I stole mayorship from someone else as a result of this checkin. // Just show the crown icon. ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown)); } } private void addSpecials(Group<Special> specials, SeparatedListAdapter adapterMain) { if (specials == null || specials.size() < 1) { return; } // For now, get rid of specials not tied to the current venue. If the special is // tied to this venue, then there would be no <venue> block associated with the // special. If there is a <venue> block associated with the special, it means it // belongs to another venue and we won't show it. Group<Special> localSpecials = new Group<Special>(); for (Special it : specials) { if (it.getVenue() == null) { localSpecials.add(it); } } if (localSpecials.size() < 1) { return; } SpecialListAdapter adapter = new SpecialListAdapter(getContext()); adapter.setGroup(localSpecials); adapterMain.addSection( getContext().getResources().getString(R.string.checkin_specials), adapter); } private void addExtras(String extras) { LinearLayout llExtras = (LinearLayout)findViewById(R.id.llCheckinExtras); if (TextUtils.isEmpty(extras)) { llExtras.setVisibility(View.GONE); return; } else { llExtras.setVisibility(View.VISIBLE); } // The server sent us additional content, it is base64 encoded, so decode it now. mExtrasDecoded = Base64Coder.decodeString(extras); // TODO: Replace with generic extras method. // Now when the user clicks this 'button' pop up yet another dialog dedicated // to showing just the webview and the decoded content. This is not ideal but // having problems putting a webview directly inline with the rest of the // checkin content, we can improve this later. llExtras.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDlgWebViewExtras = new WebViewDialog(getContext(), "SXSW Stats", mExtrasDecoded); mDlgWebViewExtras.show(); } }); } private void addClickHandlerForMayorImage(View view, final String userId) { // Show a user detail activity when the user clicks on the mayor's image. view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); v.getContext().startActivity(intent); } }); } /** * If we have to download the user's photo from the net (wasn't already in cache) * will return the uri to launch. */ private Uri populateMayorImageFromNetwork() { User user = mCheckinResult.getMayor().getUser(); ImageView ivMayor = (ImageView)findViewById(R.id.imageViewCheckinMayor); if (user != null) { Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream( mApplication.getRemoteResourceManager().getInputStream(photoUri)); ivMayor.setImageBitmap(bitmap); return null; } catch (IOException e) { // User's image wasn't already in the cache, have to start a request for it. if (Foursquare.MALE.equals(user.getGender())) { ivMayor.setImageResource(R.drawable.blank_boy); } else { ivMayor.setImageResource(R.drawable.blank_girl); } return photoUri; } } return null; } /** * Called if the remote resource manager downloads the mayor's photo. * If the photo is already on disk, this observer will never be used. */ private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { populateMayorImageFromNetwork(); } }); } } private OnItemClickListener mOnItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { Object obj = adapter.getItemAtPosition(position); if (obj != null) { if (obj instanceof Special) { // When the user clicks on a special, if the venue is different than // the venue the user checked in at (already being viewed) then show // a new venue activity for that special. Venue venue = ((Special)obj).getVenue(); if (venue != null) { Intent intent = new Intent(getContext(), VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); getContext().startActivity(intent); } } } } }; }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Display; import android.view.WindowManager; import android.webkit.WebView; import android.widget.LinearLayout; /** * Shows a listing of what's changed between * * @date March 17, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ChangelogActivity extends Activity { private static final String CHANGELOG_HTML_FILE = "file:///android_asset/changelog-en.html"; private WebView mWebViewChanges; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.changelog_activity); ensureUi(); } private void ensureUi() { WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); LinearLayout llMain = (LinearLayout)findViewById(R.id.layoutMain); // We'll force the dialog to be a certain percentage height of the screen. mWebViewChanges = new WebView(this); mWebViewChanges.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, (int)Math.floor(display.getHeight() * 0.5))); mWebViewChanges.loadUrl(CHANGELOG_HTML_FILE); llMain.addView(mWebViewChanges); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Settings; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.app.PingsService; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.Spinner; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; /** * @date June 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsSettingsActivity extends Activity { private static final String TAG = "PingsSettingsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private SharedPreferences mPrefs; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; private CheckBox mCheckBoxPings; private Spinner mSpinnerInterval; private CheckBox mCheckBoxVibrate; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pings_settings_activity); setTitle(getResources().getString(R.string.pings_settings_title)); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); ensureUi(); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); if (mStateHolder.getIsRunningTaskNotifications()) { startProgressBar( getResources().getString( R.string.pings_settings_progressbar_title_pings), getResources().getString( R.string.pings_settings_progressbar_message_pings)); } } else { // Get a fresh copy of the user object in an attempt to keep the notification // setting in sync. mStateHolder = new StateHolder(this); mStateHolder.startTaskUpdateUser(this); } } private void ensureUi() { mCheckBoxPings = (CheckBox)findViewById(R.id.pings_on); mCheckBoxPings.setChecked(mPrefs.getBoolean(Preferences.PREFERENCE_PINGS, false)); mCheckBoxPings.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mStateHolder.startTaskNotifications( PingsSettingsActivity.this, mCheckBoxPings.isChecked()); } }); mSpinnerInterval = (Spinner)findViewById(R.id.pings_interval); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.pings_refresh_interval_in_minutes, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpinnerInterval.setAdapter(adapter); mSpinnerInterval.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) { String[] values = PingsSettingsActivity.this.getResources().getStringArray( R.array.pings_refresh_interval_in_minutes_values); mPrefs.edit().putString( Preferences.PREFERENCE_PINGS_INTERVAL, values[position]).commit(); restartNotifications(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); setIntervalSpinnerFromSettings(); mCheckBoxVibrate = (CheckBox)findViewById(R.id.pings_vibrate); mCheckBoxVibrate.setChecked(mPrefs.getBoolean(Preferences.PREFERENCE_PINGS_VIBRATE, false)); mCheckBoxVibrate.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mPrefs.edit().putBoolean( Preferences.PREFERENCE_PINGS_VIBRATE, mCheckBoxVibrate.isChecked()).commit(); } }); } private void setIntervalSpinnerFromSettings() { String selected = mPrefs.getString(Preferences.PREFERENCE_PINGS_INTERVAL, "30"); String[] values = getResources().getStringArray( R.array.pings_refresh_interval_in_minutes_values); for (int i = 0; i < values.length; i++) { if (values[i].equals(selected)) { mSpinnerInterval.setSelection(i); return; } } mSpinnerInterval.setSelection(1); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunningTaskNotifications()) { startProgressBar( getResources().getString( R.string.pings_settings_progressbar_title_pings), getResources().getString( R.string.pings_settings_progressbar_message_pings)); } else if (mStateHolder.getIsRunningTaskUpdateUser()) { startProgressBar( getResources().getString( R.string.pings_settings_progressbar_title_updateuser), getResources().getString( R.string.pings_settings_progressbar_message_updateuser)); } } @Override public void onPause() { super.onPause(); if (isFinishing()) { stopProgressBar(); mStateHolder.cancelTasks(); } } private void startProgressBar(String title, String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, title, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } private void onPostTaskPings(Settings settings, boolean changeToState, Exception reason) { if (settings == null) { NotificationsUtil.ToastReasonForFailure(this, reason); // Reset the checkbox. mCheckBoxPings.setChecked(!changeToState); } else { Toast.makeText( this, getResources().getString(R.string.pings_settings_result, settings.getPings()), Toast.LENGTH_SHORT).show(); if (settings.getPings().equals("on")) { PingsService.setupPings(this); mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, true).commit(); } else { PingsService.cancelPings(this); mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); } restartNotifications(); } mStateHolder.setIsRunningTaskNotifications(false); stopProgressBar(); } private void onPostTaskUserUpdate(User user, Exception reason) { if (user == null) { NotificationsUtil.ToastReasonForFailure(this, reason); finish(); } else { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( PingsSettingsActivity.this); Editor editor = prefs.edit(); Preferences.storeUser(editor, user); if (!editor.commit()) { Log.e(TAG, "Error storing user object."); } if (user.getSettings().getPings().equals("on")) { mCheckBoxPings.setChecked(true); mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, true).commit(); } else { mCheckBoxPings.setChecked(false); mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); } restartNotifications(); } mStateHolder.setIsRunningTaskUpdateUser(false); stopProgressBar(); } private static class UpdatePingsTask extends AsyncTask<Void, Void, Settings> { private static final String TAG = "UpdatePingsTask"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private Exception mReason; private boolean mPingsOn; private PingsSettingsActivity mActivity; public UpdatePingsTask(PingsSettingsActivity activity, boolean on) { mActivity = activity; mPingsOn = on; } @Override protected void onPreExecute() { mActivity.startProgressBar( mActivity.getResources().getString( R.string.pings_settings_progressbar_title_pings), mActivity.getResources().getString( R.string.pings_settings_progressbar_message_pings)); } @Override protected Settings doInBackground(Void... params) { if (DEBUG) Log.d(TAG, "doInBackground()"); try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.setpings(mPingsOn); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Settings settings) { if (mActivity != null) { mActivity.onPostTaskPings(settings, mPingsOn, mReason); } } public void setActivity(PingsSettingsActivity activity) { mActivity = activity; } } private static class UpdateUserTask extends AsyncTask<Void, Void, User> { private PingsSettingsActivity mActivity; private Exception mReason; public UpdateUserTask(PingsSettingsActivity activity) { mActivity = activity; } @Override protected User doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); Location location = foursquared.getLastKnownLocation(); return foursquare.user( null, false, false, false, LocationUtils .createFoursquareLocation(location)); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onPostTaskUserUpdate(user, mReason); } } public void setActivity(PingsSettingsActivity activity) { mActivity = activity; } } private void restartNotifications() { PingsService.cancelPings(this); PingsService.setupPings(this); } private static class StateHolder { private UpdatePingsTask mTaskNotifications; private UpdateUserTask mTaskUpdateUser; private boolean mIsRunningTaskNotifications; private boolean mIsRunningTaskUpdateUser; public StateHolder(Context context) { mTaskNotifications = null; mTaskUpdateUser = null; mIsRunningTaskNotifications = false; mIsRunningTaskUpdateUser = false; } public void startTaskNotifications(PingsSettingsActivity activity, boolean on) { mIsRunningTaskNotifications = true; mTaskNotifications = new UpdatePingsTask(activity, on); mTaskNotifications.execute(); } public void startTaskUpdateUser(PingsSettingsActivity activity) { mIsRunningTaskUpdateUser = true; mTaskUpdateUser = new UpdateUserTask(activity); mTaskUpdateUser.execute(); } public void setActivity(PingsSettingsActivity activity) { if (mTaskNotifications != null) { mTaskNotifications.setActivity(activity); } if (mTaskUpdateUser != null) { mTaskUpdateUser.setActivity(activity); } } public boolean getIsRunningTaskNotifications() { return mIsRunningTaskNotifications; } public boolean getIsRunningTaskUpdateUser() { return mIsRunningTaskUpdateUser; } public void setIsRunningTaskNotifications(boolean isRunningTaskNotifications) { mIsRunningTaskNotifications = isRunningTaskNotifications; } public void setIsRunningTaskUpdateUser(boolean isRunningTaskUpdateUser) { mIsRunningTaskUpdateUser = isRunningTaskUpdateUser; } public void cancelTasks() { if (mTaskNotifications != null && mIsRunningTaskNotifications) { mTaskNotifications.setActivity(null); mTaskNotifications.cancel(true); } if (mTaskUpdateUser != null && mIsRunningTaskUpdateUser) { mTaskUpdateUser.setActivity(null); mTaskUpdateUser.cancel(true); } } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.maps.CheckinGroup; import com.joelapenna.foursquared.maps.CheckinGroupItemizedOverlay; import com.joelapenna.foursquared.maps.CheckinGroupItemizedOverlay.CheckinGroupOverlayTapListener; import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay; import com.joelapenna.foursquared.util.CheckinTimestampSort; import com.joelapenna.foursquared.util.GeoUtils; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.widget.MapCalloutView; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Added support for checkingroup items, also stopped recreation * of overlay group in onResume(). [2010-06-21] */ public class FriendsMapActivity extends MapActivity { public static final String TAG = "FriendsMapActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_CHECKIN_PARCELS = Foursquared.PACKAGE_NAME + ".FriendsMapActivity.EXTRA_CHECKIN_PARCELS"; private StateHolder mStateHolder; private Venue mTappedVenue; private MapCalloutView mCallout; private MapView mMapView; private MapController mMapController; private List<CheckinGroupItemizedOverlay> mCheckinGroupOverlays; private MyLocationOverlay mMyLocationOverlay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_map_activity); if (getLastNonConfigurationInstance() != null) { mStateHolder = (StateHolder) getLastNonConfigurationInstance(); } else { if (getIntent().hasExtra(EXTRA_CHECKIN_PARCELS)) { Parcelable[] parcelables = getIntent().getParcelableArrayExtra(EXTRA_CHECKIN_PARCELS); Group<Checkin> checkins = new Group<Checkin>(); for (int i = 0; i < parcelables.length; i++) { checkins.add((Checkin)parcelables[i]); } mStateHolder = new StateHolder(); mStateHolder.setCheckins(checkins); } else { Log.e(TAG, "FriendsMapActivity requires checkin array in intent extras."); finish(); return; } } initMap(); } @Override public void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); if (UiUtil.sdkVersion() > 3) { mMyLocationOverlay.enableCompass(); } } @Override public void onPause() { super.onPause(); mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); } private void initMap() { mMapView = (MapView) findViewById(R.id.mapView); mMapView.setBuiltInZoomControls(true); mMapController = mMapView.getController(); mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mMyLocationOverlay); loadSearchResults(mStateHolder.getCheckins()); mCallout = (MapCalloutView) findViewById(R.id.map_callout); mCallout.setVisibility(View.GONE); mCallout.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(FriendsMapActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, mTappedVenue); startActivity(intent); } }); recenterMap(); } private void loadSearchResults(Group<Checkin> checkins) { // One CheckinItemizedOverlay per group! CheckinGroupItemizedOverlay mappableCheckinsOverlay = createMappableCheckinsOverlay(checkins); mCheckinGroupOverlays = new ArrayList<CheckinGroupItemizedOverlay>(); if (mappableCheckinsOverlay != null) { mCheckinGroupOverlays.add(mappableCheckinsOverlay); } // Only add the list of checkin group overlays if it contains any overlays. if (mCheckinGroupOverlays.size() > 0) { mMapView.getOverlays().addAll(mCheckinGroupOverlays); } else { Toast.makeText(this, getResources().getString( R.string.friendsmapactivity_no_checkins), Toast.LENGTH_LONG).show(); } } /** * Create an overlay that contains a specific group's list of mappable * checkins. */ private CheckinGroupItemizedOverlay createMappableCheckinsOverlay(Group<Checkin> group) { // We want to group checkins by venue. Do max three checkins per venue, a total // of 100 venues total. We should only also display checkins that are within a // city radius, and are at most three hours old. CheckinTimestampSort timestamps = new CheckinTimestampSort(); Map<String, CheckinGroup> checkinMap = new HashMap<String, CheckinGroup>(); for (int i = 0, m = group.size(); i < m; i++) { Checkin checkin = (Checkin)group.get(i); Venue venue = checkin.getVenue(); if (VenueUtils.hasValidLocation(venue)) { // Make sure the venue is within city radius. try { int distance = Integer.parseInt(checkin.getDistance()); if (distance > FriendsActivity.CITY_RADIUS_IN_METERS) { continue; } } catch (NumberFormatException ex) { // Distance was invalid, ignore this checkin. continue; } // Make sure the checkin happened within the last three hours. try { Date date = new Date(checkin.getCreated()); if (date.before(timestamps.getBoundaryRecent())) { continue; } } catch (Exception ex) { // Timestamps was invalid, ignore this checkin. continue; } String venueId = venue.getId(); CheckinGroup cg = checkinMap.get(venueId); if (cg == null) { cg = new CheckinGroup(); checkinMap.put(venueId, cg); } // Stop appending if we already have three checkins here. if (cg.getCheckinCount() < 3) { cg.appendCheckin(checkin); } } // We can't have too many pins on the map. if (checkinMap.size() > 99) { break; } } Group<CheckinGroup> mappableCheckins = new Group<CheckinGroup>(checkinMap.values()); if (mappableCheckins.size() > 0) { CheckinGroupItemizedOverlay mappableCheckinsGroupOverlay = new CheckinGroupItemizedOverlay( this, ((Foursquared) getApplication()).getRemoteResourceManager(), this.getResources().getDrawable(R.drawable.pin_checkin_multiple), mCheckinGroupOverlayTapListener); mappableCheckinsGroupOverlay.setGroup(mappableCheckins); return mappableCheckinsGroupOverlay; } else { return null; } } private void recenterMap() { // Previously we'd try to zoom to span, but this gives us odd results a lot of times, // so falling back to zoom at a fixed level. GeoPoint center = mMyLocationOverlay.getMyLocation(); if (center != null) { Log.i(TAG, "Using my location overlay as center point for map centering."); mMapController.animateTo(center); mMapController.setZoom(16); } else { // Location overlay wasn't ready yet, try using last known geolocation from manager. Location bestLocation = GeoUtils.getBestLastGeolocation(this); if (bestLocation != null) { Log.i(TAG, "Using last known location for map centering."); mMapController.animateTo(GeoUtils.locationToGeoPoint(bestLocation)); mMapController.setZoom(16); } else { // We have no location information at all, so we'll just show the map at a high // zoom level and the user can zoom in as they wish. Log.i(TAG, "No location available for map centering."); mMapController.setZoom(8); } } } /** Handle taps on one of the pins. */ private CheckinGroupOverlayTapListener mCheckinGroupOverlayTapListener = new CheckinGroupOverlayTapListener() { @Override public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, CheckinGroup cg) { mTappedVenue = cg.getVenue(); mCallout.setTitle(cg.getVenue().getName()); mCallout.setMessage(cg.getDescription()); mCallout.setVisibility(View.VISIBLE); mMapController.animateTo(new GeoPoint(cg.getLatE6(), cg.getLonE6())); } @Override public void onTap(GeoPoint p, MapView mapView) { mCallout.setVisibility(View.GONE); } }; @Override protected boolean isRouteDisplayed() { return false; } private static class StateHolder { private Group<Checkin> mCheckins; public StateHolder() { mCheckins = new Group<Checkin>(); } public Group<Checkin> getCheckins() { return mCheckins; } public void setCheckins(Group<Checkin> checkins) { mCheckins = checkins; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.error.LocationException; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider; import com.joelapenna.foursquared.util.Comparators; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.TabsUtil; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import com.joelapenna.foursquared.widget.VenueListAdapter; import android.app.Activity; import android.app.SearchManager; import android.app.TabActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.os.Parcelable; import android.provider.SearchRecentSuggestions; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TabHost; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.Collections; import java.util.Observable; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class SearchVenuesActivity extends TabActivity { static final String TAG = "SearchVenuesActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String QUERY_NEARBY = null; public static SearchResultsObservable searchResultsObservable; private static final int MENU_SEARCH = 0; private static final int MENU_REFRESH = 1; private static final int MENU_NEARBY = 2; private static final int MENU_ADD_VENUE = 3; private static final int MENU_GROUP_SEARCH = 0; private SearchTask mSearchTask; private SearchHolder mSearchHolder = new SearchHolder(); private ListView mListView; private LinearLayout mEmpty; private TextView mEmptyText; private ProgressBar mEmptyProgress; private TabHost mTabHost; private SeparatedListAdapter mListAdapter; private boolean mIsShortcutPicker; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.search_venues_activity); setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); searchResultsObservable = new SearchResultsObservable(); initTabHost(); initListViewAdapter(); // Watch to see if we've been called as a shortcut intent. mIsShortcutPicker = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction()); if (getLastNonConfigurationInstance() != null) { if (DEBUG) Log.d(TAG, "Restoring state."); SearchHolder holder = (SearchHolder) getLastNonConfigurationInstance(); if (holder.results != null) { mSearchHolder.query = holder.query; setSearchResults(holder.results); putSearchResultsInAdapter(holder.results); } } else { onNewIntent(getIntent()); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(true); if (mSearchHolder.results == null && mSearchTask == null) { mSearchTask = (SearchTask) new SearchTask().execute(); } } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(); if (isFinishing()) { mListAdapter.removeObserver(); } } @Override public void onStop() { super.onStop(); if (mSearchTask != null) { mSearchTask.cancel(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Always show these. menu.add(MENU_GROUP_SEARCH, MENU_SEARCH, Menu.NONE, R.string.search_label) // .setIcon(R.drawable.ic_menu_search) // .setAlphabeticShortcut(SearchManager.MENU_KEY); menu.add(MENU_GROUP_SEARCH, MENU_NEARBY, Menu.NONE, R.string.nearby_label) // .setIcon(R.drawable.ic_menu_places); menu.add(MENU_GROUP_SEARCH, MENU_REFRESH, Menu.NONE, R.string.refresh) // .setIcon(R.drawable.ic_menu_refresh); menu.add(MENU_GROUP_SEARCH, MENU_ADD_VENUE, Menu.NONE, R.string.nearby_menu_add_venue) // .setIcon(R.drawable.ic_menu_add); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SEARCH: onSearchRequested(); return true; case MENU_NEARBY: executeSearchTask(null); return true; case MENU_REFRESH: executeSearchTask(mSearchHolder.query); return true; case MENU_ADD_VENUE: Intent intent = new Intent(SearchVenuesActivity.this, AddVenueActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Override public void onNewIntent(Intent intent) { if (intent != null) { String action = intent.getAction(); String query = intent.getStringExtra(SearchManager.QUERY); Log.i(TAG, "New Intent: action[" + action + "]."); if (!TextUtils.isEmpty(action)) { if (action.equals(Intent.ACTION_CREATE_SHORTCUT)) { Log.i(TAG, " action = create shortcut, user can click one of the current venues."); } else if (action.equals(Intent.ACTION_VIEW)) { if (!TextUtils.isEmpty(query)) { Log.i(TAG, " action = view, query term provided, prepopulating search."); startSearch(query, false, null, false); } else { Log.i(TAG, " action = view, but no query term provided, doing nothing."); } } else if (action.equals(Intent.ACTION_SEARCH) && !TextUtils.isEmpty(query)) { Log.i(TAG, " action = search, query term provided, executing search immediately."); SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, VenueQuerySuggestionsProvider.AUTHORITY, VenueQuerySuggestionsProvider.MODE); suggestions.saveRecentQuery(query, null); executeSearchTask(query); } } } } @Override public Object onRetainNonConfigurationInstance() { return mSearchHolder; } public void putSearchResultsInAdapter(Group<Group<Venue>> searchResults) { mListAdapter.removeObserver(); mListAdapter = new SeparatedListAdapter(this); int groupCount = searchResults.size(); for (int groupsIndex = 0; groupsIndex < groupCount; groupsIndex++) { Group<Venue> group = searchResults.get(groupsIndex); if (group.size() > 0) { VenueListAdapter groupAdapter = new VenueListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); groupAdapter.setGroup(group); if (DEBUG) Log.d(TAG, "Adding Section: " + group.getType()); mListAdapter.addSection(group.getType(), groupAdapter); } } mListView.setAdapter(mListAdapter); } public void setSearchResults(Group<Group<Venue>> searchResults) { if (DEBUG) Log.d(TAG, "Setting search results."); mSearchHolder.results = searchResults; searchResultsObservable.notifyObservers(); } void executeSearchTask(String query) { if (DEBUG) Log.d(TAG, "sendQuery()"); mSearchHolder.query = query; // not going through set* because we don't want to notify search result // observers. mSearchHolder.results = null; // If a task is already running, don't start a new one. if (mSearchTask != null && mSearchTask.getStatus() != AsyncTask.Status.FINISHED) { if (DEBUG) Log.d(TAG, "Query already running attempting to cancel: " + mSearchTask); if (!mSearchTask.cancel(true) && !mSearchTask.isCancelled()) { if (DEBUG) Log.d(TAG, "Unable to cancel search? Notifying the user."); Toast.makeText(this, getString(R.string.search_already_in_progress_toast), Toast.LENGTH_SHORT); return; } } mSearchTask = (SearchTask) new SearchTask().execute(); } void startItemActivity(Venue venue) { Intent intent = new Intent(SearchVenuesActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); startActivity(intent); } private void ensureSearchResults() { if (mListAdapter.getCount() > 0) { mEmpty.setVisibility(LinearLayout.GONE); mListView.setVisibility(ViewGroup.VISIBLE); } else { mEmpty.setVisibility(LinearLayout.VISIBLE); mEmptyProgress.setVisibility(ViewGroup.GONE); mEmptyText.setText(R.string.no_search_results); mListView.setVisibility(ViewGroup.GONE); } } private void ensureTitle(boolean finished) { if (finished) { if (mSearchHolder.query == QUERY_NEARBY) { setTitle(getString(R.string.title_search_finished_noquery)); } else { setTitle(getString(R.string.title_search_finished, mSearchHolder.query)); } } else { if (mSearchHolder.query == QUERY_NEARBY) { setTitle(getString(R.string.title_search_inprogress_noquery)); } else { setTitle(getString(R.string.title_search_inprogress, mSearchHolder.query)); } } } private void initListViewAdapter() { if (mListView != null) { throw new IllegalStateException("Trying to initialize already initialized ListView"); } mEmpty = (LinearLayout) findViewById(R.id.empty); mEmptyText = (TextView) findViewById(R.id.emptyText); mEmptyProgress = (ProgressBar) findViewById(R.id.emptyProgress); mListView = (ListView) findViewById(R.id.list); mListAdapter = new SeparatedListAdapter(this); mListView.setAdapter(mListAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Venue venue = (Venue) parent.getAdapter().getItem(position); if (mIsShortcutPicker) { setupShortcut(venue); finish(); } else { startItemActivity(venue); } finish(); } }); } protected void setupShortcut(Venue venue) { // First, set up the shortcut intent. For this example, we simply create // an intent that will bring us directly back to this activity. A more // typical implementation would use a data Uri in order to display a more // specific result, or a custom action in order to launch a specific operation. Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); shortcutIntent.setClassName(this, VenueActivity.class.getName()); shortcutIntent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, venue.getId()); // Then, set up the container intent (the response to the caller) Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, venue.getName()); Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.venue_shortcut_icon); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Now, return the result to the launcher setResult(RESULT_OK, intent); } private void initTabHost() { if (mTabHost != null) { throw new IllegalStateException("Trying to intialize already initializd TabHost"); } mTabHost = getTabHost(); TabsUtil.addTab(mTabHost, getString(R.string.tab_search_nav_venues), R.drawable.tab_search_nav_venues_selector, 0, R.id.listviewLayout); TabsUtil.addTab(mTabHost, getString(R.string.tab_search_nav_map), R.drawable.tab_search_nav_map_selector, 1, new Intent(this, SearchVenuesMapActivity.class)); mTabHost.setCurrentTab(0); // Fix layout for 1.5. if (UiUtil.sdkVersion() < 4) { FrameLayout flTabContent = (FrameLayout)findViewById(android.R.id.tabcontent); flTabContent.setPadding(0, 0, 0, 0); } } private class SearchTask extends AsyncTask<Void, Void, Group<Group<Venue>>> { private Exception mReason = null; @Override public void onPreExecute() { if (DEBUG) Log.d(TAG, "SearchTask: onPreExecute()"); setProgressBarIndeterminateVisibility(true); ensureTitle(false); } @Override public Group<Group<Venue>> doInBackground(Void... params) { try { return search(); } catch (Exception e) { mReason = e; } return null; } @Override public void onPostExecute(Group<Group<Venue>> groups) { try { if (groups == null) { NotificationsUtil.ToastReasonForFailure(SearchVenuesActivity.this, mReason); } else { setSearchResults(groups); putSearchResultsInAdapter(groups); } } finally { setProgressBarIndeterminateVisibility(false); ensureTitle(true); ensureSearchResults(); } } public Group<Group<Venue>> search() throws FoursquareException, LocationException, IOException { Foursquare foursquare = ((Foursquared) getApplication()).getFoursquare(); Location location = ((Foursquared) getApplication()).getLastKnownLocationOrThrow(); Group<Group<Venue>> groups = foursquare.venues(LocationUtils .createFoursquareLocation(location), mSearchHolder.query, 30); for (int i = 0; i < groups.size(); i++) { Collections.sort(groups.get(i), Comparators.getVenueDistanceComparator()); } return groups; } } private static class SearchHolder { Group<Group<Venue>> results; String query; } class SearchResultsObservable extends Observable { @Override public void notifyObservers(Object data) { setChanged(); super.notifyObservers(data); } public Group<Group<Venue>> getSearchResults() { return mSearchHolder.results; } public String getQuery() { return mSearchHolder.query; } }; }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import android.app.Activity; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.UriMatcher; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import java.net.URLDecoder; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class BrowsableActivity extends Activity { private static final String TAG = "BrowsableActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int URI_PATH_CHECKIN = 1; private static final int URI_PATH_CHECKINS = 2; private static final int URI_PATH_SEARCH = 3; private static final int URI_PATH_SHOUT = 4; private static final int URI_PATH_USER = 5; private static final int URI_PATH_VENUE = 6; public static String PARAM_SHOUT_TEXT = "shout"; public static String PARAM_SEARCH_QUERY = "q"; public static String PARAM_SEARCH_IMMEDIATE= "immediate"; public static String PARAM_USER_ID= "uid"; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI("m.foursquare.com", "checkin", URI_PATH_CHECKIN); sUriMatcher.addURI("m.foursquare.com", "checkins", URI_PATH_CHECKINS); sUriMatcher.addURI("m.foursquare.com", "search", URI_PATH_SEARCH); sUriMatcher.addURI("m.foursquare.com", "shout", URI_PATH_SHOUT); sUriMatcher.addURI("m.foursquare.com", "user", URI_PATH_USER); sUriMatcher.addURI("m.foursquare.com", "venue/#", URI_PATH_VENUE); } private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Uri uri = getIntent().getData(); if (DEBUG) Log.d(TAG, "Intent Data: " + uri); Intent intent; switch (sUriMatcher.match(uri)) { case URI_PATH_CHECKIN: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_CHECKIN"); intent = new Intent(this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getQueryParameter("vid")); startActivity(intent); break; case URI_PATH_CHECKINS: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_CHECKINS"); intent = new Intent(this, FriendsActivity.class); startActivity(intent); break; case URI_PATH_SEARCH: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_SEARCH"); intent = new Intent(this, SearchVenuesActivity.class); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_SEARCH_QUERY))) { intent.putExtra(SearchManager.QUERY, URLDecoder.decode(uri.getQueryParameter(PARAM_SEARCH_QUERY))); if (uri.getQueryParameter(PARAM_SEARCH_IMMEDIATE) != null && uri.getQueryParameter(PARAM_SEARCH_IMMEDIATE).equals("1")) { intent.setAction(Intent.ACTION_SEARCH); // interpret action as search immediately. } else { intent.setAction(Intent.ACTION_VIEW); // interpret as prepopulate search field only. } } startActivity(intent); break; case URI_PATH_SHOUT: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_SHOUT"); intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT, true); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_SHOUT_TEXT))) { intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_TEXT_PREPOPULATE, URLDecoder.decode(uri.getQueryParameter(PARAM_SHOUT_TEXT))); } startActivity(intent); break; case URI_PATH_USER: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_USER"); intent = new Intent(this, UserDetailsActivity.class); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_USER_ID))) { intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, uri.getQueryParameter(PARAM_USER_ID)); } startActivity(intent); break; case URI_PATH_VENUE: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_VENUE"); intent = new Intent(this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getLastPathSegment()); startActivity(intent); break; default: if (DEBUG) Log.d(TAG, "Matched: None"); } finish(); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay; import com.joelapenna.foursquared.maps.VenueItemizedOverlay; import com.joelapenna.foursquared.util.UiUtil; import android.os.Bundle; import android.util.Log; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueMapActivity extends MapActivity { public static final String TAG = "VenueMapActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueMapActivity.INTENT_EXTRA_VENUE"; private MapView mMapView; private MapController mMapController; private VenueItemizedOverlay mOverlay = null; private MyLocationOverlay mMyLocationOverlay = null; private StateHolder mStateHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.venue_map_activity); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE)); } else { Log.e(TAG, "VenueMapActivity requires a venue parcel its intent extras."); finish(); return; } } ensureUi(); } private void ensureUi() { /* Button mapsButton = (Button) findViewById(R.id.mapsButton); mapsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse( // "geo:0,0?q=" + mStateHolder.getVenue().getName() + " near " + mStateHolder.getVenue().getCity())); startActivity(intent); } }); if (FoursquaredSettings.SHOW_VENUE_MAP_BUTTON_MORE == false) { mapsButton.setVisibility(View.GONE); } */ setTitle(getString(R.string.venue_map_activity_title, mStateHolder.getVenue().getName())); mMapView = (MapView) findViewById(R.id.mapView); mMapView.setBuiltInZoomControls(true); mMapController = mMapView.getController(); mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mMyLocationOverlay); mOverlay = new VenueItemizedOverlay(this.getResources().getDrawable( R.drawable.map_marker_blue)); if (VenueUtils.hasValidLocation(mStateHolder.getVenue())) { Group<Venue> venueGroup = new Group<Venue>(); venueGroup.setType("Current Venue"); venueGroup.add(mStateHolder.getVenue()); mOverlay.setGroup(venueGroup); mMapView.getOverlays().add(mOverlay); } updateMap(); } @Override public void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); if (UiUtil.sdkVersion() > 3) { mMyLocationOverlay.enableCompass(); } } @Override public void onPause() { super.onPause(); mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); } @Override protected boolean isRouteDisplayed() { return false; } private void updateMap() { if (mOverlay != null && mOverlay.size() > 0) { GeoPoint center = mOverlay.getCenter(); mMapController.animateTo(center); mMapController.setZoom(17); } } private static class StateHolder { private Venue mVenue; public StateHolder() { } public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.widget.Toast; /** * Can be called to execute a shout. Should be presented with the transparent * dialog theme to appear only as a progress bar. When execution is complete, a * toast will be shown with a success or error message. * * For the location paramters of the checkin method, this activity will grab the * global last-known best location. * * The activity will setResult(RESULT_OK) if the shout worked, and will * setResult(RESULT_CANCELED) if it did not work. * * @date March 10, 2010 * @author Mark Wyszomierski (markww@gmail.com). */ public class ShoutExecuteActivity extends Activity { public static final String TAG = "ShoutExecuteActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_SHOUT = Foursquared.PACKAGE_NAME + ".ShoutExecuteActivity.INTENT_EXTRA_SHOUT"; public static final String INTENT_EXTRA_TELL_FRIENDS = Foursquared.PACKAGE_NAME + ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FRIENDS"; public static final String INTENT_EXTRA_TELL_FOLLOWERS = Foursquared.PACKAGE_NAME + ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS"; public static final String INTENT_EXTRA_TELL_TWITTER = Foursquared.PACKAGE_NAME + ".ShoutExecuteActivity.INTENT_EXTRA_TELL_TWITTER"; public static final String INTENT_EXTRA_TELL_FACEBOOK = Foursquared.PACKAGE_NAME + ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK"; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.checkin_execute_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); // We start the checkin immediately on creation. Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { mStateHolder = new StateHolder(); Foursquared foursquared = (Foursquared) getApplication(); Location location = foursquared.getLastKnownLocation(); mStateHolder.startTask( this, location, getIntent().getExtras().getString(INTENT_EXTRA_SHOUT), getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FRIENDS, false), getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FOLLOWERS, false), getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_TWITTER, false), getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FACEBOOK, false) ); } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunning()) { startProgressBar(getResources().getString(R.string.shout_action_label), getResources().getString(R.string.shout_execute_activity_progress_bar_message)); } } @Override public void onPause() { super.onPause(); stopProgressBar(); if (isFinishing()) { mStateHolder.cancelTasks(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } private void startProgressBar(String title, String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, title, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } private void onShoutComplete(CheckinResult result, Exception ex) { mStateHolder.setIsRunning(false); stopProgressBar(); if (result != null) { Toast.makeText(this, getResources().getString(R.string.shout_exceute_activity_result), Toast.LENGTH_LONG).show(); setResult(Activity.RESULT_OK); } else { NotificationsUtil.ToastReasonForFailure(this, ex); setResult(Activity.RESULT_CANCELED); } finish(); } private static class ShoutTask extends AsyncTask<Void, Void, CheckinResult> { private ShoutExecuteActivity mActivity; private Location mLocation; private String mShout; private boolean mTellFriends; private boolean mTellFollowers; private boolean mTellTwitter; private boolean mTellFacebook; private Exception mReason; public ShoutTask(ShoutExecuteActivity activity, Location location, String shout, boolean tellFriends, boolean tellFollowers, boolean tellTwitter, boolean tellFacebook) { mActivity = activity; mLocation = location; mShout = shout; mTellFriends = tellFriends; mTellFollowers = tellFollowers; mTellTwitter = tellTwitter; mTellFacebook = tellFacebook; } public void setActivity(ShoutExecuteActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(mActivity.getResources().getString( R.string.shout_action_label), mActivity.getResources().getString( R.string.shout_execute_activity_progress_bar_message)); } @Override protected CheckinResult doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); CheckinResult result = foursquare.checkin( null, null, LocationUtils.createFoursquareLocation(mLocation), mShout, !mTellFriends, // (isPrivate) mTellFollowers, mTellTwitter, mTellFacebook); return result; } catch (Exception e) { if (DEBUG) Log.d(TAG, "ShoutTask: Exception checking in.", e); mReason = e; } return null; } @Override protected void onPostExecute(CheckinResult result) { if (DEBUG) Log.d(TAG, "ShoutTask: onPostExecute()"); if (mActivity != null) { mActivity.onShoutComplete(result, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onShoutComplete(null, new Exception( "Shout cancelled.")); } } } private static class StateHolder { private ShoutTask mTask; private boolean mIsRunning; public StateHolder() { mIsRunning = false; } public void startTask(ShoutExecuteActivity activity, Location location, String shout, boolean tellFriends, boolean tellFollowers, boolean tellTwitter, boolean tellFacebook) { mIsRunning = true; mTask = new ShoutTask(activity, location, shout, tellFriends, tellFollowers, tellTwitter, tellFacebook); mTask.execute(); } public void setActivity(ShoutExecuteActivity activity) { if (mTask != null) { mTask.setActivity(activity); } } public boolean getIsRunning() { return mIsRunning; } public void setIsRunning(boolean isRunning) { mIsRunning = isRunning; } public void cancelTasks() { if (mTask != null && mIsRunning) { mTask.setActivity(null); mTask.cancel(true); } } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.LinearLayout; /** * This is pretty much a direct copy of LoadableListActivity. It just gives the caller * a chance to set their own view for the empty state. This is used by FriendsActivity * to show a button like 'Find some friends!' when the list is empty (in the case that * they are a new user and have no friends initially). * * By default, loadable_list_activity_with_view is used as the intial empty view with * a progress bar and textview description. The owner can then call setEmptyView() * with their own view to show if there are no results. * * @date April 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class LoadableListActivityWithView extends ListActivity { private LinearLayout mLayoutHeader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity_with_view); mLayoutHeader = (LinearLayout)findViewById(R.id.header); getListView().setDividerHeight(0); } public void setEmptyView(View view) { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); parent.getChildAt(0).setVisibility(View.GONE); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.addView(view); } public void setLoadingView() { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.getChildAt(0).setVisibility(View.VISIBLE); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } public LinearLayout getHeaderLayout() { return mLayoutHeader; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import android.app.ListActivity; import android.os.Bundle; import android.view.ViewGroup; import android.view.Window; import android.widget.ProgressBar; import android.widget.TextView; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LoadableListActivity extends ListActivity { private int mNoSearchResultsString = getNoSearchResultsStringId(); private ProgressBar mEmptyProgress; private TextView mEmptyText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity); mEmptyProgress = (ProgressBar)findViewById(R.id.emptyProgress); mEmptyText = (TextView)findViewById(R.id.emptyText); setLoadingView(); getListView().setDividerHeight(0); } public void setEmptyView() { mEmptyProgress.setVisibility(ViewGroup.GONE); mEmptyText.setText(mNoSearchResultsString); } public void setLoadingView() { mEmptyProgress.setVisibility(ViewGroup.VISIBLE); mEmptyText.setText("");//R.string.loading); } public void setLoadingView(String loadingText) { setLoadingView(); mEmptyText.setText(loadingText); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.widget.SegmentedButton; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.LinearLayout; /** * This is pretty much a direct copy of LoadableListActivity. It just gives the caller * a chance to set their own view for the empty state. This is used by FriendsActivity * to show a button like 'Find some friends!' when the list is empty (in the case that * they are a new user and have no friends initially). * * By default, loadable_list_activity_with_view is used as the intial empty view with * a progress bar and textview description. The owner can then call setEmptyView() * with their own view to show if there are no results. * * @date April 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class LoadableListActivityWithViewAndHeader extends ListActivity { private LinearLayout mLayoutHeader; private SegmentedButton mHeaderButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity_with_view_and_header); mLayoutHeader = (LinearLayout)findViewById(R.id.header); mHeaderButton = (SegmentedButton)findViewById(R.id.segmented); getListView().setDividerHeight(0); } public void setEmptyView(View view) { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); parent.getChildAt(0).setVisibility(View.GONE); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.addView(view); } public void setLoadingView() { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.getChildAt(0).setVisibility(View.VISIBLE); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } public LinearLayout getHeaderLayout() { return mLayoutHeader; } public SegmentedButton getHeaderButton() { return mHeaderButton; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FriendsActivity; import com.joelapenna.foursquared.MainActivity; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.StringFormatters; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.widget.RemoteViews; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This service will run every N minutes (specified by the user in settings). An alarm * handles running the service. * * When the service runs, we call /checkins. From the list of checkins, we cut down the * list of relevant checkins as follows: * <ul> * <li>Not one of our own checkins.</li> * <li>We haven't turned pings off for the user. This can be toggled on/off in the * UserDetailsActivity activity, per user.</li> * <li>The checkin is younger than the last time we ran this service.</li> * </ul> * * Note that the server might override the pings attribute to 'off' for certain checkins, * usually if the checkin is far away from our current location. * * Pings will not be cleared from the notification bar until a subsequent run can * generate at least one new ping. A new batch of pings will clear all * previous pings so as to not clutter the notification bar. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsService extends WakefulIntentService { public static final String TAG = "PingsService"; private static final boolean DEBUG = false; public static final int NOTIFICATION_ID_CHECKINS = 15; public PingsService() { super("PingsService"); } @Override public void onCreate() { super.onCreate(); } @Override protected void doWakefulWork(Intent intent) { Log.i(TAG, "Foursquare pings service running..."); // The user must have logged in once previously for this to work, // and not leave the app in a logged-out state. Foursquared foursquared = (Foursquared) getApplication(); Foursquare foursquare = foursquared.getFoursquare(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (!foursquared.isReady()) { Log.i(TAG, "User not logged in, cannot proceed."); return; } // Before running, make sure the user still wants pings on. // For example, the user could have turned pings on from // this device, but then turned it off on a second device. This // service would continue running then, continuing to notify the // user. if (!checkUserStillWantsPings(foursquared.getUserId(), foursquare)) { // Turn off locally. Log.i(TAG, "Pings have been turned off for user, cancelling service."); prefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); cancelPings(this); return; } // Get the users current location and then request nearby checkins. Group<Checkin> checkins = null; Location location = getLastGeolocation(); if (location != null) { try { checkins = foursquare.checkins( LocationUtils.createFoursquareLocation(location)); } catch (Exception ex) { Log.e(TAG, "Error getting checkins in pings service.", ex); } } else { Log.e(TAG, "Could not find location in pings service, cannot proceed."); } if (checkins != null) { Log.i(TAG, "Checking " + checkins.size() + " checkins for pings."); // Don't accept any checkins that are older than the last time we ran. long lastRunTime = prefs.getLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()); Date dateLast = new Date(lastRunTime); Log.i(TAG, "Last service run time: " + dateLast.toLocaleString() + " (" + lastRunTime + ")."); // Now build the list of 'new' checkins. List<Checkin> newCheckins = new ArrayList<Checkin>(); for (Checkin it : checkins) { if (DEBUG) Log.d(TAG, "Checking checkin of " + it.getUser().getFirstname()); // Ignore ourselves. The server should handle this by setting the pings flag off but.. if (it.getUser() != null && it.getUser().getId().equals(foursquared.getUserId())) { if (DEBUG) Log.d(TAG, " Ignoring checkin of ourselves."); continue; } // Check that our user wanted to see pings from this user. if (!it.getPing()) { if (DEBUG) Log.d(TAG, " Pings are off for this user."); continue; } // If it's an 'off the grid' checkin, ignore. if (it.getVenue() == null && it.getShout() == null) { if (DEBUG) Log.d(TAG, " Checkin is off the grid, ignoring."); continue; } // Check against date times. try { Date dateCheckin = StringFormatters.DATE_FORMAT.parse(it.getCreated()); if (DEBUG) { Log.d(TAG, " Comaring date times for checkin."); Log.d(TAG, " Last run time: " + dateLast.toLocaleString()); Log.d(TAG, " Checkin time: " + dateCheckin.toLocaleString()); } if (dateCheckin.after(dateLast)) { if (DEBUG) Log.d(TAG, " Checkin is younger than our last run time, passes all tests!!"); newCheckins.add(it); } else { if (DEBUG) Log.d(TAG, " Checkin is older than last run time."); } } catch (ParseException ex) { if (DEBUG) Log.e(TAG, " Error parsing checkin timestamp: " + it.getCreated(), ex); } } Log.i(TAG, "Found " + newCheckins.size() + " new checkins."); notifyUser(newCheckins); } else { // Checkins were null, so don't record this as the last run time in order to try // fetching checkins we may have missed on the next run. // Thanks to logan.johnson@gmail.com for the fix. Log.i(TAG, "Checkins were null, won't update last run timestamp."); return; } // Record this as the last time we ran. prefs.edit().putLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()).commit(); } private Location getLastGeolocation() { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = manager.getAllProviders(); Location bestLocation = null; for (String it : providers) { Location location = manager.getLastKnownLocation(it); if (location != null) { if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { bestLocation = location; } } } return bestLocation; } private void notifyUser(List<Checkin> newCheckins) { // If we have no new checkins to show, nothing to do. We would also be leaving the // previous batch of pings alive (if any) which is ok. if (newCheckins.size() < 1) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // Clear all previous pings notifications before showing new ones. NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); // We'll only ever show a single entry, so we collapse data depending on how many // new checkins we received on this refresh. RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.pings_list_item); if (newCheckins.size() == 1) { // A single checkin, show full checkin preview. Checkin checkin = newCheckins.get(0); String checkinMsgLine1 = StringFormatters.getCheckinMessageLine1(checkin, true); String checkinMsgLine2 = StringFormatters.getCheckinMessageLine2(checkin); String checkinMsgLine3 = StringFormatters.getCheckinMessageLine3(checkin); contentView.setTextViewText(R.id.text1, checkinMsgLine1); if (!TextUtils.isEmpty(checkinMsgLine2)) { contentView.setTextViewText(R.id.text2, checkinMsgLine2); contentView.setTextViewText(R.id.text3, checkinMsgLine3); } else { contentView.setTextViewText(R.id.text2, checkinMsgLine3); } } else { // More than one new checkin, collapse them. String checkinMsgLine1 = newCheckins.size() + " new Foursquare checkins!"; StringBuilder sbCheckinMsgLine2 = new StringBuilder(1024); for (Checkin it : newCheckins) { sbCheckinMsgLine2.append(StringFormatters.getUserAbbreviatedName(it.getUser())); sbCheckinMsgLine2.append(", "); } if (sbCheckinMsgLine2.length() > 0) { sbCheckinMsgLine2.delete(sbCheckinMsgLine2.length()-2, sbCheckinMsgLine2.length()); } String checkinMsgLine3 = "at " + StringFormatters.DATE_FORMAT_TODAY.format(new Date()); contentView.setTextViewText(R.id.text1, checkinMsgLine1); contentView.setTextViewText(R.id.text2, sbCheckinMsgLine2.toString()); contentView.setTextViewText(R.id.text3, checkinMsgLine3); } PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, FriendsActivity.class), 0); Notification notification = new Notification( R.drawable.notification_icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.flags |= Notification.FLAG_AUTO_CANCEL; if (prefs.getBoolean(Preferences.PREFERENCE_PINGS_VIBRATE, false)) { notification.defaults |= Notification.DEFAULT_VIBRATE; } if (newCheckins.size() > 1) { notification.number = newCheckins.size(); } mgr.notify(NOTIFICATION_ID_CHECKINS, notification); } private boolean checkUserStillWantsPings(String userId, Foursquare foursquare) { try { User user = foursquare.user(userId, false, false, false, null); if (user != null) { return user.getSettings().getPings().equals("on"); } } catch (Exception ex) { // Assume they still want it on. } return true; } public static void setupPings(Context context) { // If the user has pings on, set an alarm every N minutes, where N is their // requested refresh rate. We default to 30 if some problem reading set interval. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean(Preferences.PREFERENCE_PINGS, false)) { int refreshRateInMinutes = getRefreshIntervalInMinutes(prefs); if (DEBUG) { Log.d(TAG, "User has pings on, attempting to setup alarm with interval: " + refreshRateInMinutes + ".."); } // We want to mark this as the last run time so we don't get any notifications // before the service is started. prefs.edit().putLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()).commit(); // Schedule the alarm. AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + (refreshRateInMinutes * 60 * 1000), refreshRateInMinutes * 60 * 1000, makePendingIntentAlarm(context)); } } public static void cancelPings(Context context) { AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.cancel(makePendingIntentAlarm(context)); } private static PendingIntent makePendingIntentAlarm(Context context) { return PendingIntent.getBroadcast(context, 0, new Intent(context, PingsOnAlarmReceiver.class), 0); } public static void clearAllNotifications(Context context) { NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); } public static void generatePingsTest(Context context) { Intent intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.pings_list_item); contentView.setTextViewText(R.id.text1, "Ping title line"); contentView.setTextViewText(R.id.text2, "Ping message line 2"); contentView.setTextViewText(R.id.text3, "Ping message line 3"); Notification notification = new Notification( R.drawable.notification_icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.defaults |= Notification.DEFAULT_VIBRATE; mgr.notify(-1, notification); } private static int getRefreshIntervalInMinutes(SharedPreferences prefs) { int refreshRateInMinutes = 30; try { refreshRateInMinutes = Integer.parseInt(prefs.getString( Preferences.PREFERENCE_PINGS_INTERVAL, String.valueOf(refreshRateInMinutes))); } catch (NumberFormatException ex) { Log.e(TAG, "Error parsing pings interval time, defaulting to: " + refreshRateInMinutes); } return refreshRateInMinutes; } }
Java
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsOnAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { WakefulIntentService.acquireStaticLock(context); context.startService(new Intent(context, PingsService.class)); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.appwidget.FriendsAppWidgetProvider; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.Comparators; import android.app.IntentService; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import java.util.Collections; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquaredService extends IntentService { private static final String TAG = "FoursquaredService"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public FoursquaredService() { super("FoursquaredService"); } /** * Handles various intents, appwidget state changes for starters. * * {@inheritDoc} */ @Override public void onHandleIntent(Intent intent) { if (DEBUG) Log.d(TAG, "onHandleIntent: " + intent.toString()); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(intent.getAction())) { updateWidgets(); } } private void updateWidgets() { if (DEBUG) Log.d(TAG, "updateWidgets"); Group<Checkin> checkins = null; Foursquared foursquared = ((Foursquared) getApplication()); if (foursquared.isReady()) { if (DEBUG) Log.d(TAG, "User settings are ready, starting normal widget update."); try { checkins = foursquared.getFoursquare().checkins( LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); } catch (Exception e) { if (DEBUG) Log.d(TAG, "Exception: Skipping widget update.", e); return; } Collections.sort(checkins, Comparators.getCheckinRecencyComparator()); // Request the user photos for the checkins... At the moment, this // is async. It is likely this means that the first update of the widget will never // show user photos as the photos will still be downloading when the getInputStream // call is made in SpecialDealsAppWidgetProvider. for (int i = 0; i < checkins.size(); i++) { Uri photoUri = Uri.parse((checkins.get(i)).getUser().getPhoto()); if (!foursquared.getRemoteResourceManager().exists(photoUri)) { foursquared.getRemoteResourceManager().request(photoUri); } } } AppWidgetManager am = AppWidgetManager.getInstance(this); int[] appWidgetIds = am.getAppWidgetIds(new ComponentName(this, FriendsAppWidgetProvider.class)); for (int i = 0; i < appWidgetIds.length; i++) { FriendsAppWidgetProvider.updateAppWidget((Context) this, foursquared .getRemoteResourceManager(), am, appWidgetIds[i], checkins); } } }
Java
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class OnBootReceiver extends BroadcastReceiver { public static final String TAG = "OnBootReceiver"; @Override public void onReceive(Context context, Intent intent) { // If the user has notifications on, set an alarm every N minutes, where N is their // requested refresh rate. PingsService.setupPings(context); } }
Java
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.PowerManager; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public abstract class WakefulIntentService extends IntentService { public static final String TAG = "WakefulIntentService"; public static final String LOCK_NAME_STATIC = "com.joelapenna.foursquared.app.WakefulintentService.Static"; private static PowerManager.WakeLock lockStatic = null; abstract void doWakefulWork(Intent intent); public static void acquireStaticLock(Context context) { getLock(context).acquire(); } private synchronized static PowerManager.WakeLock getLock(Context context) { if (lockStatic == null) { PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE); lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME_STATIC); lockStatic.setReferenceCounted(true); } return(lockStatic); } public WakefulIntentService(String name) { super(name); } @Override final protected void onHandleIntent(Intent intent) { doWakefulWork(intent); getLock(this).release(); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.FriendListAdapter; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; /** * To be used when a user has some friends in common. We show two lists, by default * the first list is 'friends in common'. The second list is all friends. This is * expected to be used with a fully-fetched user object, so the friends in common * group should already be fetched. The full 'all friends' list is fetched separately * within this activity. * * If the user has no friends in common, then just use UserDetailsFriendsActivity * directly. * * @date September 23, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserDetailsFriendsInCommonActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "UserDetailsFriendsInCommonActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME + ".UserDetailsFriendsInCommonActivity.EXTRA_USER_PARCEL"; private StateHolder mStateHolder; private FriendListAdapter mListAdapter; private ScrollView mLayoutEmpty; private static final int MENU_REFRESH = 0; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(EXTRA_USER_PARCEL)) { mStateHolder.setUser((User)getIntent().getParcelableExtra(EXTRA_USER_PARCEL)); if (mStateHolder.getUser().getFriendsInCommon() == null || mStateHolder.getUser().getFriendsInCommon().size() == 0) { Log.e(TAG, TAG + " requires user parcel have friends in common size > 0."); finish(); return; } } else { Log.e(TAG, TAG + " requires user parcel in intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { LayoutInflater inflater = LayoutInflater.from(this); mLayoutEmpty = (ScrollView)inflater.inflate(R.layout.user_details_friends_activity_empty, null); mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); mListAdapter = new FriendListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); if (mStateHolder.getFriendsInCommonOnly()) { mListAdapter.setGroup(mStateHolder.getUser().getFriendsInCommon()); } else { mListAdapter.setGroup(mStateHolder.getAllFriends()); if (mStateHolder.getAllFriends().size() == 0) { if (mStateHolder.getRanOnce()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.user_details_friends_in_common_common_friends), getString(R.string.user_details_friends_in_common_all_friends)); if (mStateHolder.getFriendsInCommonOnly()) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setFriendsInCommonOnly(true); mListAdapter.setGroup(mStateHolder.getUser().getFriendsInCommon()); } else { mStateHolder.setFriendsInCommonOnly(false); mListAdapter.setGroup(mStateHolder.getAllFriends()); if (mStateHolder.getAllFriends().size() < 1) { if (mStateHolder.getRanOnce()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTaskAllFriends(UserDetailsFriendsInCommonActivity.this); } } } mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } }); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(false); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = (User) parent.getAdapter().getItem(position); Intent intent = new Intent(UserDetailsFriendsInCommonActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); startActivity(intent); } }); if (mStateHolder.getIsRunningTaskAllFriends()) { setProgressBarIndeterminateVisibility(true); } else { setProgressBarIndeterminateVisibility(false); } setTitle(getString(R.string.user_details_friends_in_common_title, mStateHolder.getUser().getFirstname())); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: if (!mStateHolder.getFriendsInCommonOnly()) { mStateHolder.startTaskAllFriends(this); } return true; } return super.onOptionsItemSelected(item); } private void onStartTaskAllFriends() { mStateHolder.setIsRunningTaskAllFriends(true); setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onTaskAllFriendsComplete(Group<User> allFriends, Exception ex) { setProgressBarIndeterminateVisibility(false); mStateHolder.setRanOnce(true); mStateHolder.setIsRunningTaskAllFriends(false); if (allFriends != null) { mStateHolder.setAllFriends(allFriends); } else { NotificationsUtil.ToastReasonForFailure(this, ex); } SegmentedButton buttons = getHeaderButton(); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getAllFriends()); if (mStateHolder.getAllFriends().size() == 0) { if (mStateHolder.getRanOnce()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } } /** * Gets friends of the current user we're working for. */ private static class TaskAllFriends extends AsyncTask<Void, Void, Group<User>> { private UserDetailsFriendsInCommonActivity mActivity; private String mUserId; private Exception mReason; public TaskAllFriends(UserDetailsFriendsInCommonActivity activity, String userId) { mActivity = activity; mUserId = userId; } @Override protected void onPreExecute() { mActivity.onStartTaskAllFriends(); } @Override protected Group<User> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.friends( mUserId, LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<User> allFriends) { if (mActivity != null) { mActivity.onTaskAllFriendsComplete(allFriends, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskAllFriendsComplete(null, mReason); } } public void setActivity(UserDetailsFriendsInCommonActivity activity) { mActivity = activity; } } private static class StateHolder { private User mUser; private Group<User> mAllFriends; private TaskAllFriends mTaskAllFriends; private boolean mIsRunningTaskAllFriends; private boolean mRanOnceTaskAllFriends; private boolean mFriendsInCommonOnly; public StateHolder() { mAllFriends = new Group<User>(); mIsRunningTaskAllFriends = false; mRanOnceTaskAllFriends = false; mFriendsInCommonOnly = true; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public Group<User> getAllFriends() { return mAllFriends; } public void setAllFriends(Group<User> allFriends) { mAllFriends = allFriends; } public void startTaskAllFriends(UserDetailsFriendsInCommonActivity activity) { if (!mIsRunningTaskAllFriends) { mIsRunningTaskAllFriends = true; mTaskAllFriends = new TaskAllFriends(activity, mUser.getId()); mTaskAllFriends.execute(); } } public void setActivity(UserDetailsFriendsInCommonActivity activity) { if (mTaskAllFriends != null) { mTaskAllFriends.setActivity(activity); } } public boolean getIsRunningTaskAllFriends() { return mIsRunningTaskAllFriends; } public void setIsRunningTaskAllFriends(boolean isRunning) { mIsRunningTaskAllFriends = isRunning; } public void cancelTasks() { if (mTaskAllFriends != null) { mTaskAllFriends.setActivity(null); mTaskAllFriends.cancel(true); } } public boolean getRanOnce() { return mRanOnceTaskAllFriends; } public void setRanOnce(boolean ranOnce) { mRanOnceTaskAllFriends = ranOnce; } public boolean getFriendsInCommonOnly() { return mFriendsInCommonOnly; } public void setFriendsInCommonOnly(boolean friendsInCommonOnly) { mFriendsInCommonOnly = friendsInCommonOnly; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.appwidget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.MainActivity; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.UserDetailsActivity; import com.joelapenna.foursquared.app.FoursquaredService; import com.joelapenna.foursquared.util.DumpcatcherHelper; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.text.format.DateUtils; import android.util.Log; import android.view.View; import android.widget.RemoteViews; import java.io.IOException; import java.util.Date; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FriendsAppWidgetProvider extends AppWidgetProvider { private static final String TAG = "FriendsAppWidgetProvider"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int[][] WIDGET_VIEW_IDS = { { R.id.widgetItem0, R.id.photo0, R.id.user0, R.id.time0, R.id.location0 }, { R.id.widgetItem1, R.id.photo1, R.id.user1, R.id.time1, R.id.location1 }, { R.id.widgetItem2, R.id.photo2, R.id.user2, R.id.time2, R.id.location2 }, { R.id.widgetItem3, R.id.photo3, R.id.user3, R.id.time3, R.id.location3 }, { R.id.widgetItem4, R.id.photo4, R.id.user4, R.id.time4, R.id.location4 } }; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { if (DEBUG) Log.d(TAG, "onUpdate()"); Intent intent = new Intent(context, FoursquaredService.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); context.startService(intent); } public static void updateAppWidget(Context context, RemoteResourceManager rrm, AppWidgetManager appWidgetManager, Integer appWidgetId, Group<Checkin> checkins) { if (DEBUG) Log.d(TAG, "updateAppWidget: " + String.valueOf(appWidgetId)); // Get the layout for the App Widget and attach an on-click listener to the button RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.friends_appwidget); if (DEBUG) Log.d(TAG, "adding header intent: " + String.valueOf(appWidgetId)); Intent baseIntent = new Intent(context, MainActivity.class); views.setOnClickPendingIntent(R.id.widgetHeader, PendingIntent.getActivity(context, 0, baseIntent, 0)); if (DEBUG) Log.d(TAG, "adding footer intent: " + String.valueOf(appWidgetId)); baseIntent = new Intent(context, FoursquaredService.class); baseIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); views.setOnClickPendingIntent(R.id.widgetFooter, PendingIntent.getService(context, 0, baseIntent, 0)); // Now hide all views if checkins is null (a sign of not being logged in), or populate the // checkins. if (checkins == null) { if (DEBUG) Log.d(TAG, "checkins is null, hiding UI."); views.setViewVisibility(R.id.widgetNotLoggedInTextView, View.VISIBLE); for (int i = 0; i < WIDGET_VIEW_IDS.length; i++) { hideCheckinView(views, WIDGET_VIEW_IDS[i]); } } else { if (DEBUG) Log.d(TAG, "Displaying checkins"); views.setViewVisibility(R.id.widgetNotLoggedInTextView, View.GONE); int numCheckins = checkins.size(); for (int i = 0; i < WIDGET_VIEW_IDS.length; i++) { if (i < numCheckins) { updateCheckinView(context, rrm, views, checkins.get(i), WIDGET_VIEW_IDS[i]); } else { hideCheckinView(views, WIDGET_VIEW_IDS[i]); } } } // Lastly, update the refresh timestamp CharSequence timestamp = DateUtils.formatDateTime(context, new Date().getTime(), DateUtils.FORMAT_SHOW_TIME); views.setTextViewText(R.id.widgetFooter, context.getResources().getString( R.string.friends_appwidget_footer_text, timestamp)); // Tell the AppWidgetManager to perform an update on the current App Widget try { appWidgetManager.updateAppWidget(appWidgetId, views); } catch (Exception e) { if (DEBUG) Log.d(TAG, "updateAppWidget crashed: ", e); DumpcatcherHelper.sendException(e); } } private static void updateCheckinView(Context context, RemoteResourceManager rrm, RemoteViews views, Checkin checkin, int[] viewIds) { int viewId = viewIds[0]; int photoViewId = viewIds[1]; int userViewId = viewIds[2]; int timeViewId = viewIds[3]; int locationViewId = viewIds[4]; final User user = checkin.getUser(); final Uri photoUri = Uri.parse(user.getPhoto()); views.setViewVisibility(viewId, View.VISIBLE); Intent baseIntent; baseIntent = new Intent(context, UserDetailsActivity.class); baseIntent.putExtra(UserDetailsActivity.EXTRA_USER_ID, checkin.getUser().getId()); baseIntent.setData(Uri.parse("https://foursquare.com/user/" + checkin.getUser().getId())); views.setOnClickPendingIntent(viewId, PendingIntent.getActivity(context, 0, baseIntent, 0)); try { Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri)); views.setImageViewBitmap(photoViewId, bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(checkin.getUser().getGender())) { views.setImageViewResource(photoViewId, R.drawable.blank_boy); } else { views.setImageViewResource(photoViewId, R.drawable.blank_girl); } } views.setTextViewText(userViewId, StringFormatters.getUserAbbreviatedName(user)); views.setTextViewText(timeViewId, StringFormatters.getRelativeTimeSpanString(checkin .getCreated())); if (VenueUtils.isValid(checkin.getVenue())) { views.setTextViewText(locationViewId, checkin.getVenue().getName()); } else { views.setTextViewText(locationViewId, ""); } } private static void hideCheckinView(RemoteViews views, int[] viewIds) { views.setViewVisibility(viewIds[0], View.GONE); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.location; import com.joelapenna.foursquare.Foursquare.Location; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LocationUtils { public static final Location createFoursquareLocation(android.location.Location location) { if (location == null) { return new Location(null, null, null, null, null); } String geolat = null; if (location.getLatitude() != 0.0) { geolat = String.valueOf(location.getLatitude()); } String geolong = null; if (location.getLongitude() != 0.0) { geolong = String.valueOf(location.getLongitude()); } String geohacc = null; if (location.hasAccuracy()) { geohacc = String.valueOf(location.getAccuracy()); } String geoalt = null; if (location.hasAccuracy()) { geoalt = String.valueOf(location.hasAltitude()); } return new Location(geolat, geolong, geohacc, null, geoalt); } }
Java
package com.joelapenna.foursquared.location; import com.joelapenna.foursquared.FoursquaredSettings; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import java.util.Date; import java.util.List; import java.util.Observable; public class BestLocationListener extends Observable implements LocationListener { private static final String TAG = "BestLocationListener"; private static final boolean DEBUG = FoursquaredSettings.LOCATION_DEBUG; public static final long LOCATION_UPDATE_MIN_TIME = 0; public static final long LOCATION_UPDATE_MIN_DISTANCE = 0; public static final long SLOW_LOCATION_UPDATE_MIN_TIME = 1000 * 60 * 5; public static final long SLOW_LOCATION_UPDATE_MIN_DISTANCE = 50; public static final float REQUESTED_FIRST_SEARCH_ACCURACY_IN_METERS = 100.0f; public static final int REQUESTED_FIRST_SEARCH_MAX_DELTA_THRESHOLD = 1000 * 60 * 5; public static final long LOCATION_UPDATE_MAX_DELTA_THRESHOLD = 1000 * 60 * 5; private Location mLastLocation; public BestLocationListener() { super(); } @Override public void onLocationChanged(Location location) { if (DEBUG) Log.d(TAG, "onLocationChanged: " + location); updateLocation(location); } @Override public void onProviderDisabled(String provider) { // do nothing. } @Override public void onProviderEnabled(String provider) { // do nothing. } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // do nothing. } synchronized public void onBestLocationChanged(Location location) { if (DEBUG) Log.d(TAG, "onBestLocationChanged: " + location); mLastLocation = location; setChanged(); notifyObservers(location); } synchronized public Location getLastKnownLocation() { return mLastLocation; } synchronized public void clearLastKnownLocation() { mLastLocation = null; } public void updateLocation(Location location) { if (DEBUG) { Log.d(TAG, "updateLocation: Old: " + mLastLocation); Log.d(TAG, "updateLocation: New: " + location); } // Cases where we only have one or the other. if (location != null && mLastLocation == null) { if (DEBUG) Log.d(TAG, "updateLocation: Null last location"); onBestLocationChanged(location); return; } else if (location == null) { if (DEBUG) Log.d(TAG, "updated location is null, doing nothing"); return; } long now = new Date().getTime(); long locationUpdateDelta = now - location.getTime(); long lastLocationUpdateDelta = now - mLastLocation.getTime(); boolean locationIsInTimeThreshold = locationUpdateDelta <= LOCATION_UPDATE_MAX_DELTA_THRESHOLD; boolean lastLocationIsInTimeThreshold = lastLocationUpdateDelta <= LOCATION_UPDATE_MAX_DELTA_THRESHOLD; boolean locationIsMostRecent = locationUpdateDelta <= lastLocationUpdateDelta; boolean accuracyComparable = location.hasAccuracy() || mLastLocation.hasAccuracy(); boolean locationIsMostAccurate = false; if (accuracyComparable) { // If we have only one side of the accuracy, that one is more // accurate. if (location.hasAccuracy() && !mLastLocation.hasAccuracy()) { locationIsMostAccurate = true; } else if (!location.hasAccuracy() && mLastLocation.hasAccuracy()) { locationIsMostAccurate = false; } else { // If we have both accuracies, do a real comparison. locationIsMostAccurate = location.getAccuracy() <= mLastLocation.getAccuracy(); } } if (DEBUG) { Log.d(TAG, "locationIsMostRecent:\t\t\t" + locationIsMostRecent); Log.d(TAG, "locationUpdateDelta:\t\t\t" + locationUpdateDelta); Log.d(TAG, "lastLocationUpdateDelta:\t\t" + lastLocationUpdateDelta); Log.d(TAG, "locationIsInTimeThreshold:\t\t" + locationIsInTimeThreshold); Log.d(TAG, "lastLocationIsInTimeThreshold:\t" + lastLocationIsInTimeThreshold); Log.d(TAG, "accuracyComparable:\t\t\t" + accuracyComparable); Log.d(TAG, "locationIsMostAccurate:\t\t" + locationIsMostAccurate); } // Update location if its more accurate and w/in time threshold or if // the old location is // too old and this update is newer. if (accuracyComparable && locationIsMostAccurate && locationIsInTimeThreshold) { onBestLocationChanged(location); } else if (locationIsInTimeThreshold && !lastLocationIsInTimeThreshold) { onBestLocationChanged(location); } } public boolean isAccurateEnough(Location location) { if (location != null && location.hasAccuracy() && location.getAccuracy() <= REQUESTED_FIRST_SEARCH_ACCURACY_IN_METERS) { long locationUpdateDelta = new Date().getTime() - location.getTime(); if (locationUpdateDelta < REQUESTED_FIRST_SEARCH_MAX_DELTA_THRESHOLD) { if (DEBUG) Log.d(TAG, "Location is accurate: " + location.toString()); return true; } } if (DEBUG) Log.d(TAG, "Location is not accurate: " + String.valueOf(location)); return false; } public void register(LocationManager locationManager, boolean gps) { if (DEBUG) Log.d(TAG, "Registering this location listener: " + this.toString()); long updateMinTime = SLOW_LOCATION_UPDATE_MIN_TIME; long updateMinDistance = SLOW_LOCATION_UPDATE_MIN_DISTANCE; if (gps) { updateMinTime = LOCATION_UPDATE_MIN_TIME; updateMinDistance = LOCATION_UPDATE_MIN_DISTANCE; } List<String> providers = locationManager.getProviders(true); int providersCount = providers.size(); for (int i = 0; i < providersCount; i++) { String providerName = providers.get(i); if (locationManager.isProviderEnabled(providerName)) { updateLocation(locationManager.getLastKnownLocation(providerName)); } // Only register with GPS if we've explicitly allowed it. if (gps || !LocationManager.GPS_PROVIDER.equals(providerName)) { locationManager.requestLocationUpdates(providerName, updateMinTime, updateMinDistance, this); } } } public void unregister(LocationManager locationManager) { if (DEBUG) Log.d(TAG, "Unregistering this location listener: " + this.toString()); locationManager.removeUpdates(this); } /** * Updates the current location with the last known location without * registering any location listeners. * * @param locationManager the LocationManager instance from which to * retrieve the latest known location */ synchronized public void updateLastKnownLocation(LocationManager locationManager) { List<String> providers = locationManager.getProviders(true); for (int i = 0, providersCount = providers.size(); i < providersCount; i++) { String providerName = providers.get(i); if (locationManager.isProviderEnabled(providerName)) { updateLocation(locationManager.getLastKnownLocation(providerName)); } } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.maps; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.util.StringFormatters; /** * * @date June 18, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class CheckinGroup implements FoursquareType { private Venue mVenue; private String mDescription; private String mPhotoUrl; private String mGender; private int mCheckinCount; private int mLatE6; private int mLonE6; public CheckinGroup() { mVenue = null; mDescription = ""; mPhotoUrl = ""; mCheckinCount = 0; mGender = Foursquare.MALE; } public void appendCheckin(Checkin checkin) { User user = checkin.getUser(); if (mCheckinCount == 0) { mPhotoUrl = user.getPhoto(); mGender = user.getGender(); mDescription += StringFormatters.getUserAbbreviatedName(user); Venue venue = checkin.getVenue(); mVenue = venue; mLatE6 = (int)(Double.parseDouble(venue.getGeolat()) * 1E6); mLonE6 = (int)(Double.parseDouble(venue.getGeolong()) * 1E6); } else { mDescription += ", " + StringFormatters.getUserAbbreviatedName(user); } mCheckinCount++; } public Venue getVenue() { return mVenue; } public int getLatE6() { return mLatE6; } public int getLonE6() { return mLonE6; } public String getDescription() { return mDescription; } public String getPhotoUrl() { return mPhotoUrl; } public String getGender() { return mGender; } public int getCheckinCount() { return mCheckinCount; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.maps; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import java.io.IOException; /** * @date June 18, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class CheckinGroupItemizedOverlay extends BaseGroupItemizedOverlay<CheckinGroup> { public static final String TAG = "CheckinItemizedGroupOverlay"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private Context mContext; private RemoteResourceManager mRrm; private Bitmap mBmpPinSingle; private Bitmap mBmpPinMultiple; private OverlayItem mLastSelected; private CheckinGroupOverlayTapListener mTapListener; public CheckinGroupItemizedOverlay(Context context, RemoteResourceManager rrm, Drawable defaultMarker, CheckinGroupOverlayTapListener tapListener) { super(defaultMarker); mContext = context; mRrm = rrm; mTapListener = tapListener; mLastSelected = null; constructScaledPinBackgrounds(context); } @Override protected OverlayItem createItem(int i) { CheckinGroup cg = (CheckinGroup)group.get(i); GeoPoint point = new GeoPoint(cg.getLatE6(), cg.getLonE6()); return new CheckinGroupOverlayItem(point, cg, mContext, mRrm, mBmpPinSingle, mBmpPinMultiple); } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (mTapListener != null) { mTapListener.onTap(p, mapView); } return super.onTap(p, mapView); } @Override public boolean onTap(int i) { if (mTapListener != null) { mTapListener.onTap(getItem(i), mLastSelected, group.get(i)); } mLastSelected = getItem(i); return true; } @Override public void draw(android.graphics.Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, false); } private void constructScaledPinBackgrounds(Context context) { Drawable drwSingle = context.getResources().getDrawable(R.drawable.pin_checkin_single); Drawable drwMultiple = context.getResources().getDrawable(R.drawable.pin_checkin_multiple); drwSingle.setBounds(0, 0, drwSingle.getIntrinsicWidth(), drwSingle.getIntrinsicHeight()); drwMultiple.setBounds(0, 0, drwMultiple.getIntrinsicWidth(), drwMultiple.getIntrinsicHeight()); mBmpPinSingle = drawableToBitmap(drwSingle); mBmpPinMultiple = drawableToBitmap(drwMultiple); } private Bitmap drawableToBitmap(Drawable drw) { Bitmap bmp = Bitmap.createBitmap( drw.getIntrinsicWidth(), drw.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); drw.draw(canvas); return bmp; } private static int dddi(int dd, float screenDensity) { return (int)(dd * screenDensity + 0.5f); } public static class CheckinGroupOverlayItem extends OverlayItem { private CheckinGroup mCheckinGroup; public CheckinGroupOverlayItem(GeoPoint point, CheckinGroup cg, Context context, RemoteResourceManager rrm, Bitmap bmpPinSingle, Bitmap bmpPinMultiple) { super(point, cg.getVenue().getName(), cg.getVenue().getAddress()); mCheckinGroup = cg; constructPinDrawable(cg, context, rrm, bmpPinSingle, bmpPinMultiple); } public CheckinGroup getCheckin() { return mCheckinGroup; } private void constructPinDrawable(CheckinGroup cg, Context context, RemoteResourceManager rrm, Bitmap bmpPinSingle, Bitmap bmpPinMultiple) { // The mdpi size of the photo background is 52 x 58. // The user's photo should begin at origin (9, 12). // The user's photo should be 34 x 34. float screenDensity = context.getResources().getDisplayMetrics().density; int cx = dddi(52, screenDensity); int cy = dddi(58, screenDensity); int pox = dddi(9, screenDensity); int poy = dddi(12, screenDensity); int pcx = cx - (pox * 2); int pcy = cy - (poy * 2); Bitmap bmp = Bitmap.createBitmap(cx, cy, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); Paint paint = new Paint(); // Draw the correct background pin image. if (cg.getCheckinCount() < 2) { canvas.drawBitmap(bmpPinSingle, new Rect(0, 0, bmpPinSingle.getWidth(), bmpPinSingle.getHeight()), new Rect(0, 0, cx, cy), paint); } else { canvas.drawBitmap(bmpPinMultiple, new Rect(0, 0, bmpPinMultiple.getWidth(), bmpPinMultiple.getHeight()), new Rect(0, 0, cx, cy), paint); } // Put the user's photo on top. Uri photoUri = Uri.parse(cg.getPhotoUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri)); canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(pox, poy, pox + pcx, poy + pcy), paint); } catch (IOException e) { // If the user's photo isn't already in the cache, don't try loading it, // use a default user pin. Drawable drw2 = null; if (Foursquare.MALE.equals(cg.getGender())) { drw2 = context.getResources().getDrawable(R.drawable.blank_boy); } else { drw2 = context.getResources().getDrawable(R.drawable.blank_girl); } drw2.draw(canvas); } Drawable bd = new BitmapDrawable(bmp); bd.setBounds(-cx / 2, -cy, cx / 2, 0); setMarker(bd); } } public interface CheckinGroupOverlayTapListener { public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, CheckinGroup cg); public void onTap(GeoPoint p, MapView mapView); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.maps; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.FoursquaredSettings; import android.graphics.drawable.Drawable; import android.util.Log; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract class BaseGroupItemizedOverlay<T extends FoursquareType> extends ItemizedOverlay<OverlayItem> { public static final String TAG = "BaseGroupItemizedOverlay"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; Group<T> group = null; public BaseGroupItemizedOverlay(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); } @Override public int size() { if (group == null) { return 0; } return group.size(); } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (DEBUG) Log.d(TAG, "onTap: " + group.getType() + " " + p); return super.onTap(p, mapView); } @Override protected boolean onTap(int i) { if (DEBUG) Log.d(TAG, "onTap: " + group.getType() + " " + i); return super.onTap(i); } public void setGroup(Group<T> g) { assert g.getType() != null; group = g; super.populate(); } }
Java