Guest User

Untitled

a guest
Feb 1st, 2016
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.69 KB | None | 0 0
  1. public static final List<String> mPermissions = new ArrayList<String>() {
  2. {
  3. add("public_profile");
  4. add("email");
  5. add("gender");
  6. add("user_birthday");
  7. }};
  8.  
  9.  
  10.  
  11. @Override
  12. protected void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.activity_login);
  15.  
  16. //set and transition to signup page
  17. mSignUpTextView = (TextView)findViewById(R.id.signupText);
  18. mSignUpTextView.setOnClickListener(new View.OnClickListener() {
  19. @Override
  20. public void onClick(View v) {
  21. Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
  22. startActivity(intent);
  23. }
  24. });
  25.  
  26. //set and transition to reset password page
  27. mResetPasswordText = (TextView)findViewById(R.id.login_ForgotPasswordText);
  28. mResetPasswordText.setOnClickListener(new View.OnClickListener() {
  29. @Override
  30. public void onClick(View v) {
  31. Intent intent = new Intent(LoginActivity.this, ResetPasswordActivity.class);
  32. startActivity(intent);
  33. }
  34. });
  35.  
  36. //set and handle all login tasks
  37. mUsername = (EditText)findViewById(R.id.usernameField);
  38. mPassword = (EditText)findViewById(R.id.passwordField);
  39. mLoginButton = (Button)findViewById(R.id.loginButton);
  40.  
  41. //Facebook login
  42. loginButton = (LoginButton) findViewById(R.id.login_button);
  43. loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
  44.  
  45. callbackManager = CallbackManager.Factory.create();
  46.  
  47.  
  48. mFbProfile = Profile.getCurrentProfile();
  49. Log.d("Login FB", String.valueOf(mFbProfile));
  50.  
  51.  
  52. // Other app specific specialization
  53.  
  54. // Callback registration
  55. loginButton.setOnClickListener(new View.OnClickListener() {
  56. @Override
  57. public void onClick(View v) {
  58.  
  59. ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginActivity.this, mPermissions, new LogInCallback() {
  60. @Override
  61. public void done(ParseUser user, ParseException err) {
  62.  
  63. if (user == null) {
  64. Log.d("Login", "Uh oh. The user cancelled the Facebook login.");
  65. if (err != null) {
  66. Log.d("ParseFacebookLogin", "Error: " + err.getLocalizedMessage());
  67. }
  68. }
  69. else if (user.isNew()) {
  70. Log.d("Login", "User signed up and logged in through Facebook!");
  71. getUserDetailsFromFB();
  72.  
  73. //success
  74. FlokkApp.updateParseInstallation(user);
  75.  
  76. Intent intent = new Intent(LoginActivity.this, MainActivity.class);
  77. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  78. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  79. startActivity(intent);
  80.  
  81. Log.d("Login FB", "User logged in through Facebook!");
  82.  
  83. }
  84. else {
  85. Log.d("Login", "User logged in through Facebook!");
  86. getUserDetailsFromParse();
  87.  
  88. //success
  89. FlokkApp.updateParseInstallation(user);
  90.  
  91. Intent intent = new Intent(LoginActivity.this, MainActivity.class);
  92. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  93. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  94. startActivity(intent);
  95. }
  96. }
  97. });
  98.  
  99. }
  100. });
  101.  
  102.  
  103.  
  104.  
  105.  
  106. //Regular Parse Login ----------------------------------------------------------
  107. mLoginButton.setOnClickListener(new View.OnClickListener() {
  108. @Override
  109. public void onClick(View v) {
  110.  
  111. String username = mUsername.getText().toString();
  112. String password = mPassword.getText().toString();
  113.  
  114. username = username.trim();
  115. password = password.trim();
  116.  
  117. //noinspection StatementWithEmptyBody
  118. if (username.isEmpty() || password.isEmpty()){
  119. // display message if field is blank
  120. AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
  121. builder.setMessage(R.string.login_error_message)
  122. .setTitle(R.string.login_error_title)
  123. .setPositiveButton(android.R.string.ok, null);
  124. AlertDialog dialog = builder.create();
  125. dialog.show();
  126. }
  127. else {
  128. // login user
  129. ParseUser.logInInBackground(username, password, new LogInCallback() {
  130. public void done(ParseUser user, ParseException e) {
  131. if (user != null) {
  132. //success
  133. FlokkApp.updateParseInstallation(user);
  134.  
  135. Intent intent = new Intent(LoginActivity.this, MainActivity.class);
  136. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  137. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  138. startActivity(intent);
  139. //Toast.makeText(LoginActivity.this, "Successful Login", Toast.LENGTH_SHORT).show();
  140. }
  141. else {
  142. AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
  143. builder.setMessage(e.getMessage())
  144. .setTitle(R.string.login_error_title)
  145. .setPositiveButton(android.R.string.ok, null);
  146. AlertDialog dialog = builder.create();
  147. dialog.show();
  148. }
  149. }
  150. });
  151. }
  152.  
  153. }
  154. });
  155. }
  156.  
  157. //Facebook login required below ------------------------------------
  158. @Override
  159. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  160. Log.d("Login", "on activity result");
  161.  
  162. super.onActivityResult(requestCode, resultCode, data);
  163. ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
  164. }
  165.  
  166. //Facebook save new user code -----------------------------------------------
  167. private void saveNewUser() {
  168. Log.d("Login", "Save new user");
  169.  
  170.  
  171. parseUser = ParseUser.getCurrentUser();
  172. parseUser.setUsername(name);
  173. parseUser.setEmail(email);
  174.  
  175. //will need to update once I figure out how facebook sends the data
  176. boolean genderValue;
  177.  
  178. if (gender == "Male") {
  179. genderValue = true;
  180. } else {
  181. genderValue = false;
  182. };
  183. parseUser.put(ParseConstants.KEY_GENDERMALE, genderValue);
  184.  
  185. String searchtext = name.toLowerCase().trim();
  186. parseUser.put(ParseConstants.KEY_SEARCHTEXT, searchtext);
  187.  
  188.  
  189. //Saving profile photo as a ParseFile
  190. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  191. Bitmap bitmap = null; //((BitmapDrawable) mProfileImage.getDrawable()).getBitmap();
  192.  
  193. if (bitmap != null) {
  194. bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
  195. byte[] data = stream.toByteArray();
  196. String thumbName = parseUser.getUsername().replaceAll("\s+", "");
  197. final ParseFile parseFile = new ParseFile(thumbName + "_android_FBLogin.jpg", data);
  198.  
  199. parseFile.saveInBackground(new SaveCallback() {
  200. @Override
  201. public void done(ParseException e) {
  202. parseUser.put(ParseConstants.KEY_PROFILEPIC, parseFile);
  203.  
  204. //Finally save all the user details
  205. parseUser.saveInBackground(new SaveCallback() {
  206. @Override
  207. public void done(ParseException e) {
  208. Toast.makeText(LoginActivity.this, "New user:" + name + " Signed up", Toast.LENGTH_SHORT).show();
  209. }
  210. });
  211.  
  212. }
  213. });
  214. }
  215.  
  216. }
  217.  
  218. private void getUserDetailsFromFB() {
  219. Log.d("Login", "getUserDetails From FB");
  220.  
  221. // Suggested by https://disqus.com/by/dominiquecanlas/
  222. Bundle parameters = new Bundle();
  223. parameters.putString("fields", "email,name,gender,picture");
  224.  
  225.  
  226. new GraphRequest(
  227. AccessToken.getCurrentAccessToken(),
  228. "/me",
  229. parameters,
  230. HttpMethod.GET,
  231. new GraphRequest.Callback() {
  232. public void onCompleted(GraphResponse response) {
  233. /* handle the result */
  234. try {
  235.  
  236. Log.d("Response", response.getRawResponse());
  237.  
  238. email = response.getJSONObject().getString("email");
  239. //mEmailID.setText(email);
  240.  
  241. name = response.getJSONObject().getString("name");
  242. mUsername.setText(name);
  243.  
  244. gender = response.getJSONObject().getString("gender");
  245.  
  246. JSONObject picture = response.getJSONObject().getJSONObject("picture");
  247. JSONObject data = picture.getJSONObject("data");
  248.  
  249. // Returns a 50x50 profile picture
  250. String pictureUrl = data.getString("url");
  251.  
  252. Log.d("Profile pic", "url: " + pictureUrl);
  253.  
  254. new ProfilePhotoAsync(pictureUrl).execute();
  255.  
  256. } catch (JSONException e) {
  257. e.printStackTrace();
  258. }
  259. }
  260. }
  261. ).executeAsync();
  262.  
  263. }
  264.  
  265. private void getUserDetailsFromParse() {
  266. Log.d(" Login", "getUserDetails From parse");
  267.  
  268. parseUser = ParseUser.getCurrentUser();
  269.  
  270. //Fetch profile photo
  271. try {
  272. ParseFile parseFile = parseUser.getParseFile(ParseConstants.KEY_PROFILEPIC);
  273. byte[] data = parseFile.getData();
  274. Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
  275. //mProfileImage.setImageBitmap(bitmap);
  276.  
  277. } catch (Exception e) {
  278. e.printStackTrace();
  279. }
  280.  
  281. //mEmailID.setText(parseUser.getEmail());
  282. mUsername.setText(parseUser.getUsername());
  283.  
  284. //Toast.makeText(LoginActivity.this, "Welcome back " + mUsername.getText().toString(), Toast.LENGTH_SHORT).show();
  285.  
  286. }
  287.  
  288. public boolean onCreateOptionsMenu(Menu menu) {
  289. // Inflate the menu; this adds items to the action bar if it is present.
  290. getMenuInflater().inflate(R.menu.menu_login, menu);
  291. return true;
  292. }
  293.  
  294. public boolean onOptionsItemSelected(MenuItem item) {
  295. // Handle action bar item clicks here. The action bar will
  296. // automatically handle clicks on the Home/Up button, so long
  297. // as you specify a parent activity in AndroidManifest.xml.
  298. int id = item.getItemId();
  299.  
  300. //noinspection SimplifiableIfStatement
  301. if (id == R.id.action_settings) {
  302. return true;
  303. }
  304.  
  305. return super.onOptionsItemSelected(item);
  306. }
  307.  
  308.  
  309. //Required for facebook
  310. class ProfilePhotoAsync extends AsyncTask<String, String, String> {
  311. public Bitmap bitmap;
  312. String url;
  313.  
  314. public ProfilePhotoAsync(String url) {
  315. this.url = url;
  316. }
  317.  
  318. @Override
  319. protected String doInBackground(String... params) {
  320. // Fetching data from URI and storing in bitmap
  321. bitmap = DownloadImageBitmap(url);
  322. return null;
  323. }
  324.  
  325. @Override
  326. protected void onPostExecute(String s) {
  327. super.onPostExecute(s);
  328. //mProfileImage.setImageBitmap(bitmap);
  329.  
  330. saveNewUser();
  331. }
  332. }
  333.  
  334. public static Bitmap DownloadImageBitmap(String url) {
  335. Bitmap bm = null;
  336. try {
  337. URL aURL = new URL(url);
  338. URLConnection conn = aURL.openConnection();
  339. conn.connect();
  340. InputStream is = conn.getInputStream();
  341. BufferedInputStream bis = new BufferedInputStream(is);
  342. bm = BitmapFactory.decodeStream(bis);
  343. bis.close();
  344. is.close();
  345. } catch (IOException e) {
  346. Log.e("IMAGE", "Error getting bitmap", e);
  347. }
  348. return bm;
  349. }
  350.  
  351. @Override
  352. protected void onCreate(Bundle savedInstanceState) {
  353. super.onCreate(savedInstanceState);
  354. setContentView(R.layout.activity_main);
  355. ParseAnalytics.trackAppOpened(getIntent());
  356.  
  357. ParseUser currentUser = ParseUser.getCurrentUser();
  358. if (currentUser == null) {
  359. navigateToLogin();
  360. Log.d("Login Check", String.valueOf(ParseUser.getCurrentUser()));
  361.  
  362. }
  363. else {
  364. }
  365.  
  366. toolbar = (Toolbar) findViewById(R.id.app_bar);
  367. setSupportActionBar(toolbar);
  368.  
  369. mPager = (ViewPager) findViewById(R.id.pager);
  370. mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
  371. mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
  372. mTabs.setDistributeEvenly(true);
  373. mTabs.setViewPager(mPager);
  374.  
  375.  
  376.  
  377. try {
  378. PackageInfo info = getPackageManager().getPackageInfo(
  379. "com.myflokk.testflokkd",
  380. PackageManager.GET_SIGNATURES);
  381. for (Signature signature : info.signatures) {
  382. MessageDigest md = MessageDigest.getInstance("SHA");
  383. md.update(signature.toByteArray());
  384. Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
  385. }
  386. } catch (PackageManager.NameNotFoundException e) {
  387.  
  388. } catch (NoSuchAlgorithmException e) {
  389.  
  390. }
  391.  
  392.  
  393. }
  394.  
  395. //included onResume as a part of facebook integration
  396. @Override
  397. protected void onResume() {
  398. super.onResume();
  399.  
  400. // Logs 'install' and 'app activate' App Events.
  401. AppEventsLogger.activateApp(this);
  402. }
  403.  
  404. //included onPause as a part of facebook integration
  405. @Override
  406. protected void onPause() {
  407. super.onPause();
  408.  
  409. // Logs 'app deactivate' App Event.
  410. AppEventsLogger.deactivateApp(this);
  411. }
  412.  
  413.  
  414.  
  415. private void navigateToLogin() {
  416. Intent intent = new Intent(MainActivity.this, LoginActivity.class);
  417. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  418. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  419. startActivity(intent);
  420. }
  421.  
  422.  
  423. @Override
  424. public boolean onCreateOptionsMenu(Menu menu) {
  425. // Inflate the menu; this adds items to the action bar if it is present.
  426. getMenuInflater().inflate(R.menu.menu_main, menu);
  427. return true;
  428. }
  429.  
  430. @Override
  431. public boolean onOptionsItemSelected(MenuItem item) {
  432. // Handle action bar item clicks here. The action bar will automatically handle clicks on the Home/Up button, so long as you specify a parent activity in AndroidManifest.xml.
  433. int id = item.getItemId();
  434.  
  435. //noinspection SimplifiableIfStatement
  436.  
  437. switch (id) {
  438.  
  439. case R.id.addEvent:
  440. startActivity(new Intent(this, AddEventActivity.class));
  441. break;
  442.  
  443. case R.id.editProfile:
  444. startActivity(new Intent(this, UserProfileEditActivity.class));
  445. break;
  446.  
  447. case R.id.action_logout:
  448. ParseUser.logOut();
  449. navigateToLogin();
  450. break;
  451.  
  452.  
  453. }
  454. return super.onOptionsItemSelected(item);
  455. }
  456.  
  457. @Override
  458. public void onStart() {
  459. super.onStart();
  460.  
  461. ParseUser currentUser = ParseUser.getCurrentUser();
  462. if (currentUser == null) {
  463. navigateToLogin();
  464. Log.d("Login Check 2", String.valueOf(ParseUser.getCurrentUser()));
  465.  
  466. }
  467. else {
  468. }
  469.  
  470. // ATTENTION: This was auto-generated to implement the App Indexing API.
  471. // See https://g.co/AppIndexing/AndroidStudio for more information.
  472. client.connect();
  473. Action viewAction = Action.newAction(
  474. Action.TYPE_VIEW, // TODO: choose an action type.
  475. "Main Page", // TODO: Define a title for the content shown.
  476. // TODO: If you have web page content that matches this app activity's content,
  477. // make sure this auto-generated web page URL is correct.
  478. // Otherwise, set the URL to null.
  479. Uri.parse("http://host/path"),
  480. // TODO: Make sure this auto-generated app deep link URI is correct.
  481. Uri.parse("android-app://com.myflokk.testflokkd/http/host/path")
  482. );
  483. AppIndex.AppIndexApi.start(client, viewAction);
  484. }
  485.  
  486. @Override
  487. public void onStop() {
  488. super.onStop();
  489.  
  490. // ATTENTION: This was auto-generated to implement the App Indexing API.
  491. // See https://g.co/AppIndexing/AndroidStudio for more information.
  492. Action viewAction = Action.newAction(
  493. Action.TYPE_VIEW, // TODO: choose an action type.
  494. "Main Page", // TODO: Define a title for the content shown.
  495. // TODO: If you have web page content that matches this app activity's content,
  496. // make sure this auto-generated web page URL is correct.
  497. // Otherwise, set the URL to null.
  498. Uri.parse("http://host/path"),
  499. // TODO: Make sure this auto-generated app deep link URI is correct.
  500. Uri.parse("android-app://com.myflokk.testflokkd/http/host/path")
  501. );
  502. AppIndex.AppIndexApi.end(client, viewAction);
  503. client.disconnect();
  504. }
  505.  
  506.  
  507. class MyPagerAdapter extends FragmentPagerAdapter {
  508. String[] tabs;
  509.  
  510. public MyPagerAdapter(FragmentManager fm) {
  511. super(fm);
  512. tabs = getResources().getStringArray(R.array.tabs);
  513. }
  514.  
  515. @Override
  516. public Fragment getItem(int position) {
  517.  
  518. switch (position) {
  519. case 0:
  520. return new UserEventListFragment();
  521. case 1:
  522. return new UserSearchFragment();
  523. case 2:
  524. return new UserProfileActivityFragment();
  525. }
  526. return null;
  527. }
  528.  
  529. @Override
  530. public CharSequence getPageTitle(int position) {
  531. return tabs[position];
  532. }
  533.  
  534. @Override
  535. public int getCount() {
  536. return 3;
  537. }
  538. }
  539.  
  540. protected Context mContext;
  541. protected List<ParseObject> mEvents;
  542. private SimpleDateFormat mFormat = new SimpleDateFormat("E, MMM d", Locale.US);
  543. protected Date mDate;
  544. protected List<Object> mLikeList = new ArrayList<>();
  545. protected int mLikes = 0;
  546. protected String Flokking = "I am flokking to this event!";
  547.  
  548. public EventAdapter(Context context, List<ParseObject> events) {
  549. super(context, R.layout.row_event_list, events);
  550. mContext = context;
  551. mEvents = events;
  552. }
  553.  
  554. @Override
  555. public View getView(final int position, View convertView, ViewGroup parent) {
  556. final ViewHolder holder;
  557.  
  558. if (convertView == null) {
  559.  
  560. convertView = LayoutInflater.from(mContext).inflate(R.layout.row_event_list, null);
  561. holder = new ViewHolder();
  562. holder.eventName = (TextView) convertView.findViewById(R.id.eventRow_TextEventName);
  563. holder.eventLocation = (TextView) convertView.findViewById(R.id.eventRow_TextEventLocation);
  564. holder.eventImage = (ImageView) convertView.findViewById(R.id.eventRow_EventImage);
  565. holder.eventDate = (TextView) convertView.findViewById(R.id.eventRow_Date);
  566. holder.eventNotLiked = (ImageView) convertView.findViewById(R.id.eventRow_ImageNotLiked);
  567. holder.eventLiked = (ImageView) convertView.findViewById(R.id.eventRow_ImageLiked);
  568. holder.eventFlokkingCount = (TextView) convertView.findViewById(R.id.eventRow_FlokkingCount);
  569.  
  570. convertView.setTag(holder);
  571. } else {
  572. holder = (ViewHolder) convertView.getTag();
  573. }
  574.  
  575.  
  576. ParseObject event = mEvents.get(position);
  577. ParseObject details = mEvents.get(position);
  578. final String currentEvent = details.getObjectId();
  579.  
  580. //Log.d("EventAdapter", "This is the position --> " + position);
  581.  
  582. holder.eventName.setText(event.getString(ParseConstants.KEY_EVENTNAME));
  583. holder.eventLocation.setText(event.getString(ParseConstants.KEY_EVENTVENUE));
  584. holder.eventFlokkingCount.setText(event.getNumber(ParseConstants.EVENT_LIKECOUNT).toString());
  585.  
  586. //get the date and assign to mDate and then change the way the date is displayed
  587. mDate = event.getDate(ParseConstants.KEY_EVENTDATE);
  588. holder.eventDate.setText(mFormat.format(mDate));
  589.  
  590.  
  591. mLikeList = event.getList(ParseConstants.EVENT_LIKES);
  592. Log.d("Login Event Check", String.valueOf(ParseUser.getCurrentUser()));
  593.  
  594. if (mLikeList == null || mLikeList.isEmpty()) {
  595. //this is false and the user has not liked the event
  596. holder.eventLiked.setVisibility(View.INVISIBLE);
  597. holder.eventNotLiked.setVisibility(View.VISIBLE);
  598. }
  599.  
  600. else {
  601. //if there are users in the list check for the current user
  602.  
  603. if (mLikeList.contains(ParseUser.getCurrentUser().getObjectId())) {
  604. // true
  605. holder.eventLiked.setVisibility(View.VISIBLE);
  606. holder.eventNotLiked.setVisibility(View.INVISIBLE);
  607. }
  608. else {
  609. holder.eventLiked.setVisibility(View.INVISIBLE);
  610. holder.eventNotLiked.setVisibility(View.VISIBLE);
  611. }
  612. }
  613.  
  614. 02-01 19:05:28.800 E/AndroidRuntime: FATAL EXCEPTION: main
  615. Process: com.myflokk.testflokkd, PID: 1933
  616. java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.parse.ParseUser.getObjectId()' on a null object reference
  617. at com.myflokk.testflokkd.Adapters.EventAdapter.getView(EventAdapter.java:98)
Add Comment
Please, Sign In to add comment