1

在 LoginActivity 类中,我使用 Asynctask 类对获取的电子邮件地址和密码进行身份验证。

这是调用尝试登录函数的主要活动类,该函数又将控制权传递给扩展了 Asynctask 类的 UserLoginTask 类,以对用户进行身份验证。

但是执行总是在之后停止,Log.d(TAG, mUsername+ "--" + mPassword);并为 ThreadPoolExecutor 抛出异常。

我是android开发的新手,所以请帮助我理解代码中的问题。

public class LoginActivity extends Activity {
    // Values for email and password at the time of the login attempt.
private String mUsername;
private String mPassword;

@Override
protected void onCreate(Bundle savedInstanceState) {
            ......

    // Set up the login form.
    mUsername = getIntent().getStringExtra(EXTRA_EMAIL);
    mUsernameView = (EditText) findViewById(R.id.email);\

            ......

    findViewById(R.id.sign_in_button).setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    attemptLogin();
                }
            });
}

/**
 * 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.
    mUsernameView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    mUsername = mUsernameView.getText().toString();
    mPassword = mPasswordView.getText().toString();

            ..........

    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.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
        showProgress(true);
        try {
        mAuthTask = new UserLoginTask();
        mAuthTask.execute(mUsername, mPassword);
        } catch(Exception e) {
            Log.e(TAG, e.toString());
        }
        //mAuthTask.execute((Void) null);
    }
}

/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<String, Void, Boolean> {
    UserFunctions userFunction;

    private String isUserLoggedIn;
    private String TAG = "Feedback App";
    private String KEY_SUCCESS = "success";
    private String result;

    @Override
    protected Boolean doInBackground(String... loginVars) {
        // TODO: attempt authentication against a network service.
        mUsername = loginVars[0];
        mPassword = loginVars[1];

        try {
            // Simulate network access.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return false;
        }

                    Log.d(TAG, mUsername+ "--" + mPassword);

        JSONObject json = userFunction.loginUser(mUsername, mPassword);
        Log.e(TAG, "fetched json" + json.toString());

        // check for login response
        try {
            if (json.getString(KEY_SUCCESS) != null) {

                                            ........
                // Close Login Screen
                finish();
            } else {
                // Error in login
                //loginErrorMsg.setText("Incorrect username/password");
                return false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // TODO: register the new account here.
        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled() {
        mAuthTask = null;
        showProgress(false);
    }
}
}

这是用于身份验证的功能

public JSONObject loginUser(String username, String password) {
    Log.d(TAG, "jsonparser class - in login");

    // Building Parameters      
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password));

    JSONObject json = jsonParser.getJSONFromUrl(serverURL, params);
    return json;
}

抛出的异常是,

03-07 11:22:26.002: E/ActivityThread(650): Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d06618 that was originally bound here
03-07 11:22:26.002: E/ActivityThread(650): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d06618 that was originally bound here
03-07 11:22:26.002: E/ActivityThread(650):  at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
03-07 11:22:26.002: E/ActivityThread(650):  at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
03-07 11:22:26.002: E/ActivityThread(650):  at android.app.ContextImpl.bindService(ContextImpl.java:1418)
03-07 11:22:26.002: E/ActivityThread(650):  at android.app.ContextImpl.bindService(ContextImpl.java:1407)
03-07 11:22:26.002: E/ActivityThread(650):  at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
03-07 11:22:26.002: E/ActivityThread(650):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
03-07 11:22:26.002: E/ActivityThread(650):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
03-07 11:22:26.002: E/ActivityThread(650):  at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191)
03-07 11:22:26.002: E/ActivityThread(650):  at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850)
03-07 11:22:26.002: E/ActivityThread(650):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
03-07 11:22:26.002: E/ActivityThread(650):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
03-07 11:22:26.002: E/ActivityThread(650):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-07 11:22:26.002: E/ActivityThread(650):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-07 11:22:26.002: E/ActivityThread(650):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-07 11:22:26.002: E/ActivityThread(650):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-07 11:22:26.002: E/ActivityThread(650):  at java.lang.Thread.run(Thread.java:856)
03-07 11:22:26.772: E/StrictMode(650): null
03-07 11:22:26.772: E/StrictMode(650): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d06618 that was originally bound here
03-07 11:22:26.772: E/StrictMode(650):  at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:969)
03-07 11:22:26.772: E/StrictMode(650):  at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863)
03-07 11:22:26.772: E/StrictMode(650):  at android.app.ContextImpl.bindService(ContextImpl.java:1418)
03-07 11:22:26.772: E/StrictMode(650):  at android.app.ContextImpl.bindService(ContextImpl.java:1407)
03-07 11:22:26.772: E/StrictMode(650):  at android.content.ContextWrapper.bindService(ContextWrapper.java:473)
03-07 11:22:26.772: E/StrictMode(650):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157)
03-07 11:22:26.772: E/StrictMode(650):  at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145)
03-07 11:22:26.772: E/StrictMode(650):  at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191)
03-07 11:22:26.772: E/StrictMode(650):  at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850)
03-07 11:22:26.772: E/StrictMode(650):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551)
03-07 11:22:26.772: E/StrictMode(650):  at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549)
03-07 11:22:26.772: E/StrictMode(650):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-07 11:22:26.772: E/StrictMode(650):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-07 11:22:26.772: E/StrictMode(650):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-07 11:22:26.772: E/StrictMode(650):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-07 11:22:26.772: E/StrictMode(650):  at java.lang.Thread.run(Thread.java:856)

并打开此 ThredPoolExecutor 选项卡,显示

public class java.util.concurrent.ThreadPoolExecutor extends java.util.concurrent.AbstractExecutorService {
// Method descriptor #17 (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;)V
// Signature: (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue<Ljava/lang/Runnable;>;)V
// Stack: 3, Locals: 7
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit unit, java.util.concurrent.BlockingQueue workQueue);
 0  aload_0 [this]
 1  invokespecial java.util.concurrent.AbstractExecutorService() [1]
 4  new java.lang.RuntimeException [2]
 7  dup
 8  ldc <String "Stub!"> [3]
10  invokespecial java.lang.RuntimeException(java.lang.String) [4]
13  athrow
  Line numbers:
    [pc: 0, line: 29]
  Local variable table:
    [pc: 0, pc: 14] local: this index: 0 type: java.util.concurrent.ThreadPoolExecutor
    [pc: 0, pc: 14] local: corePoolSize index: 1 type: int
    [pc: 0, pc: 14] local: maximumPoolSize index: 2 type: int
    [pc: 0, pc: 14] local: keepAliveTime index: 3 type: long
    [pc: 0, pc: 14] local: unit index: 5 type: java.util.concurrent.TimeUnit
    [pc: 0, pc: 14] local: workQueue index: 6 type: java.util.concurrent.BlockingQueue
  Local variable type table:
    [pc: 0, pc: 14] local: workQueue index: 6 type: java.util.concurrent.BlockingQueue<java.lang.Runnable>

// Method descriptor #36 (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;)V
// Signature: (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue<Ljava/lang/Runnable;>;Ljava/util/concurrent/ThreadFactory;)V
// Stack: 3, Locals: 8
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, java.util.concurrent.TimeUnit unit, java.util.concurrent.BlockingQueue workQueue, java.util.concurrent.ThreadFactory threadFactory);
 0  aload_0 [this]
 1  invokespecial java.util.concurrent.AbstractExecutorService() [1]
 4  new java.lang.RuntimeException [2]
 7  dup
 8  ldc <String "Stub!"> [3]
10  invokespecial java.lang.RuntimeException(java.lang.String) [4]
13  athrow
  Line numbers:
    [pc: 0, line: 30]
  Local variable table:
    [pc: 0, pc: 14] local: this index: 0 type: java.util.concurrent.ThreadPoolExecutor
    [pc: 0, pc: 14] local: corePoolSize index: 1 type: int
    [pc: 0, pc: 14] local: maximumPoolSize index: 2 type: int
    [pc: 0, pc: 14] local: keepAliveTime index: 3 type: long
    [pc: 0, pc: 14] local: unit index: 5 type: java.util.concurrent.TimeUnit
    [pc: 0, pc: 14] local: workQueue index: 6 type: java.util.concurrent.BlockingQueue
    [pc: 0, pc: 14] local: threadFactory index: 7 type: java.util.concurrent.ThreadFactory
  Local variable type table:
    [pc: 0, pc: 14] local: workQueue index: 6 type: java.util.concurrent.BlockingQueue<java.lang.Runnable>

Inner classes:
[inner class info: #7 java/util/concurrent/ThreadPoolExecutor$DiscardOldestPolicy, outer class info: #5 java/util/concurrent/ThreadPoolExecutor
 inner name: #8 DiscardOldestPolicy, accessflags: 9 public static],
[inner class info: #10 java/util/concurrent/ThreadPoolExecutor$DiscardPolicy, outer class info: #5 java/util/concurrent/ThreadPoolExecutor
 inner name: #11 DiscardPolicy, accessflags: 9 public static],
[inner class info: #12 java/util/concurrent/ThreadPoolExecutor$AbortPolicy, outer class info: #5 java/util/concurrent/ThreadPoolExecutor
 inner name: #13 AbortPolicy, accessflags: 9 public static],
[inner class info: #14 java/util/concurrent/ThreadPoolExecutor$CallerRunsPolicy, outer class info: #5 java/util/concurrent/ThreadPoolExecutor
 inner name: #15 CallerRunsPolicy, accessflags: 9 public static]
}
4

2 回答 2

0

这似乎不是(因为)您的代码中引发的异常。检查您的应用程序的 PID,并将其与 logcat 异常消息中显示的 PID 进行比较(例如:E/StrictMode( 650 ) - 这里的 PID 是650)。

但是,我认为您做错的一件事是从AsyncTask 的doInBackground调用finish()。我相信你不应该这样做,因为doInBackground在它自己的线程中运行,并且可能应该从 UI 线程调用finish () (即应该在onPostExecute() 中调用)

于 2013-03-07T11:43:16.097 回答
0

尝试在 LoginActivity 中集成其他类的所有功能。例如,来自 UserFunctions 类的 loginUser 函数和来自 JSONParser 类的 getJSONFromUrl。

如果需要,不要忘记声明您的 serverURL 字符串并添加导入。

    public class LoginActivity extends Activity {
    // Values for email and password at the time of the login attempt.
private String mUsername;
private String mPassword;

 private static String serverURL = "YOUR URL";

    //private JSONParser jsonParser;

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
            ......

    // Set up the login form.
    mUsername = getIntent().getStringExtra(EXTRA_EMAIL);
    mUsernameView = (EditText) findViewById(R.id.email);\

            ......

    findViewById(R.id.sign_in_button).setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    attemptLogin();
                }
            });
}

/**
 * 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.
    mUsernameView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    mUsername = mUsernameView.getText().toString();
    mPassword = mPasswordView.getText().toString();

            ..........

    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.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
        showProgress(true);
        try {
        mAuthTask = new UserLoginTask();
        mAuthTask.execute(mUsername, mPassword);
        } catch(Exception e) {
            Log.e(TAG, e.toString());
        }
        //mAuthTask.execute((Void) null);
    }
}

public JSONObject loginUser(String username, String password) {
    Log.d(TAG, "jsonparser class - in login");

    // Building Parameters      
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password));

    JSONObject json = jsonParser.getJSONFromUrl(serverURL, params);
    return json;
}

/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<String, Void, Boolean> {
    UserFunctions userFunction;

    private String isUserLoggedIn;
    private String TAG = "Feedback App";
    private String KEY_SUCCESS = "success";
    private String result;

    @Override
    protected Boolean doInBackground(String... loginVars) {
        // TODO: attempt authentication against a network service.
        mUsername = loginVars[0];
        mPassword = loginVars[1];

        try {
            // Simulate network access.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return false;
        }

                    Log.d(TAG, mUsername+ "--" + mPassword);

        JSONObject json = userFunction.loginUser(mUsername, mPassword);
        Log.e(TAG, "fetched json" + json.toString());

        // check for login response
        try {
            if (json.getString(KEY_SUCCESS) != null) {

                                            ........
                // Close Login Screen
                finish();
            } else {
                // Error in login
                //loginErrorMsg.setText("Incorrect username/password");
                return false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // TODO: register the new account here.
        return true;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled() {
        mAuthTask = null;
        showProgress(false);
    }
}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) 
    {
        // Making HTTP request
        try 
        {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            /*
             *  if you are referring to a localhost from your device than use the http://10.0.2.2/ 
             *  instead of the http://127.0.0.1/ or http://localhost/. Because your Android emulator is running
             *  on a Virtual Machine(QEMU) and you can not connect to a server directly running on your PC.
             *  So your code snippet will be like this:
             *  HttpPost httpMethod = new HttpPost("http://10.0.2.2:8080/ + address insteda of the normal website name");
             *  Modify your url from the previous activity
             */
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            /*  If you come across connection problems and any action requiring data transfer silently fails
             *  the following line of code could be the reason of the issue. Add a line breakpoint and check 
             *  whether the request has been sent or not. Check your server ip, and make sure that your
             *  machine is visible.
             */
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
        catch (UnsupportedEncodingException e) 
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }

        try 
        {
            /*
             *  Here you should receive the response from the web, check out reader response from BufferedReader class
             *  If you receive a html page response then your server is not online or reachable.
             */
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) 
            {
                Log.e("JSON PARSER:","line : "+ line);
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
            //Log.e("JSON", json);
        } 
        catch (Exception e) 
        {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try 
        {
            jObj = new JSONObject(json);
        } 
        catch (JSONException e) 
        {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

}
于 2013-09-04T20:42:28.157 回答