Guest User

Untitled

a guest
Jan 6th, 2018
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.15 KB | None | 0 0
  1. public class MainActivity extends AppCompatActivity {
  2.  
  3. Button btnSingIn,btnRegister;
  4. RelativeLayout rootLayout;
  5.  
  6. FirebaseAuth auth;
  7. FirebaseDatabase db;
  8. DatabaseReference users;
  9.  
  10. private final static int PERMISSION = 1000;
  11.  
  12. @Override
  13. protected void attachBaseContext(Context newBase) {
  14. super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
  15. }
  16.  
  17. @Override
  18. protected void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. //be4 set content view
  21. CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
  22. .setDefaultFontPath("fonts/MontserratAlternates-Regular.otf")
  23. .setFontAttrId(R.attr.fontPath)
  24. .build()
  25. );
  26. setContentView(R.layout.activity_main);
  27.  
  28. //init firebase
  29. auth = FirebaseAuth.getInstance();
  30. db = FirebaseDatabase.getInstance();
  31. users = db.getReference("Rider");
  32. rootLayout = (RelativeLayout)findViewById(R.id.rootLayout);
  33.  
  34. //init view
  35. btnRegister = (Button) findViewById(R.id.btnRegister);
  36. btnRegister.setOnClickListener(new View.OnClickListener() {
  37. @Override
  38. public void onClick(View v) {
  39. showRegisterDialog();
  40. }
  41. });
  42. btnSingIn = (Button)findViewById(R.id.btnSignin);
  43. btnSingIn.setOnClickListener(new View.OnClickListener() {
  44. @Override
  45. public void onClick(View v) {
  46. btnSingIn.setEnabled(false);
  47. showLoginDialog();
  48. }
  49. });
  50. }
  51.  
  52. private void showLoginDialog() {
  53. AlertDialog.Builder dialog = new AlertDialog.Builder(this);
  54. dialog.setTitle("SIGN IN ");
  55. dialog.setMessage("Please use email to sign in");
  56.  
  57. LayoutInflater inflater = LayoutInflater.from(this);
  58. View login_Layout = inflater.inflate(R.layout.layout_signin,null);
  59.  
  60. final MaterialEditText editEmail = login_Layout.findViewById(R.id.editEmail);
  61. final MaterialEditText editPassword = login_Layout.findViewById(R.id.editPassword);
  62.  
  63. dialog.setView(login_Layout);
  64.  
  65. //set button
  66. dialog.setPositiveButton("SIGN IN", new DialogInterface.OnClickListener() {
  67. @Override
  68. public void onClick(DialogInterface dialog, int which) {
  69.  
  70. dialog.dismiss();
  71.  
  72. //set disable button sign in if is progressing
  73. btnSingIn.setEnabled(false);
  74.  
  75.  
  76.  
  77. //check validation
  78. if (TextUtils.isEmpty(editEmail.getText().toString()))
  79. {
  80. Snackbar.make(rootLayout,"Please enter your email adress",Snackbar.LENGTH_SHORT)
  81. .show();
  82. return;
  83. }
  84.  
  85. if (TextUtils.isEmpty(editPassword.getText().toString()))
  86. {
  87. Snackbar.make(rootLayout,"Please enter your password",Snackbar.LENGTH_SHORT)
  88. .show();
  89. return;
  90. }
  91.  
  92. if (editPassword.getText().toString().length() < 6)
  93. {
  94. Snackbar.make(rootLayout,"Password too short !!!",Snackbar.LENGTH_SHORT)
  95. .show();
  96. return;
  97. }
  98.  
  99. final SpotsDialog waitingDialog = new SpotsDialog(MainActivity.this);
  100. waitingDialog.show();
  101.  
  102. //login
  103. auth.signInWithEmailAndPassword(editEmail.getText().toString(),editPassword.getText().toString())
  104. .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
  105. @Override
  106. public void onSuccess(AuthResult authResult) {
  107. waitingDialog.show();
  108. startActivity(new Intent(MainActivity.this,Home.class));
  109. finish();
  110. }
  111. }).addOnFailureListener(new OnFailureListener() {
  112. @Override
  113. public void onFailure(@NonNull Exception e) {
  114. waitingDialog.show();
  115. Snackbar.make(rootLayout,"Failed"+e.getMessage(),Snackbar.LENGTH_SHORT)
  116. .show();
  117.  
  118. //active button
  119. btnSingIn.setEnabled(true);
  120. }
  121. });
  122. }
  123.  
  124. });
  125.  
  126. dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
  127. @Override
  128. public void onClick(DialogInterface dialog, int which) {
  129. dialog.dismiss();
  130. }
  131. });
  132.  
  133.  
  134.  
  135.  
  136.  
  137. dialog.show();
  138. }
  139.  
  140. private void showRegisterDialog() {
  141. AlertDialog.Builder dialog = new AlertDialog.Builder(this);
  142. dialog.setTitle("REGISTER ");
  143. dialog.setMessage("Please use email to register");
  144.  
  145. LayoutInflater inflater = LayoutInflater.from(this);
  146. View register_Layout = inflater.inflate(R.layout.layout_register,null);
  147.  
  148. final MaterialEditText editEmail = register_Layout.findViewById(R.id.editEmail);
  149. final MaterialEditText editPassword = register_Layout.findViewById(R.id.editPassword);
  150. final MaterialEditText editName = register_Layout.findViewById(R.id.editName);
  151. final MaterialEditText editPhone = register_Layout.findViewById(R.id.editPhone);
  152.  
  153. dialog.setView(register_Layout);
  154.  
  155. //set button
  156. dialog.setPositiveButton("REGISTER", new DialogInterface.OnClickListener() {
  157. @Override
  158. public void onClick(DialogInterface dialog, int which) {
  159.  
  160. dialog.dismiss();
  161.  
  162. //check validation
  163. if (TextUtils.isEmpty(editEmail.getText().toString()))
  164. {
  165. Snackbar.make(rootLayout,"Please enter your email adresse",Snackbar.LENGTH_SHORT)
  166. .show();
  167. return;
  168. }
  169.  
  170. if (TextUtils.isEmpty(editPhone.getText().toString()))
  171. {
  172. Snackbar.make(rootLayout,"Please enter your phone number",Snackbar.LENGTH_SHORT)
  173. .show();
  174. return;
  175. }
  176.  
  177. if (TextUtils.isEmpty(editPassword.getText().toString()))
  178. {
  179. Snackbar.make(rootLayout,"Please enter your password",Snackbar.LENGTH_SHORT)
  180. .show();
  181. return;
  182. }
  183.  
  184. if (editPassword.getText().toString().length() < 6)
  185. {
  186. Snackbar.make(rootLayout,"Password too short !!!",Snackbar.LENGTH_SHORT)
  187. .show();
  188. return;
  189. }
  190.  
  191. //register new user
  192. auth.createUserWithEmailAndPassword(editEmail.getText().toString(),editPassword.getText().toString())
  193. .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
  194. @Override
  195. public void onSuccess(AuthResult authResult) {
  196. //save user to db
  197. Rider user = new Rider();
  198. user.setEmail(editEmail.getText().toString());
  199. user.setName(editName.getText().toString());
  200. user.setPhone(editPhone.getText().toString());
  201. user.setPassword(editPassword.getText().toString());
  202.  
  203. //user email to key
  204. users.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
  205. .setValue(user)
  206. .addOnSuccessListener(new OnSuccessListener<Void>() {
  207. @Override
  208. public void onSuccess(Void aVoid) {
  209. Snackbar.make(rootLayout,"Register success fully !!!",Snackbar.LENGTH_SHORT)
  210. .show();
  211. return;
  212. }
  213. })
  214. .addOnFailureListener(new OnFailureListener() {
  215. @Override
  216. public void onFailure(@NonNull Exception e) {
  217. Snackbar.make(rootLayout,"Faild !!!"+e.getMessage(),Snackbar.LENGTH_SHORT)
  218. .show();
  219. return;
  220. }
  221. });
  222. }
  223. })
  224. .addOnFailureListener(new OnFailureListener() {
  225. @Override
  226. public void onFailure(@NonNull Exception e) {
  227. Snackbar.make(rootLayout,"Faild !!!"+e.getMessage(),Snackbar.LENGTH_SHORT)
  228. .show();
  229. return;
  230. }
  231. });
  232. }
  233. });
  234.  
  235. dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
  236. @Override
  237. public void onClick(DialogInterface dialog, int which) {
  238. dialog.dismiss();
  239. }
  240. });
  241.  
  242. dialog.show();
  243.  
  244.  
  245. }
  246.  
  247. }
  248.  
  249. public class Home extends AppCompatActivity
  250. implements NavigationView.OnNavigationItemSelectedListener,
  251. OnMapReadyCallback,
  252. GoogleApiClient.ConnectionCallbacks,
  253. GoogleApiClient.OnConnectionFailedListener,
  254. LocationListener{
  255.  
  256. SupportMapFragment mapFragment;
  257.  
  258.  
  259. //location
  260. private GoogleMap mMap;
  261. private static final int MY_PERMISSION_REQUEST_CODE = 7000;
  262. private static final int PLAY_services_RES_REQUEST = 7001;
  263.  
  264. private LocationRequest mLocationRequest;
  265. private GoogleApiClient mGoogleApiClient;
  266. private Location mLastLocation;
  267.  
  268. private static int UPDATE_INTERVAL = 5000;
  269. private static int FASTEST_INTERVAL = 3000;
  270. private static int DISPLACEMENT = 10;
  271.  
  272. DatabaseReference drivers;
  273. GeoFire geoFire;
  274.  
  275. Marker mUserMarker;
  276.  
  277. @Override
  278. protected void onCreate(Bundle savedInstanceState) {
  279. super.onCreate(savedInstanceState);
  280. setContentView(R.layout.activity_home);
  281. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  282. setSupportActionBar(toolbar);
  283.  
  284.  
  285.  
  286. DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  287. ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
  288. this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
  289. drawer.addDrawerListener(toggle);
  290. toggle.syncState();
  291.  
  292. NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
  293. navigationView.setNavigationItemSelectedListener(this);
  294.  
  295. //maps
  296. mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  297. mapFragment.getMapAsync(this);
  298.  
  299. //geo fire
  300. drivers = FirebaseDatabase.getInstance().getReference("Drivers");
  301. geoFire = new GeoFire(drivers);
  302.  
  303. setUpLocation();
  304.  
  305. }
  306.  
  307. //ctr o
  308.  
  309.  
  310. @Override
  311. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  312. switch (requestCode)
  313. {
  314. case MY_PERMISSION_REQUEST_CODE:
  315. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);
  316. {
  317. if (checkPlayServices())
  318. {
  319. buildGoogleApiClient();
  320. createLocationRequest();
  321. displayLocation();
  322. }
  323. }
  324. break;
  325.  
  326. }
  327. }
  328.  
  329. private void setUpLocation() {
  330. if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
  331. ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED )
  332. {
  333. //request run time permission
  334. ActivityCompat.requestPermissions(this , new String[]{
  335. android.Manifest.permission.ACCESS_COARSE_LOCATION,
  336. android.Manifest.permission.ACCESS_FINE_LOCATION,
  337.  
  338. },MY_PERMISSION_REQUEST_CODE);
  339. }
  340. else
  341. {
  342. if (checkPlayServices())
  343. {
  344. buildGoogleApiClient();
  345. createLocationRequest();
  346. displayLocation();
  347. }
  348. }
  349. }
  350.  
  351. private void displayLocation() {
  352. if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) !=PackageManager.PERMISSION_GRANTED &&
  353. ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED )
  354. {
  355. return;
  356. }
  357. mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
  358. if (mLastLocation != null)
  359. {
  360. final double latitude = mLastLocation.getLatitude();
  361. final double longitude = mLastLocation.getLongitude();
  362.  
  363. //update to firebase
  364. geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
  365. @Override
  366. public void onComplete(String key, DatabaseError error) {
  367. //add maker
  368. if (mUserMarker != null)
  369. mUserMarker.remove(); // remove alredy maker
  370. mUserMarker = mMap.addMarker(new MarkerOptions()
  371. .position(new LatLng(latitude,longitude))
  372. .title("Here You are"));
  373. //move camera to this position
  374. mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
  375.  
  376. }
  377. });
  378.  
  379. }
  380. else
  381. {
  382. Log.d("ERROR","Cannot get your location");
  383. }
  384. }
  385.  
  386. private void createLocationRequest() {
  387. mLocationRequest = new LocationRequest();
  388. mLocationRequest.setInterval(UPDATE_INTERVAL);
  389. mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
  390. mLocationRequest.setPriority(mLocationRequest.PRIORITY_HIGH_ACCURACY);
  391. mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
  392. }
  393.  
  394. private void buildGoogleApiClient() {
  395. mGoogleApiClient = new GoogleApiClient.Builder(this)
  396. .addConnectionCallbacks(this)
  397. .addOnConnectionFailedListener(this)
  398. .addApi(LocationServices.API)
  399. .build();
  400. mGoogleApiClient.connect();
  401. }
  402.  
  403. private boolean checkPlayServices() {
  404. int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
  405. if (resultCode != ConnectionResult.SUCCESS)
  406. {
  407. if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
  408. GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_services_RES_REQUEST).show();
  409. else {
  410. Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
  411. finish();
  412. }
  413. return false;
  414. }
  415. return true;
  416. }
  417.  
  418. @Override
  419. public void onBackPressed() {
  420. DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  421. if (drawer.isDrawerOpen(GravityCompat.START)) {
  422. drawer.closeDrawer(GravityCompat.START);
  423. } else {
  424. super.onBackPressed();
  425. }
  426. }
  427.  
  428. @Override
  429. public boolean onCreateOptionsMenu(Menu menu) {
  430. // Inflate the menu; this adds items to the action bar if it is present.
  431. getMenuInflater().inflate(R.menu.home, menu);
  432. return true;
  433. }
  434.  
  435. @Override
  436. public boolean onOptionsItemSelected(MenuItem item) {
  437. // Handle action bar item clicks here. The action bar will
  438. // automatically handle clicks on the Home/Up button, so long
  439. // as you specify a parent activity in AndroidManifest.xml.
  440. int id = item.getItemId();
  441.  
  442. //noinspection SimplifiableIfStatement
  443. if (id == R.id.action_settings) {
  444. return true;
  445. }
  446.  
  447. return super.onOptionsItemSelected(item);
  448. }
  449.  
  450. @SuppressWarnings("StatementWithEmptyBody")
  451. @Override
  452. public boolean onNavigationItemSelected(MenuItem item) {
  453. // Handle navigation view item clicks here.
  454. int id = item.getItemId();
  455.  
  456. if (id == R.id.nav_camera) {
  457. // Handle the camera action
  458. } else if (id == R.id.nav_gallery) {
  459.  
  460. } else if (id == R.id.nav_slideshow) {
  461.  
  462. } else if (id == R.id.nav_manage) {
  463.  
  464. } else if (id == R.id.nav_share) {
  465.  
  466. } else if (id == R.id.nav_send) {
  467.  
  468. }
  469.  
  470. DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
  471. drawer.closeDrawer(GravityCompat.START);
  472. return true;
  473. }
  474.  
  475. @Override
  476. public void onMapReady(GoogleMap googleMap) {
  477.  
  478. mMap = googleMap;
  479. }
  480.  
  481. @Override
  482. public void onConnected(@Nullable Bundle bundle) {
  483. displayLocation();
  484. startLocationUpdates();
  485. }
  486.  
  487. private void startLocationUpdates() {
  488. if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=PackageManager.PERMISSION_GRANTED &&
  489. ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=PackageManager.PERMISSION_GRANTED )
  490. {
  491. return;
  492. }
  493. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest, (com.google.android.gms.location.LocationListener) this);
  494.  
  495. }
  496.  
  497. @Override
  498. public void onConnectionSuspended(int i) {
  499. mGoogleApiClient.connect();
  500.  
  501.  
  502. }
  503.  
  504. @Override
  505. public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  506.  
  507. }
  508.  
  509. @Override
  510. public void onLocationChanged(Location location) {
  511. mLastLocation = location;
  512. displayLocation();
  513. }
  514. }
  515.  
  516. E/AndroidRuntime: FATAL EXCEPTION: main
  517. Process: com.logo.tm.androidriderapp, PID: 16166
  518. java.lang.RuntimeException: Unable to start activity ComponentInfo{com.logo.tm.androidriderapp/com.logo.tm.androidriderapp.Home}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
  519. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
  520. at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595)
  521. at android.app.ActivityThread.access$800(ActivityThread.java:178)
  522. at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
  523. at android.os.Handler.dispatchMessage(Handler.java:111)
  524. at android.os.Looper.loop(Looper.java:194)
  525. at android.app.ActivityThread.main(ActivityThread.java:5631)
  526. at java.lang.reflect.Method.invoke(Native Method)
  527. at java.lang.reflect.Method.invoke(Method.java:372)
  528. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
  529. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
  530. Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
  531. at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:715)
  532. at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
  533. at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
  534. at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
  535. at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
  536. at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
  537. at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
  538. at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
  539. at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
  540. at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
  541. at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
  542. at com.logo.tm.androidriderapp.Home.onCreate(Home.java:76)
  543. at android.app.Activity.performCreate(Activity.java:6092)
  544. at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
  545. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
  546. at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595) 
  547. at android.app.ActivityThread.access$800(ActivityThread.java:178) 
  548. at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
  549. at android.os.Handler.dispatchMessage(Handler.java:111) 
  550. at android.os.Looper.loop(Looper.java:194) 
  551. at android.app.ActivityThread.main(ActivityThread.java:5631) 
  552. at java.lang.reflect.Method.invoke(Native Method) 
  553. at java.lang.reflect.Method.invoke(Method.java:372) 
  554. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) 
  555. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) 
Add Comment
Please, Sign In to add comment