看了很多,但在我阅读Take Control of Your Firebase Init on Android
之前没有运气因此,当我添加提到的代码块时,单击“登录”或“注册”时,我的应用程序不会持续崩溃。
添加到RegistrationActivity.java
时不会崩溃FirebaseOptions.Builder builder = new FirebaseOptions.Builder()
.setApplicationId("1:0123456789012:android:0123456789abcdef")
.setApiKey("your_api_key")
.setDatabaseUrl("https://your-app.firebaseio.com")
.setStorageBucket("your-app.appspot.com");
FirebaseApp.initializeApp(this, builder.build());
输入我的Firebase用户后无法登录,但这是因为我从未向我的数据库值中提供的示例值中填写了我的Firebase值。但我很困惑为什么我的应用程序不会立即崩溃我的RegistrationActivity.Java这段代码,但当我发表评论时,我得到了标题中提到的错误。
有人可以解释如何在没有上面的代码块的情况下让我的原始代码工作,或者这是新方法吗?当我开始搞乱我的Gradle文件时,我的问题全部开始了,所以这就是我今天所处的位置。 TIA。
这是我的Project Gradle
buildscript {
ext.versions = [
'compileSdk' : 27,
'targetSdk' : 27,
'buildTools' : '27.0.3',
// 'butterknife' : '8.8.1',
// 'glide' : '4.6.1',
// 'kotlin' : '1.2.21',
// 'retrofit' : '2.3.0',
// 'supportLibrary': '27.0.2'
]
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.5.4'
//classpath 'com.google.gms:google-services:3.1.0'
}
allprojects {
repositories {
jcenter()
maven { url "https://maven.google.com" }// Google's Maven repository
}
}
}
这是我的Module App Gradle apply plugin:'com.android.application'
android {
compileSdkVersion versions.compileSdk
buildToolsVersion versions.buildTools
defaultConfig {
applicationId "com.example.tinder"
minSdkVersion 26
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-
optimize.txt'), 'proguard-rules.pro'
}
customDebug {
debuggable true
}
}
}
repositories {
google()
jcenter()
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:support-annotations:27.1.1'
implementation 'com.google.firebase:firebase-core:15.0.2'
implementation 'com.google.firebase:firebase-auth:15.1.0'
implementation 'com.google.firebase:firebase-storage:15.0.2'
implementation 'com.google.firebase:firebase-database:15.0.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
implementation 'com.lorentzos.swipecards:library:1.0.9'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
//apply plugin: 'com.google.gms.google-services'
这是我的RegistrationActivity.java package com.example.tinder;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
public class RegistrationActivity extends AppCompatActivity {
private Button mRegister;
private EditText mEmail, mPassword, mName;
private RadioGroup mRadioGroup;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
//
// FirebaseOptions.Builder builder = new FirebaseOptions.Builder()
//
// .setApplicationId("1:0123456789012:android:0123456789abcdef")
// .setApiKey("your_api_key")
// .setDatabaseUrl("https://your-app.firebaseio.com")
// .setStorageBucket("your-app.appspot.com");
// FirebaseApp.initializeApp(this, builder.build());
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user =
FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
Intent intent = new Intent(RegistrationActivity.this,
MainActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mRegister = (Button) findViewById(R.id.register);
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mName = (EditText) findViewById(R.id.name);
mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
mRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int selectId = mRadioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = (RadioButton)
findViewById(selectId);
if(radioButton.getText() == null){
return;
}
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
final String name = mName.getText().toString();
mAuth.createUserWithEmailAndPassword(email,
password).addOnCompleteListener(RegistrationActivity.this, new
OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(RegistrationActivity.this, "sign up
error", Toast.LENGTH_SHORT).show();
}else{
String userId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserDb =
FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
Map userInfo = new HashMap<>();
userInfo.put("name" , name);
userInfo.put("gender",
"Male");//radioButton.getTag().toString());
userInfo.put("profileImageUrl", "default");
currentUserDb.updateChildren(userInfo);
}
}
});
}
});
}
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthStateListener);
}
@Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
}
这是我的MainActivitiy.java
package com.example.tinder;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private cards cards_data[];
private arrayAdapter arrayAdapter;
private int i;
private FirebaseAuth mAuth;
private String currentUId;
private DatabaseReference usersDb;
ListView listView;
List<cards> rowItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usersDb = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
currentUId = mAuth.getCurrentUser().getUid();
checkUserPreferences();
rowItems = new ArrayList<cards>();
// al.add("javascript");
// al.add("php");
arrayAdapter = new arrayAdapter(this, R.layout.item, rowItems );
// al.add("javascript");
// arrayAdapter.notifyDataSetChanged();
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView)
findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new
SwipeFlingAdapterView.onFlingListener() {
@Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter
(/AdapterView)
Log.d("LIST", "removed object!");
rowItems.remove(0);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
cards obj = (cards) dataObject;
String userId = obj.getUserId();
usersDb.child(userId).child("connections").child("pass").
child(currentUId).setValue(true);
isConnectionMatch(userId);
Toast.makeText(MainActivity.this,"Pass",
Toast.LENGTH_SHORT).show();
}
@Override
public void onRightCardExit(Object dataObject) {
cards obj = (cards) dataObject;
String userId = obj.getUserId();
usersDb.child(userId).child("connections").child("meet").
child(currentUId).setValue(true);
isConnectionMatch(userId);
Toast.makeText(MainActivity.this,"Meet",
Toast.LENGTH_SHORT).show();
}
@Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
}
@Override
public void onScroll(float scrollProgressPercent) {
}
}
);
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new
SwipeFlingAdapterView.OnItemClickListener() {
@Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this,"Clicked",
Toast.LENGTH_SHORT).show();
}
}
);
}
private void isConnectionMatch(String userId) {
DatabaseReference currentUserConnectionsDb =
usersDb.child(currentUId).child("connections").
child("meet").child(userId);
currentUserConnectionsDb.addListenerForSingleValueEvent(new
ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivity.this, "New Match",
Toast.LENGTH_LONG).show();
usersDb.child(dataSnapshot.getKey()).child("connections").
child("matches").child(currentUId).setValue(true);
usersDb.child(currentUId).child("connections").child("matches").
child(dataSnapshot.getKey()).setValue(true);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
}
);
}
private String userGender;
private String searchGender;
public void checkUserPreferences(){
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference userDb = usersDb.child(user.getUid());
userDb.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getKey().equals(user.getUid())){
if (dataSnapshot.exists()){
if (dataSnapshot.child("gender") != null){
userGender =
dataSnapshot.child("gender").getValue().toString();
searchGender = "Female";
switch (userGender) {
case "Male":
searchGender = "Female";
break;
case "Female":
searchGender = "Male";
break;
}
getSearchGender();
}
}
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
}
);
}
public void getSearchGender(){
usersDb.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists() &&
!dataSnapshot.child("connections").child("pass").hasChild(currentUId) &&
!dataSnapshot.child("connections").child("meet").hasChild(currentUId) &&
dataSnapshot.child("gender").getValue().toString().equals(searchGender)) {
String profileImageUrl = "default";
if
(dataSnapshot.child("profileImageUrl").getValue().equals("default")) {
profileImageUrl =
dataSnapshot.child("profileImageUrl").getValue().toString();
}
cards item = new cards(dataSnapshot.getKey(),
dataSnapshot.child("name").getValue().toString(), profileImageUrl);
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
}
);
}
public void logoutUser(View view) {
mAuth.signOut();
Intent intent = new Intent(MainActivity.this,
ChooseLoginRegistrationActivity.class);
startActivity(intent);
finish();
return;
}
public void gotoSettings(View view) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
intent.putExtra("userGender", userGender);
startActivity(intent);
return;
}
}
答案 0 :(得分:1)
使用我在这篇文章中的原始文件,唯一需要的更改是取消注释1行并添加另一行(都在Gradle文件中)
PROJECT APP取消注释了gms行并更新了原始帖子的版本
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:4.5.4'
classpath 'com.google.gms:google-services:3.2.0'
}
MODULE APP已添加到文件底部
apply plugin: 'com.google.gms.google-services'
我还必须从3.0.1将google-service版本更新为3.2.0。不需要任何其他东西。我现在稍微领先于我原来的问题是我的应用程序在上传的照片上更新(点击确认按钮)后崩溃了。该照片存储在Firebase数据库存储中,但在要求更多帮助之前,我会对此进行一些故障排除。感谢@VIKAS SHARMA的建议
答案 1 :(得分:0)
您只需要在应用程序应用程序文件中初始化firebase
这样做:
private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
mAuth.signInWithEmailAndPassword(email, password)
.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
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
然后让我知道loggs