2015-11-16 55 views
1

Splash.JavagetCurrentUser不會空,即使我退出使用解析SDK

import android.content.Intent; 
import android.os.Handler; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 

import com.parse.Parse; 
import com.parse.ParseUser; 

public class Splash extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_splash); 
     new Handler().postDelayed(new Runnable() { 

      @Override 
      public void run() { 
       final ParseUser user = ParseUser.getCurrentUser(); 
       if (user != null) { 
        // Start an intent for the logged in activity 
        startActivity(new Intent(Splash.this, MainActivity.class)); 
       } else { 
        // Start and intent for the logged out activity 
        startActivity(new Intent(Splash.this, LoginActivity.class)); 
       } 
      } 
     }, 3000); 
    } 

} 

LoginActivity.java

import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.Bundle; 
import android.provider.ContactsContract; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.parse.LogInCallback; 
import com.parse.ParseException; 
import com.parse.ParseUser; 

import butterknife.ButterKnife; 
import butterknife.InjectView; 

public class LoginActivity extends AppCompatActivity { 
    private static final String TAG = "LoginActivity"; 
    private static final int REQUEST_SIGNUP = 0; 

    @InjectView(R.id.input_username) 
    EditText _usernameText; 
    @InjectView(R.id.input_password) 
    EditText _passwordText; 
    @InjectView(R.id.btn_login) 
    Button _loginButton; 
    @InjectView(R.id.link_signup) 
    TextView _signInLink; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
     ButterKnife.inject(this); 


     _loginButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       login(); 
      } 
     }); 

     _signInLink.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // Start the Signup activity 
       Intent intent = new Intent(LoginActivity.this, SignupActivity.class); 
       startActivity(intent); 
      } 
     }); 
    } 

    public void login() { 
     Log.d(TAG, "Login"); 

     if (!validate()) { 
      onLoginFailed(); 
      return; 
     } 

     _loginButton.setEnabled(false); 

     final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this, 
       R.style.AppTheme_Dark_Dialog); 
     progressDialog.setIndeterminate(true); 
//  progressDialog.setMessage("Authenticating..."); 
     progressDialog.show(); 
     new android.os.Handler().postDelayed(
       new Runnable() { 
        public void run() { 
         onLoginSuccess(); 
         progressDialog.dismiss(); 
        } 
       }, 3000); 
    } 

    void onLoginSuccess() { 

     // TODO: Authentication Source 

     ParseUser.logInInBackground(_usernameText.getText().toString(), 
       _passwordText.getText().toString(), new LogInCallback() { 
        @Override 
        public void done(ParseUser parseUser, ParseException e) { 
         if (parseUser != null) { 
          moveTaskToBack(false); 
          Toast.makeText(LoginActivity.this, "Logged in Successfully!!", Toast.LENGTH_SHORT).show(); 
          Intent intent = new Intent(LoginActivity.this, MainActivity.class); 
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | 
            Intent.FLAG_ACTIVITY_NEW_TASK); 
          startActivity(intent); 
         } else { 

          Toast.makeText(LoginActivity.this, "\n Enter correct user credentials.", 
            Toast.LENGTH_LONG).show(); 
          _loginButton.setEnabled(true); 
         } 
        } 
       }); 
    } 


    void onLoginFailed() { 
     _passwordText.getText().clear(); 
     _usernameText.getText().clear(); 
     Toast.makeText(LoginActivity.this, "Login Failed!!", Toast.LENGTH_SHORT).show(); 
    } 

    public boolean validate() { 
     boolean valid = true; 

     String username = _usernameText.getText().toString(); 
     String password = _passwordText.getText().toString(); 

     if (username.isEmpty()) { 
      _usernameText.setError("enter a valid username"); 
      Toast.makeText(LoginActivity.this, "Enter a valid username!", Toast.LENGTH_SHORT).show(); 
      valid = false; 

     } else { 
      _usernameText.setError(null); 
     } 

     if (password.isEmpty() || password.length() < 4 || password.length() > 10) { 
      _passwordText.setError("between 4 and 10 alphanumeric characters"); 
      Toast.makeText(LoginActivity.this, "Enter a valid Password!", Toast.LENGTH_SHORT).show(); 
      valid = false; 
     } else { 
      _passwordText.setError(null); 
     } 

     return valid; 
    } 
} 

MainActivity.java

import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.support.design.widget.NavigationView; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.Button; 
import android.widget.Toast; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 
import com.parse.ParseUser; 


public class MainActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback { 
    Button button_offer_ride; 
    Button button_find_ride; 
    private GoogleMap mMap; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     //map start 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 
     //map stop 

     button_find_ride=(Button) findViewById(R.id.btn_findride); 
     button_offer_ride=(Button) findViewById(R.id.btn_offerride); 

     String user=ParseUser.getCurrentUser().getUsername(); 
     Toast.makeText(MainActivity.this, user, Toast.LENGTH_SHORT).show(); 

     button_find_ride.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent inten_onClick_findride=new Intent(MainActivity.this,FindActivity.class); 
       startActivity(inten_onClick_findride); 
      } 
     }); 

     button_offer_ride.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent inten_onClick_Offerride=new Intent(MainActivity.this,OfferActivity.class); 
       startActivity(inten_onClick_Offerride); 
      } 
     }); 


     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 

     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 

    } 

    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    @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 boolean onOptionsItemSelected(MenuItem item) { 
     // 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. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     if(id == R.id.action_logout){ 

      ParseUser.logOut(); 
      Intent intent = new Intent(MainActivity.this, LoginActivity.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); 
      startActivity(intent); 
      Toast.makeText(MainActivity.this, "Logged out successfully", Toast.LENGTH_SHORT).show(); 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     // Handle navigation view item clicks here. 
     int id = item.getItemId(); 

     if (id == R.id.nav_camara) { 
      Toast.makeText(MainActivity.this, "Profile page will created soon..", Toast.LENGTH_SHORT).show(); 
     } else if (id == R.id.nav_gallery) { 
      Toast.makeText(MainActivity.this, "Offer Ride page", Toast.LENGTH_SHORT).show(); 
      Intent intent= new Intent(MainActivity.this,OfferActivity.class); 
      startActivity(intent); 

     } else if (id == R.id.nav_slideshow) { 

      Toast.makeText(MainActivity.this, "Find Ride page", Toast.LENGTH_SHORT).show(); 
      Intent intent= new Intent(MainActivity.this,FindActivity.class); 
      startActivity(intent); 

     } else if (id == R.id.nav_manage) { 
      Toast.makeText(MainActivity.this, "Tool Page will created Soon", Toast.LENGTH_SHORT).show(); 
     } else if (id == R.id.nav_share) { 

      Toast.makeText(MainActivity.this, "Share page will created Soon..", Toast.LENGTH_SHORT).show(); 

     } else if (id == R.id.nav_send) { 

      Toast.makeText(MainActivity.this, "Send page will created Soon...", Toast.LENGTH_SHORT).show(); 

     } 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     // Add a marker in Jaipur and move the camera 
     LatLng jaipur = new LatLng(26, 75.80); 
     LatLng bikaner= new LatLng(28.0167, 73.3119); 
     LatLng bangalore=new LatLng(12.9667, 77.5667); 
     LatLng delhi=new LatLng(28.6100, 77.2300); 
     mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); 
     mMap.setMyLocationEnabled(true); 
     mMap.addMarker(new MarkerOptions().position(jaipur).title("Cars available in Jaipur")) 
       .setIcon(BitmapDescriptorFactory.fromResource(R.drawable.caricon)); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(jaipur)); 
     mMap.addMarker(new MarkerOptions().position(bikaner).title("Cars available in Bikaner")) 
       .setIcon(BitmapDescriptorFactory.fromResource(R.drawable.caricon)); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(bikaner)); 
     mMap.addMarker(new MarkerOptions().position(bangalore).title("Cars available in Bangalore")) 
       .setIcon(BitmapDescriptorFactory.fromResource(R.drawable.caricon)); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(bangalore)); 
     mMap.addMarker(new MarkerOptions().position(delhi).title("Cars available in Delhi")) 
       .setIcon(BitmapDescriptorFactory.fromResource(R.drawable.caricon)); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(delhi)); 

    } 
} 

註冊活動

import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.parse.ParseException; 
import com.parse.ParseUser; 
import com.parse.SignUpCallback; 

import butterknife.ButterKnife; 
import butterknife.InjectView; 

public class SignupActivity extends AppCompatActivity { 
    private static final String TAG = "SignupActivity"; 

    @InjectView(R.id.input_name) 
    EditText _nameText; 
    @InjectView(R.id.input_email) EditText _emailText; 
    @InjectView(R.id.input_password) EditText _passwordText; 
    @InjectView(R.id.input_repassword) EditText _passwordAgainText; 
    @InjectView(R.id.input_mobile) EditText _mobileText; 
    @InjectView(R.id.btn_signup) 
    Button _signupButton; 
    @InjectView(R.id.link_login) 
    TextView _loginLink; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_signup); 
     ButterKnife.inject(this); 

     _signupButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       signup(); 
      } 
     }); 

     _loginLink.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // Finish the registration screen and return to the Login activity 
       finish(); 
      } 
     }); 
    } 

    public void signup() { 
     Log.d(TAG, "Signup"); 

     if (!validate()) { 
      onSignupFailed(); 
      return; 
     } 
     else { 
      _signupButton.setEnabled(false); 

      final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this, 
        R.style.AppTheme_Dark_Dialog); 
      progressDialog.setIndeterminate(true); 
//   progressDialog.setMessage("Creating Account..."); 
      progressDialog.show(); 

      new android.os.Handler().postDelayed(
        new Runnable() { 
         public void run() { 
          onSignupSuccess(); 
          progressDialog.dismiss(); 
         } 
        }, 3000); 
     } 
    } 


    public void onSignupSuccess() { 
     _signupButton.setEnabled(true); 
     setResult(RESULT_OK, null); 
     //code for succefully signed up 
     ParseUser user =new ParseUser(); 
     user.setUsername(_nameText.getText().toString()); 
     user.setEmail(_emailText.getText().toString()); 
     user.setPassword(_passwordText.getText().toString()); 


     user.signUpInBackground(new SignUpCallback() { 
      @Override 
      public void done(ParseException e) { 
       if (e != null) { 
        // Show the error message 
        Toast.makeText(SignupActivity.this, e.getMessage(), 
          Toast.LENGTH_LONG).show(); 
       } else { 
        // Start an intent for the dispatch activity 
        Intent intent = new Intent(SignupActivity.this, MainActivity.class); 
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | 
          Intent.FLAG_ACTIVITY_NEW_TASK); 
        startActivity(intent); 
       } 
      } 
     }); 
    } 

    public void onSignupFailed() { 
     Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show(); 
     _signupButton.setEnabled(true); 

    } 

    public boolean validate() { 
     boolean valid = true; 

     String name = _nameText.getText().toString(); 
     String email = _emailText.getText().toString(); 
     String password = _passwordText.getText().toString(); 
     String password_again= _passwordAgainText.getText().toString(); 
     String mobile=_mobileText.getText().toString(); 


     if (name.isEmpty() || name.length() < 3) { 
      _nameText.setError("at least 3 characters"); 
      valid = false; 
     } else { 
      _nameText.setError(null); 
     } 

     if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { 
      _emailText.setError("enter a valid email address"); 
      valid = false; 
     } else { 
      _emailText.setError(null); 
     } 

     if (password.isEmpty() || password.length() < 4 || password.length() > 10) { 
      _passwordText.setError("between 4 and 10 alphanumeric characters"); 
      valid = false; 
     } else { 
      _passwordText.setError(null); 
     } 


     if (name.isEmpty() || name.length() < 3) { 
      _nameText.setError("at least 3 characters"); 
      valid = false; 
     } else { 
      _passwordAgainText.setError(null); 
     } 

     if (!password.equals(password_again)){ 
      _passwordAgainText.setError("Password Do not match"); 
      valid = false; 
     } 
     else { 
      _passwordAgainText.setError(null); 
     } 

     if (mobile.isEmpty() || mobile.length() < 10 || mobile.length() >10) { 
      _mobileText.setError("Enter correct Mobile No."); 
      valid = false; 
     } 
     else { 
      _mobileText.setError(null); 
     } 
     return valid; 

    } 
} 

ParseApplication.java

import android.app.Application; 

import com.parse.Parse; 
import com.parse.ParseACL; 
import com.parse.ParseUser; 

public class ParseApplication extends Application { 
    @Override 
    public void onCreate() { 
     super.onCreate(); 

     // Enable Local Datastore. 
     Parse.enableLocalDatastore(this); 

     Parse.initialize(this, "key", "key"); 
     ParseUser.enableRevocableSessionInBackground(); 

     ParseUser.enableAutomaticUser(); 
     ParseACL defaultACL = new ParseACL(); 

     // If you would like all objects to be private by default, remove this 
     // line. 
     defaultACL.setPublicReadAccess(true); 

     ParseACL.setDefaultACL(defaultACL, true); 
    } 
} 

清單文件

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.developer.akshay.youmego" > 

    <!-- To auto-complete the email text field in the login form with the user's emails --> 
    <uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
    <uses-permission android:name="android.permission.READ_PROFILE" /> 
    <uses-permission android:name="android.permission.READ_CONTACTS" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 


    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 


    <application 
     android:name=".ParseApplication" 
     android:allowBackup="true" 
     android:icon="@drawable/logo_main" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme.NoActionBar" > 
     <meta-data 
      android:name="com.google.android.geo.API_KEY" 
      android:value="@string/google_maps_key" /> 
     <activity 
      android:name=".Splash" 
      android:label="@string/app_name" 
      android:theme="@style/AppTheme.NoActionBar" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.VIEW" /> 
      </intent-filter> 
     </activity> 
     <activity android:name=".MapsActivity"/> 
     <activity android:name=".SignupActivity" 
      android:theme="@style/AppTheme"/> 
     <activity android:name=".LoginActivity" 
      android:theme="@style/AppTheme"> 
     </activity> 
     <activity android:name=".OfferActivity" 
      android:theme="@style/AppTheme"> 
     </activity> 
     <activity android:name=".FindActivity" 
      android:theme="@style/AppTheme"> 
     </activity> 

    </application> 

</manifest> 
  1. 當運行該應用程序。 MainActivity.java打開即使我從用戶註銷。
  2. 我想讓應用程序也用電子郵件ID登錄。
  3. 如何檢索當前用戶詳細信息。像用戶名和全部。
  4. 註冊頁面:可以創建相同的手機號碼。如何解決它?
+0

你在哪裏初始化解析? –

+0

你可以請你的應用程序類的解析初始化? (不要在發佈方法調用時包含你的私鑰) – galvan

回答

0

根據您的登錄和註冊活動之外,你還可以使用解析會話管理只需使用SharedPrefences ..

0

我不知道第一個問題的解決方案,因爲即使我沒有得到它的工作。其中一個解決方法是在用戶登錄時將用戶信息臨時存儲在共享首選項中,並在用戶註銷應用程序時將其清除。

private void setUserPreferences(String username){ 
     SharedPreferences sharedPreferences=getSharedPreferences("DEFAULT_SP", Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor=sharedPreferences.edit(); 
     editor.putString("username", username); 
     editor.commit(); 
    } 

    private String getUserPreferences(){ 
     SharedPreferences sharedPreferences=getSharedPreferences("DEFAULT_SP", Context.MODE_PRIVATE); 
     return sharedPreferences.getString("username", null); 
    } 

    private void clearUserPreferences(){ 
     SharedPreferences sharedPreferences=getSharedPreferences("DEFAULT_SP", Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor=sharedPreferences.edit(); 
     editor.clear(); 
     editor.commit(); 
    } 

現在,您可以在登錄到應用程序並註銷應用程序時調用這些功能。不是一個可行的解決方案,但它是我目前所擁有的。

此外,您不能在解析中使用email-id登錄,您將需要用戶名。因此,您可以做的是找到與該電子郵件關聯的用戶名,然後使用該用戶名登錄解析。

private String mUsername=null; 
private void getParseUsername(String email){ 
    ParseQuery<ParseObject> query = ParseQuery.getQuery("User"); 
    query.whereEqualTo("email", email); 
    query.findInBackground(new FindCallback<ParseObject>() { 
     public void done(List<ParseObject> parseList, ParseException e) { 
      if (e == null) { 
       //assuming you don't have same email id's in the parse database 
       //, I don't think that's even allowed. 
       mUsername = parseList.get(0).getString(""); 
      } else { 
       Log.d("parseList", "Error: " + e.getMessage()); 
      } 
     } 
    }); 
} 

用於獲取用戶信息,你可以簡單地輸入此代碼:

ParseUser.getCurrentUser().getUsername() 

對於第四個問題,如果我理解正確的話,你不希望用戶用手機號碼註冊,其已經註冊。

private boolean mDuplicatePhoneNo=false; 
private void isPhoneNumberDuplicate(String phoneNo) 
    ParseQuery<ParseObject> query = ParseQuery.getQuery("User"); 
    //Here phone_no is the field name in which you have stored your phone numbers 
    //Make sure they are in string format. 
    query.whereEqualTo("phone_no", phone); 
    query.findInBackground(new FindCallback<ParseObject>() { 
     public void done(List<ParseObject> parseList, ParseException e) { 
      if (e == null) { 
       if(phoneNo.equals(parseList.get(0).getString("phone_no"))){ 
        mDuplicatePhoneNo=true; 
       } 
      } else { 
       Log.d("parseList", "Error: " + e.getMessage()); 
      } 
     } 
}); 

同時確保訪問https://parse.com/docs/android/guide#getting-started 一個更好的指導。

相關問題