1

LoginActivity クラスでは、取得した電子メール アドレスとパスワードの認証を行うために Asynctask クラスを使用しています。

これは、ユーザーを認証するために Asynctask クラスを拡張する UserLoginTask クラスに制御を渡す Attemptlogin 関数を呼び出すメイン アクティビティ クラスです。

ただし、実行は常に停止し、Log.d(TAG, mUsername+ "--" + mPassword);ThreadPoolExecutor の例外をスローします。

私はアンドロイド開発に慣れていないので、コードの何が問題なのかを理解するのを手伝ってください。

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 例外メッセージに表示されているものと比較します (例: E/StrictMode( 650 ) - PID は650です)。

ただし、あなたが間違っていると思うことの 1 つは、 AsyncTaskの doInBackgroundからfinish()を呼び出すことです。doInBackgroundは独自のスレッドで実行され、finish()はおそらく UI スレッドから呼び出す必要があるため (つまり、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 に答える