Não consigo logar no app | Fórum | School of Net

Deseja poder participar de nosso fórum e tirar todas as suas dúvidas?
Clique aqui e assine nosso plano de acesso ilimitado. Saiba mais.

por Leandro

10 meses atrás Leandro

Não consigo logar no app

Quando entro com um usuário e senha inválidos e aplicativo, corretamente, informa "Invalid Credentials". Porém quando entro com login e senha válidos ele dá erro e fecha o aplicativo. Imagem do erro: http://prntscr.com/nhm1we Como posso resolver isso? Debugando eu vi que ele recupera o token e retorna true na função "doInBackground" em "LoginActivity.java". Meu LoginActivity.java: ``` package club.andorinhas.app.activities; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.content.Intent; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v4.app.LoaderManager; import android.support.v7.app.AppCompatActivity; import android.app.LoaderManager.LoaderCallbacks; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.HttpResponse; import cz.msebera.android.httpclient.client.HttpClient; import cz.msebera.android.httpclient.client.methods.HttpPost; import cz.msebera.android.httpclient.entity.StringEntity; import cz.msebera.android.httpclient.impl.client.HttpClientBuilder; import cz.msebera.android.httpclient.util.EntityUtils; import static android.Manifest.permission.READ_CONTACTS; import club.andorinhas.app.R; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { /** * Id to identity READ_CONTACTS permission request. */ private static final int REQUEST_READ_CONTACTS = 0; /** * Keep track of the login task to ensure we can cancel it if requested. */ private UserLoginTask mAuthTask = null; // UI references. private EditText mUserName; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Set up the login form. mUserName = (EditText) findViewById(R.id.txtUserName); mPasswordView = (EditText) findViewById(R.id.txtPassword); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.btnLogin || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); Button btnLogin = (Button) findViewById(R.id.btnLogin); btnLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); } private void populateAutoComplete() { if (!mayRequestContacts()) { return; } } private boolean mayRequestContacts() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { return true; } if (shouldShowRequestPermissionRationale(READ_CONTACTS)) { Snackbar.make(mUserName, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(android.R.string.ok, new View.OnClickListener() { @Override @TargetApi(Build.VERSION_CODES.M) public void onClick(View v) { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } }); } else { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } return false; } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { populateAutoComplete(); } } } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ private void attemptLogin() { if (mAuthTask != null) { return; } // Reset errors. mUserName.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. String name = mUserName.getText().toString(); String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; // 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 user name. if (TextUtils.isEmpty(name)) { mUserName.setError(getString(R.string.error_field_required)); focusView = mUserName; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true); mAuthTask = new UserLoginTask(name, password); mAuthTask.execute((Void) null); } } 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) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. 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 { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } private interface ProfileQuery { String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY, }; int ADDRESS = 0; int IS_PRIMARY = 1; } /** * Represents an asynchronous login/registration task used to authenticate * the user. */ public class UserLoginTask extends AsyncTask<Void, Void, Boolean> { private final String mUserName; private final String mPassword; private HttpClient httpClient = HttpClientBuilder.create().build(); UserLoginTask(String name, String password) { mUserName = name; mPassword = password; } @Override protected Boolean doInBackground(Void... params) { HttpPost clientPost = new HttpPost("http://192.168.0.46:8000/api/v1/login"); JSONObject jsonObject = new JSONObject(); Boolean returnValue = false; try { jsonObject.put("name", mUserName); jsonObject.put("password", mPassword); } catch (JSONException e) { e.printStackTrace(); } clientPost.addHeader("Content-Type", "application/json"); StringEntity bodyRequest = null; Integer codeStatus = null; JSONObject result = null; try { bodyRequest = new StringEntity(jsonObject.toString()); clientPost.setEntity(bodyRequest); HttpResponse response = httpClient.execute(clientPost); String json = EntityUtils.toString(response.getEntity()); result = new JSONObject(json); codeStatus = response.getStatusLine().getStatusCode(); if (codeStatus != null && codeStatus != 401) { UserSession userSession = UserSession.getInstance(getApplicationContext()); userSession.setUser(result.getString("token")); returnValue = true; } if (codeStatus != null && codeStatus == 401) { returnValue = false; } } catch (IOException | JSONException e) { e.printStackTrace(); // return true; } return returnValue; } @Override protected void onPostExecute(final Boolean success) { mAuthTask = null; showProgress(false); if (success) { startActivity(new Intent(getApplicationContext(), MainActivity.class)); finish(); } else { Toast.makeText(LoginActivity.this, "Invalid Credentials", Toast.LENGTH_LONG).show(); } } @Override protected void onCancelled() { mAuthTask = null; showProgress(false); } } } ``` O erro foi esse: ``` I/Choreographer: Skipped 58 frames! The application may be doing too much work on its main thread. D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main Process: club.andorinhas.app, PID: 14245 java.lang.RuntimeException: Unable to start activity ComponentInfo{club.andorinhas.app/club.andorinhas.app.activities.MainActivity}: android.os.NetworkOnMainThreadException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273) at java.net.InetAddress.lookupHostByName(InetAddress.java:431) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) at java.net.InetAddress.getAllByName(InetAddress.java:215) at cz.msebera.android.httpclient.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45) at cz.msebera.android.httpclient.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:112) at cz.msebera.android.httpclient.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353) at cz.msebera.android.httpclient.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380) at cz.msebera.android.httpclient.impl.execchain.MainClientExec.execute(MainClientExec.java:236) at cz.msebera.android.httpclient.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) at cz.msebera.android.httpclient.impl.execchain.RetryExec.execute(RetryExec.java:88) at cz.msebera.android.httpclient.impl.execchain.RedirectExec.execute(RedirectExec.java:110) at cz.msebera.android.httpclient.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107) at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55) at club.andorinhas.app.activities.Categorias.findCategorias(Categorias.java:63) at club.andorinhas.app.activities.Categorias.onViewCreated(Categorias.java:52) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1471) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852) at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802) at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411) at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273) at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273) at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229) at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201) at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620) at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237) at android.app.Activity.performStart(Activity.java:6253) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  ```

3 Respostas