2016-12-01 79 views
0

我有一個php服務器用戶名(jonik)和密碼a(123456)作爲登錄名。我試圖用我的應用程序進行改進登錄,但它總是失敗的方法。如果連接發生,服務器必須響應「成功」,所以我不知道我在做什麼錯 - 是否在我的代碼中?爲什麼在此代碼中翻新失敗?

mainactivity

public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    String myLoginEmailAddress = getLoginEmailAddress(); 
    TextView loginInformation = (TextView)findViewById(R.id.login_email); 
    if(myLoginEmailAddress != null || !myLoginEmailAddress.equals("")){ 
     loginInformation.setText("Welcome!!! You have logged in as " + myLoginEmailAddress); 
    }else { 
     loginInformation.setText("Your login email is missing"); 
    } 
} 

private String getLoginEmailAddress(){ 
    String storedEmail = ""; 
    Intent mIntent = getIntent(); 
    Bundle mBundle = mIntent.getExtras(); 
    if(mBundle != null){ 
     storedEmail = mBundle.getString("EMAIL"); 
    } 
    return storedEmail; 
    } 
} 

loginactivity

public class LoginActivity extends AppCompatActivity { 

private final String TAG = "LoginActivity"; 

public static final String BASE_URL = "http://555.555.555.555"; 

// UI references. 
private AutoCompleteTextView mEmailView; 
private EditText mPasswordView; 
private View mProgressView; 
private View mLoginFormView; 
private TextView failedLoginMessage; 

View focusView = null; 
private String username; 
private String password; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_login); 
    // Set up the login form. 
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email); 
    populateAutoComplete(); 

    failedLoginMessage = (TextView)findViewById(R.id.failed_login); 

    mPasswordView = (EditText) findViewById(R.id.password); 
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { 
     @Override 
     public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { 
      if (id == R.id.login || id == EditorInfo.IME_NULL) { 
       attemptLogin(); 
       return true; 
      } 
      return false; 
     } 
    }); 

    Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); 
    mEmailSignInButton.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      failedLoginMessage.setText(""); 
      attemptLogin(); 
     } 
    }); 


    mLoginFormView = findViewById(R.id.login_form); 
    mProgressView = findViewById(R.id.login_progress); 
} 

private void attemptRegistration(){ 
    boolean mCancel = this.loginValidation(); 
    if (mCancel) { 
     focusView.requestFocus(); 
    } else { 
     registrationProcessWithRetrofit(username, password); 
    } 
} 

private void attemptLogin(){ 
    boolean mCancel = this.loginValidation(); 
    if (mCancel) { 
     focusView.requestFocus(); 
    } else { 
     loginProcessWithRetrofit(username, password); 
    } 
} 

private boolean loginValidation() { 
    // Reset errors. 
    mEmailView.setError(null); 
    mPasswordView.setError(null); 

    // Store values at the time of the login attempt. 
    username = mEmailView.getText().toString(); 
    password = mPasswordView.getText().toString(); 

    boolean cancel = false; 

    // Check for a valid password, if the user entered one. 
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { 
     mPasswordView.setError(getString(R.string.error_invalid_password)); 
     focusView = mPasswordView; 
     cancel = true; 
    } 

    // Check for a valid username address. 
    if (TextUtils.isEmpty(username)) { 
     mEmailView.setError(getString(R.string.error_field_required)); 
     focusView = mEmailView; 
     cancel = true; 
    } /*else if (!isEmailValid(username)) { 
     mEmailView.setError(getString(R.string.error_invalid_email)); 
     focusView = mEmailView; 
     cancel = true; 
    }*/ 
    return cancel; 
} 

private void populateAutoComplete(){ 
    String[] countries = getResources().getStringArray(R.array.autocomplete); 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,countries); 
    mEmailView.setAdapter(adapter); 
} 



private boolean isPasswordValid(String password) { 
    //TODO: Replace this with your own logic 
    return password.length() > 4; 
} 

/** 
* Shows the progress UI and hides the login form. 
*/ 
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) 
private void showProgress(final boolean show) { 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { 
     int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); 

     mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); 
     mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() { 
      @Override 
      public void onAnimationEnd(Animator animation) { 
       mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); 
      } 
     }); 

     mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); 
     mProgressView.animate().setDuration(shortAnimTime).alpha(
       show ? 1 : 0).setListener(new AnimatorListenerAdapter() { 
      @Override 
      public void onAnimationEnd(Animator animation) { 
       mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); 
      } 
     }); 
    } else { 
     mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); 
     mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); 
    } 
} 

private ApiInterface getInterfaceService() { 

    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(BASE_URL) 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 

    final ApiInterface mInterfaceService = retrofit.create(ApiInterface.class); 
    return mInterfaceService; 
} 

private void loginProcessWithRetrofit(final String username, String password){ 

    ApiInterface mApiService = this.getInterfaceService(); 
    Call<Login> mService = mApiService.authenticate(username, password); 
    mService.enqueue(new Callback<Login>() { 
     @Override 
     public void onResponse(Call<Login> call, Response<Login> response) { 

      Login mLoginObject = response.body(); 
      String returnedResponse = mLoginObject.isLogin; 
      Toast.makeText(LoginActivity.this, "Returned " + returnedResponse, Toast.LENGTH_LONG).show(); 

      //showProgress(false); 
      if(returnedResponse.trim().equals("success")){ 
       // redirect to Main Activity page 
       Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class); 
       loginIntent.putExtra("EMAIL", username); 
       startActivity(loginIntent); 
      } 
      if(returnedResponse.trim().equals("error")){ 
       // use the registration button to register 
       failedLoginMessage.setText(getResources().getString(R.string.registration_message)); 
       mPasswordView.requestFocus(); 
      } 
     } 

     @Override 
     public void onFailure(Call<Login> call, Throwable t) { 
      call.cancel(); 
      Toast.makeText(LoginActivity.this, "Please check your network connection and internet permission", Toast.LENGTH_LONG).show(); 
     } 
    }); 
} 

登錄

public class Login { 
public String isLogin; 
      } 

ApiInterface

public interface ApiInterface { 
    @FormUrlEncoded 
@POST("/cult_tickets/request/login.php") 
Call<Login> authenticate(@Field("username") String username, @Field("password") String password); 

編輯 我得到這個日誌,但仍然在登錄活動進入故障

D/CustomLogRetrofit: <-- 200 OK  http://555.555.555.555/cult_tickets/request/login.php (298ms) 
    D/CustomLogRetrofit: Date: Fri, 02 Dec 2016 05:27:47 GMT 
    D/CustomLogRetrofit: Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.6.24 
    D/CustomLogRetrofit: X-Powered-By: PHP/5.6.24 
    D/CustomLogRetrofit: Content-Length: 7 
    D/CustomLogRetrofit: Keep-Alive: timeout=5, max=100 
    D/CustomLogRetrofit: Connection: Keep-Alive 
    D/CustomLogRetrofit: Content-Type: text/html; charset=UTF-8 
    D/CustomLogRetrofit: success 
    D/CustomLogRetrofit: <-- END HTTP (7-byte body) 
+0

你的throwable在onF中說什麼ailure? –

+0

我得到這個土司「請檢查您的網絡連接和網絡許可 – EasyE

+0

當然,我寫在清單 – EasyE

回答

0

執行下列步驟menifeist文件

第1步 - 檢查許可

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

步驟2-檢查代理服務器設置(如果您的網絡中有代理服務器)用於檢查此https://stackoverflow.com/a/18443524/4741746

步驟3-嘗試查看從郵遞員響應或RESTClient實現是API正常工作

步驟4 - 變化公共靜態最終字符串BASE_URL = 「http://555.555.555.555」;您一部開拓創新的IP編輯部地址或本地主機

告訴我們您的清單文件

+0

1檢查 2-沒有代理問題 3,它是工作在郵遞員 4 - 當然,我改變了我的IP – EasyE

0

,這就是你的答案:)你的java對象不是可轉換到服務器響應。 Basicly您登錄的對象是不是從服務器回來

添加http洛攔截你的改造,你會本身的答覆:)

private ApiInterface getInterfaceService() { 
     HttpLoggingInterceptor.Logger myLogger = new HttpLoggingInterceptor.Logger() { 
     @Override 
     public void log(String message) { 
      Log.d("CustomLogRetrofit", message); 
     } 
    }; 
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(myLogger); 
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); 
    OkHttpClient client = new OkHttpClient.Builder() 
         .addInterceptor(loggingInterceptor) 
         .build(); 



    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(BASE_URL) 
      .client(client) 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 

    final ApiInterface mInterfaceService = retrofit.create(ApiInterface.class); 
    return mInterfaceService; 
} 

編輯: 這是因爲你的服務器沒有返回JSON對象。 「成功」只是一個字符串。你可以改變你的服務器返回類似{"isLogin"="success"}或使用@Rainmaker溶液(使用RespondBody)

+0

對不起你需要添加到搖籃編譯「com.squareup.okhttp3:logging-interceptor:3.2.0」 –

+0

消息 - > Log.d(「CustomLogRetrofit」,消息);這個錯誤呢?我確實添加了它 – EasyE

+0

我已經改變了它。這是lamda expresion。看看sushant gosavi響應,並改變BASE_URL以及 –

0

嘗試

Call<JsonObject> authenticate(@Field("username") String username, @Field("password") String password); 

如果你會得到的JSONObject

Call<ResponseBody> authenticate(@Field("username") String username, @Field("password") String password); 

如果你會得到字符串

+0

如果我這樣做,我會改變我的整個登錄方法 – EasyE

+0

否則你的服務器應該返回你的Android應用程序預期的確切對象。 – Rainmaker

+0

是的,我希望服務器像他們建造 我與新代碼@wojciech_maciejewski把它給我,但在Android Studio中沒有輸入登錄方法內 – EasyE