Android应用程序在模拟器上运行但在真实设备上崩溃

时间:2017-09-21 22:30:12

标签: java android firebase apk

我已经检查了有关此问题的stackoverflow上的所有问题,并尝试了所有内容并仍然得到相同的错误。我有一个带有firebase身份验证,存储和数据库的android应用程序。我在android studio上创建的每个模拟器上都运行得很好。我也尝试在使用Genymotion创建的设备上运行应用程序,该应用程序也可以正常工作。然后我尝试使用USB调试在真实设备上运行,即使这样应用程序运行正常。

只有当我尝试使用Android工作室“Build Apk”选项创建的APK文件安装应用时,应用才会崩溃。由于应用程序在USB调试和每个模拟器上运行良好,我甚至无法在logcat中看到错误。

这是文件文件。 Mainfest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kinny.instagram_clone">

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="false"
        android:fullBackupContent="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

                <meta-data
                    android:name="android.support.PARENT_ACTIVITY"
                    android:value="com.example.kinny.instagram_clone" />
            </intent-filter>
        </activity>
        <activity
            android:name=".UserList"
             />
        <activity android:name=".UserFeed"
            android:parentActivityName=".UserList"
            ></activity>
        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="504a079771b5c515a67b9ed577e080347a024bc7" />
    </application>

    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

我的Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.kinny.instagram_clone.MainActivity">

    <ImageView
        android:id="@+id/mainPageLogo"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="6dp"
        app:srcCompat="@drawable/logo" />

    <EditText
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:ems="10"
        android:hint="test@gmail.com"
        android:includeFontPadding="false"
        android:inputType="textPersonName"
        android:paddingTop="20dp" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/email"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:hint="password"
        android:inputType="textPassword"
        android:paddingTop="20dp" />

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="14dp"
        android:ems="10"
        android:hint="username"
        android:inputType="textPersonName"
        android:paddingTop="20dp" />

    <Button
        android:id="@+id/LoginSignup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:background="@color/colorPrimaryDark"
        android:onClick="signupOrLogin"
        android:text="Sign Up"
        android:textColor="@android:color/holo_red_light"
        android:textSize="25dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_above="@+id/changeButtonText"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/changeButtonText"
        android:paddingTop="20dp"
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="Log In"
        android:textColor="#1d27ff"
        android:textSize="30dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="12dp" />


</RelativeLayout>

和我的主要活动文件

class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnKeyListener {

    // Layout elements
    EditText password;
    EditText email;
    TextView changeSingupLoginMode;
    Button signupButton;
    ImageView logo;
    RelativeLayout relativeLayout;
    EditText username;

    // Fierbase credentials
    public static FirebaseUser user;
    public static FirebaseDatabase database = FirebaseDatabase.getInstance();
    public static DatabaseReference myRef = database.getReference("users");
    DatabaseReference users;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    // Util variables
    Boolean signupModeActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Write a message to the database


        signupModeActive = true;
        // Firebase Database reference
        users = FirebaseDatabase.getInstance().getReference();


        // Firebase Authentication
        mAuth = FirebaseAuth.getInstance();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in


                    makeToast("Welcome " + user.getEmail());
                    showUserList();
                } else {
                    // User is signed out
                    makeToast("Welcome");
                }
            }
        };

        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        signupButton = (Button) findViewById(R.id.LoginSignup);
        logo = (ImageView) findViewById(R.id.mainPageLogo);
        relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
        changeSingupLoginMode = (TextView) findViewById(R.id.changeButtonText);
        username = (EditText) findViewById(R.id.username);

        changeSingupLoginMode.setOnClickListener(this);
        logo.setOnKeyListener(this);
        relativeLayout.setOnClickListener(this);

        email.setOnKeyListener(this);
        password.setOnKeyListener(this);
        username.setOnClickListener(this);


    }

    public void showUserList() {
        Intent i = new Intent(getApplicationContext(), UserList.class);
        startActivity(i);
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    public void createAccount(final String accountEmail, final String accountPassword, final String accountUsername){
        mAuth.createUserWithEmailAndPassword(accountEmail, accountPassword)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            User newUser = new User(accountEmail, accountPassword, accountUsername);
                            myRef.push().setValue(newUser);
                            showUserList();

                        } else {
                            // If sign in fails, display a message to the user.
                            task.getException();
                            Toast.makeText(getApplicationContext(), task.getException().getLocalizedMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    public void signupOrLogin(View view) {

        if (TextUtils.isEmpty(String.valueOf(email.getText()))) {
            this.makeToast("Please enter an email id!");
            return;
        }

        if (TextUtils.isEmpty(String.valueOf(password.getText()))) {
            this.makeToast("Please enter a password");
            return;
        }

        if (!isValidEmail(String.valueOf(email.getText()))) {
            this.makeToast("Invalid email address!!");
            return;
        } else {

            if (signupModeActive) {

                if (TextUtils.isEmpty(String.valueOf(username.getText()))) {
                    this.makeToast("Please enter a username");
                    return;
                }

                myRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        boolean usernamTaken = false;
                        boolean emailIdTken = false;

                        for(DataSnapshot data: dataSnapshot.getChildren()){

                            if ((data.child("username").getValue()).equals(String.valueOf(username.getText()))) {
                                usernamTaken = true;
                                break;
                            }
                        }

                        if(!usernamTaken){
                            createAccount(String.valueOf(email.getText()), String.valueOf(password.getText()), String.valueOf(username.getText()));
                            return;
                        }
                        else{
                            makeToast("Username Taken, Try Something else");
                            return;
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError error) {
                        // Failed to read value
                        Log.w("data", "Failed to read value.", error.toException());
                    }
                });

            } else {
                mAuth.signInWithEmailAndPassword(String.valueOf(email.getText()), String.valueOf(password.getText()))
                        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                Log.d("Login", "LogIn:onComplete:" + task.isSuccessful());

                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                if (!task.isSuccessful()) {
                                    Log.w("Login", "signInWithEmail:failed", task.getException());
                                    Toast.makeText(getApplicationContext(), task.getException().getLocalizedMessage(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    showUserList();
                                }
                            }
                        });
            }

        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    public void makeToast(String text) {
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.changeButtonText) {
            if (signupModeActive == true) {
                signupModeActive = false;
                changeSingupLoginMode.setText("Sign Up");
                signupButton.setText("Log In");
                username.setVisibility(View.INVISIBLE);
            } else {
                signupModeActive = true;
                changeSingupLoginMode.setText("Log In");
                signupButton.setText("Sign Up");
                username.setVisibility(View.VISIBLE);
            }
        } else if (v.getId() == R.id.mainPageLogo || v.getId() == R.id.relativeLayout) {

            // removing keyboard form the app if clicked somewhere else

            InputMethodManager inm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            inm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            signupOrLogin(v);
        }
        return false;
    }
}

请注意,我的应用中还有多项活动,可以查看here

1 个答案:

答案 0 :(得分:0)

1)如果您使用USB插入设备并安装apk并在插入的设备上运行它,您可以在Android Studio 2中的Android Monitor面板中看到logcat)此外,您可以使用Crashlytics(只需将其附加到您的应用程序)即可查看Crashlytics仪表板中的错误。

相关问题