强制关闭的android应用程序需要修复错误

时间:2013-10-21 10:35:04

标签: android android-intent android-fragments forceclose

我正在创建一个Android应用程序,在用户登录应用程序后使用片段使用intent显示第二个活动。但问题是申请会在登录后强制关闭。

有人可以帮我解决错误吗?

AndroidNavigationTabsActivity

ackage com.exercise.AndroidNavigationTabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class AndroidNavigationTabsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        Tab tabA = actionBar.newTab();
        tabA.setText("Tab A");
        tabA.setTabListener(new TabListener<MyFragmentA>(this, "Tag A", MyFragmentA.class));
        actionBar.addTab(tabA);

        Tab tabB = actionBar.newTab();
        tabB.setText("Tab B");
        tabB.setTabListener(new TabListener<MyFragmentB>(this, "Tag B", MyFragmentB.class));
        actionBar.addTab(tabB);

        Tab tabC = actionBar.newTab();
        tabC.setText("Tab C");
        tabC.setTabListener(new TabListener<MyFragmentC>(this, "Tag C", MyFragmentC.class));
        actionBar.addTab(tabC);

        if (savedInstanceState != null) {
            int savedIndex = savedInstanceState.getInt("SAVED_INDEX");
            getActionBar().setSelectedNavigationItem(savedIndex);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putInt("SAVED_INDEX", getActionBar().getSelectedNavigationIndex());
    }

    public static class TabListener<T extends Fragment> 
        implements ActionBar.TabListener{

        private final Activity myActivity;
        private final String myTag;
        private final Class<T> myClass;

        public TabListener(Activity activity, String tag, Class<T> cls) {
            myActivity = activity;
            myTag = tag;
            myClass = cls;
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {

            Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);

            // Check if the fragment is already initialized
            if (myFragment == null) {
                // If not, instantiate and add it to the activity
                myFragment = Fragment.instantiate(myActivity, myClass.getName());
                ft.add(android.R.id.content, myFragment, myTag);
            } else {
                // If it exists, simply attach it in order to show it
                ft.attach(myFragment);
            }

        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {

            Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);

            if (myFragment != null) {
                // Detach the fragment, because another one is being attached
                ft.detach(myFragment);
            }

        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            // TODO Auto-generated method stub

        }

    }
}

LoginActivity

package com.exercise.AndroidNavigationTabs;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
    /**
     * 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" };

    /**
     * The default email to populate the email field with.
     */
    public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // Values for email and password at the time of the login attempt.
    private String mEmail = "jamil@jamil.com";
    private String mPassword = "jamil123";

    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;
    private TextView mRegister;

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

        setContentView(R.layout.activity_login);

        // Set up the login form.
        mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
        mEmailView = (EditText) findViewById(R.id.email);
        mEmailView.setText(mEmail);

        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;
                    }
                });

        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

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

        // Register link

        mRegister = (TextView) findViewById(R.id.txt_register);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    /**
     * 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) {

            // if everything go well the application will send the user to the
            // second page
            Intent intent = new Intent(this, MyFragmentA.class);
            startActivity(intent);

            Toast.makeText(this, "the system will display the second page",
                    Toast.LENGTH_SHORT).show();

            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

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

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (TextUtils.isEmpty(mPassword)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        } else if (mPassword.length() < 6) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(mEmail)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!mEmail.contains("@")) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            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.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            mAuthTask = new UserLoginTask();
            mAuthTask.execute((Void) null);

        }
    }

    /**
     * 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);

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

            mLoginFormView.setVisibility(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);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

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

            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the password matches.
                    return pieces[1].equals(mPassword);
                }
            }

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

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

            if (success) {
                finish();
            } else {
                mPasswordView
                        .setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

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

MyFragmentA

package com.exercise.AndroidNavigationTabs;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyFragmentA extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
        return myFragmentView;
    }

}

的logcat

10-21 10:32:58.146: D/AndroidRuntime(784): CheckJNI is ON
10-21 10:32:58.976: D/AndroidRuntime(784): Calling main entry com.android.commands.am.Am
10-21 10:32:59.006: I/ActivityManager(89): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.exercise.AndroidNavigationTabs/.LoginActivity} from pid 784
10-21 10:32:59.006: W/WindowManager(89): Failure taking screenshot for (180x300) to layer 21005
10-21 10:32:59.136: W/NetworkManagementSocketTagger(89): setKernelCountSet(10047, 1) failed with errno -2
10-21 10:32:59.136: D/AndroidRuntime(784): Shutting down VM
10-21 10:32:59.186: D/dalvikvm(784): GC_CONCURRENT freed 102K, 77% free 485K/2048K, paused 0ms+1ms
10-21 10:32:59.196: D/dalvikvm(784): Debugger has detached; object registry had 1 entries
10-21 10:32:59.206: I/AndroidRuntime(784): NOTE: attach of thread 'Binder Thread #3' failed
10-21 10:32:59.627: I/Process(89): Sending signal. PID: 726 SIG: 3
10-21 10:32:59.627: I/dalvikvm(726): threadid=3: reacting to signal 3
10-21 10:32:59.716: I/dalvikvm(726): Wrote stack traces to '/data/anr/traces.txt'
10-21 10:33:00.196: D/dalvikvm(89): GC_CONCURRENT freed 404K, 12% free 11366K/12871K, paused 7ms+76ms
10-21 10:33:00.216: I/Process(89): Sending signal. PID: 726 SIG: 3
10-21 10:33:00.216: I/dalvikvm(726): threadid=3: reacting to signal 3
10-21 10:33:00.246: I/dalvikvm(726): Wrote stack traces to '/data/anr/traces.txt'
10-21 10:33:00.446: I/ActivityManager(89): Displayed com.exercise.AndroidNavigationTabs/.LoginActivity: +1s326ms
10-21 10:33:00.766: W/NetworkManagementSocketTagger(89): setKernelCountSet(10013, 0) failed with errno -2
10-21 10:33:01.067: D/dalvikvm(144): GC_CONCURRENT freed 295K, 29% free 9990K/13959K, paused 5ms+6ms
10-21 10:33:18.656: D/dalvikvm(175): GC_CONCURRENT freed 384K, 6% free 9534K/10119K, paused 5ms+5ms
10-21 10:33:28.957: D/InputEventConsistencyVerifier(726): KeyEvent: ACTION_UP but key was not down.
10-21 10:33:28.957: D/InputEventConsistencyVerifier(726):   in android.widget.EditText@412bc250
10-21 10:33:28.957: D/InputEventConsistencyVerifier(726):   0: sent at 1906974000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=1906974, downTime=1906890, deviceId=0, source=0x101 }
10-21 10:33:40.476: W/WindowManager(89): Failure taking screenshot for (180x300) to layer 21010
10-21 10:33:40.596: W/NetworkManagementSocketTagger(89): setKernelCountSet(10013, 1) failed with errno -2
10-21 10:33:40.826: W/InputManagerService(89): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@413a0168 (uid=10047 pid=726)
10-21 10:33:40.836: W/IInputConnectionWrapper(726): showStatusIcon on inactive InputConnection
10-21 10:33:41.576: W/NetworkManagementSocketTagger(89): setKernelCountSet(10047, 0) failed with errno -2
10-21 10:33:41.646: D/dalvikvm(144): GC_CONCURRENT freed 586K, 30% free 9867K/13959K, paused 5ms+37ms

0 个答案:

没有答案
相关问题