Back to project page groceryviewer.
The source code is released under:
GNU General Public License
If you think the Android project groceryviewer listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.github.knrajago.groceryviewer; //from w w w. j a va 2 s . co m import static com.github.knrajago.groceryviewer.constants.GroceryViewerConstants.APPLICATION_TAG; import static com.github.knrajago.groceryviewer.constants.GroceryViewerConstants.AUTHORITIES_STRING; import static com.github.knrajago.groceryviewer.constants.GroceryViewerConstants.COL_SELECTION; import static com.github.knrajago.groceryviewer.constants.GroceryViewerConstants.CONTENT_PROVIDER_URI; import static com.github.knrajago.groceryviewer.constants.GroceryViewerConstants.MAX_NUM_OF_AUTH; import static com.github.knrajago.groceryviewer.constants.GroceryViewerConstants.SPREADSHEET_SCOPE; import static com.github.knrajago.groceryviewer.constants.GroceryViewerConstants.TABLE_NAME; import static com.github.knrajago.groceryviewer.constants.GroceryViewerConstants.TOKEN_KEY; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Set; import javax.net.ssl.HttpsURLConnection; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.Window; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Toast; import com.github.knrajago.groceryviewer.listadapters.GroceryListAdapter; import com.github.knrajago.groceryviewer.localdb.GroceryListHelper; import com.github.knrajago.groceryviewer.utils.GroceryViewerUtils; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.services.drive.DriveScopes; public class GroceryViewerActivity extends Activity { private String mToken = null; private Account mAccount = null; private SQLiteDatabase mDatabse = null; private Cursor mCursor = null; private GroceryViewerObserver mObserver = null; private GroceryListAdapter mAdapter = null; private GoogleAccountCredential mCredential = null; private static final int USER_CONFIGURED = 1; private static final int USER_AUTHORIZES = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_grocery_viewer); mDatabse = new GroceryListHelper(getApplicationContext()).getReadableDatabase(); mCursor = mDatabse.query(TABLE_NAME, COL_SELECTION, null, null, null, null, null); mAdapter = new GroceryListAdapter(this.getBaseContext(), mCursor, true); ListView groceryList = (ListView) findViewById(R.id.grocery_lst); groceryList.setAdapter(mAdapter); this.mObserver = new GroceryViewerObserver(new Handler()); getContentResolver().registerContentObserver(Uri.parse(CONTENT_PROVIDER_URI), true, this.mObserver); final ImageButton refreshBtn = (ImageButton) findViewById(R.id.refresh_btn); final ImageButton settingBtn = (ImageButton) findViewById(R.id.settings_btn); // Refresh handler refreshBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mAccount == null) { String userName = GroceryViewerUtils.getUserName(getApplicationContext()); String accType = GroceryViewerUtils.getAccountType(getApplicationContext()); if (userName == null || accType == null) { mAccount = new Account(userName, accType); } else { ArrayList<String> credList = new ArrayList<String>(1); credList.add(DriveScopes.DRIVE); mCredential = GoogleAccountCredential.usingOAuth2(GroceryViewerActivity.this, credList); startActivityForResult(mCredential.newChooseAccountIntent(), USER_CONFIGURED); } } else { getValidatedToken(mAccount.name); } } }); // Settings handler settingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ArrayList<String> credList = new ArrayList<String>(1); credList.add(DriveScopes.DRIVE); mCredential = GoogleAccountCredential.usingOAuth2(GroceryViewerActivity.this, credList); startActivityForResult(mCredential.newChooseAccountIntent(), USER_CONFIGURED); } }); } @Override protected void onStart() { super.onStart(); String methodName = "onStart()"; Log.i(APPLICATION_TAG, methodName + " entering"); if (GroceryViewerUtils.isUserNotSetup(this.getApplicationContext())) { ArrayList<String> credList = new ArrayList<String>(1); credList.add(DriveScopes.DRIVE); mCredential = GoogleAccountCredential.usingOAuth2(GroceryViewerActivity.this, credList); startActivityForResult(mCredential.newChooseAccountIntent(), USER_CONFIGURED); } if (GroceryViewerUtils.isUserNotSetup(this.getApplicationContext())) { String userName = GroceryViewerUtils.getUserName(this.getApplicationContext()); String accType = GroceryViewerUtils.getAccountType(this.getApplicationContext()); Log.i(APPLICATION_TAG, methodName + " User: " + userName + " Account: " + accType); if (userName != null && accType != null) { mAccount = new Account(userName, accType); getValidatedToken(userName); } Log.i(APPLICATION_TAG, methodName + " user setup"); } else { Log.i(APPLICATION_TAG, methodName + " user not setup"); } Log.i(APPLICATION_TAG, methodName + " exiting"); } private void showAccountPicker() { ArrayList<String> credList = new ArrayList<String>(1); credList.add(DriveScopes.DRIVE); mCredential = GoogleAccountCredential.usingOAuth2(GroceryViewerActivity.this, credList); startActivityForResult(mCredential.newChooseAccountIntent(), USER_CONFIGURED); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String methodName = "onActivityResult() "; super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case USER_CONFIGURED: if (resultCode == RESULT_OK && data != null && data.getExtras() != null) { String userName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); String accountType = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE); Log.i(APPLICATION_TAG, methodName + " User: " + userName + " account: " + accountType); if (userName == null && accountType == null) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.user_acc_not_config), Toast.LENGTH_SHORT).show(); } else { mAccount = new Account (userName, accountType); getValidatedToken(userName); } } break; case USER_AUTHORIZES: if (resultCode == RESULT_OK && data != null && data.getExtras() != null) { Bundle extras = data.getExtras(); Set<String> keySet = extras.keySet(); for (String oneKey : keySet) { Log.i(APPLICATION_TAG, "Key: " + oneKey + " value: " + extras.getString(oneKey)); } Log.i(APPLICATION_TAG, "after request sync"); if (mAccount != null) { getValidatedToken(mAccount.name); } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.grocery_viewer, menu); return true; } @Override protected void onDestroy() { super.onDestroy(); getContentResolver().unregisterContentObserver(this.mObserver); if (this.mCursor != null && !this.mCursor.isClosed()) { this.mCursor.close(); } if (this.mDatabse != null && this.mDatabse.isOpen()) { this.mDatabse.close(); } } private void getValidatedToken(String pAccountName) { AsyncTask<String, Void, String> getTokenTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { String accountName = params[0]; //String token = null; int numOfTimes = 0; numOfTimes ++; try { do { try { mToken = GoogleAuthUtil.getToken(GroceryViewerActivity.this.getApplicationContext(), accountName, SPREADSHEET_SCOPE); } catch (UserRecoverableAuthException e) { startActivityForResult(e.getIntent(), USER_AUTHORIZES); numOfTimes = MAX_NUM_OF_AUTH; // Set it to max number so it exists out of while loop. This function - getValidatedToken() // will be called again from onActivityResult() } catch (IOException e) { e.printStackTrace(); } catch (GoogleAuthException e) { e.printStackTrace(); } } while(!validateToken(mToken) && numOfTimes < MAX_NUM_OF_AUTH); } catch (IOException e) { Log.e(APPLICATION_TAG, "Error while validating token: ", e); } return mToken; } @Override protected void onPostExecute(String pResult) { ContentResolver.setSyncAutomatically(mAccount, AUTHORITIES_STRING, true); if (mAccount != null) { ContentResolver.setIsSyncable(mAccount, AUTHORITIES_STRING, 1); } else { Log.i(APPLICATION_TAG, "mAccount is null"); } Bundle settingsBundle = new Bundle(); settingsBundle.putBoolean( ContentResolver.SYNC_EXTRAS_MANUAL, true); settingsBundle.putString(TOKEN_KEY, pResult); ContentResolver.requestSync(mAccount, AUTHORITIES_STRING, settingsBundle); } }; getTokenTask.execute(pAccountName); } private boolean validateToken(String pToken) throws IOException { URL url = new URL("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + pToken); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); int sc = con.getResponseCode(); boolean returnValue = false; if (sc == 200) { returnValue = true; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(this, pToken); returnValue = false; showValidationToast(); } else { showValidationToast(); returnValue = false; } return returnValue; } private void showValidationToast() { this.runOnUiThread(new Runnable() { public void run() { Toast.makeText(GroceryViewerActivity.this, getResources().getString(R.string.validation_error), Toast.LENGTH_SHORT).show(); } }); } public class GroceryViewerObserver extends ContentObserver { public GroceryViewerObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); mCursor.close(); Cursor newCursor = mDatabse.query(TABLE_NAME, COL_SELECTION, null, null, null, null, null); mAdapter.changeCursor(newCursor); } } }