我一直在用户的身份验证工作很长一段时间,但每次运行我的应用程序时都会出现此错误:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.g11.colinaapp, PID: 9752
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.SecurityException: Permission Denial: opening provider
com.android.providers.contacts.ContactsProvider2 from
ProcessRecord{26a3953 9752:com.g11.colinaapp/u0a72} (pid=9752,
uid=10072) requires android.permission.READ_CONTACTS or
android.permission.WRITE_CONTACTS
at android.os.Parcel.readException(Parcel.java:1599)
at android.os.Parcel.readException(Parcel.java:1552)
at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:3550)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:4778)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2018)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1468)
at android.content.ContentResolver.query(ContentResolver.java:475)
at android.content.CursorLoader.loadInBackground(CursorLoader.java:64)
at android.content.CursorLoader.loadInBackground(CursorLoader.java:56)
at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
这是我的代码。而且我知道我必须将HttpClient
更改为HttpUrlConnection
,但我不知道我和我一直在寻找很长时间。
有人可以帮助我吗?
提前致谢
package com.g11.colinaapp;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
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 org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.auth.AUTH;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
public class Login extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world"
};
private static final String AUTH_ENDPOINT = "https://colinaapp.com/api/v1/authenticate/";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmail;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
public static String userToken = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//
final EditText etUser = (EditText) findViewById(R.id.email);
final EditText etPass = (EditText) findViewById(R.id.password);
final TextView tvLog = (TextView) findViewById(R.id.email_sign_in_button);
final TextView tvOlvide = (TextView) findViewById(R.id.tvOlvide);
//recuperar contraseña
tvOlvide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent olvidoIntent = new Intent(Login.this, Olvide.class);
Login.this.startActivity(olvidoIntent);
}
});
// Set up the login form.
mEmail = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
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;
}
});
TextView mUsernameSignInButton = (TextView) findViewById(R.id.email_sign_in_button);
mUsernameSignInButton.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() {
getLoaderManager().initLoader(0, null, this);
}
/**
* 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.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmail.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String username = mEmail.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 email address.
if (TextUtils.isEmpty(username)) {
mEmail.setError(getString(R.string.error_field_required));
focusView = mEmail;
cancel = true;
} else if (!isUsernameValid(username)) {
mEmail.setError(getString(R.string.error_invalid_email));
focusView = mEmail;
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(username, password);
mAuthTask.execute((String) null);
}
}
private boolean isUsernameValid(String username) {
//TODO: Replace this with your own logic
return username.length() > 1;
}
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)
public 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);
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addUsernamesToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
private void addUsernamesToAutoComplete(List<String> emailCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(Login.this,
android.R.layout.simple_dropdown_item_1line, emailCollection);
mEmail.setAdapter(adapter);
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<String, Void, List<NameValuePair>> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected List<NameValuePair> doInBackground(String... params) {
// TODO: attempt authentication against a network service.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
try {
nameValuePairs.add(new BasicNameValuePair("email", mEmail));
nameValuePairs.add(new BasicNameValuePair("password", mPassword));
} catch (Exception e) {
Log.d("ColinaApp", "Login: " + e.getClass());
Log.d("ColinaApp", "Login: " + e.getMessage());
}
String text = "";
// Send data
try {
// Send POST data request
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AUTH_ENDPOINT);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
HttpResponse response = httpclient.execute(httppost);
StatusLine sl = response.getStatusLine();
int statusCode = sl.getStatusCode();
if (statusCode == 200) {
HttpEntity hp = response.getEntity();
InputStream content = hp.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String responseBody = builder.toString();
JSONObject jObject = new JSONObject(responseBody);
userToken = jObject.getString("token");
Log.d("ColinaApp", "Login: auth successful");
return nameValuePairs;
} else {
Log.d("ColinaApp", "LoginActivity: error: " + statusCode + " : " + sl.getReasonPhrase());
System.out.println(text);
return null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (IOException e) {
Log.d("ColinaApp", "Login: " + e.getClass());
Log.d("ColinaApp", "Login: " + e.getMessage());
} catch (Exception ex) {
Log.d("ColinaApp", "Login Exception: " + ex.getMessage());
Log.d("ColinaApp", "Login Exception: " + ex.getClass());
ex.printStackTrace();
}
Log.d("ColinaApp", "Login: Response: " + text);
return null;
}
@Override
protected void onPostExecute(final List<NameValuePair> success) {
mAuthTask = null;
showProgress(false);
if (success != null) {
//show the user list
Intent m2 = new Intent(Login.this, Inicio.class);
m2.putExtra("userToken", userToken);
startActivity(m2);
} else {
Log.d("ColinaApp", "Auth FAILED");
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
public static class Global {
public static String Token = userToken;
}
}
答案 0 :(得分:0)
在Manifest中放置权限并对其进行授权,因为这是一个危险的权限(根据您的情况调整此代码):
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
//This is called if user has denied the permission before
//In this case I am just asking the permission again
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
}
else {
System.out.println("" + permission + " is already granted.");
}