我一直在使用Firebase作为数据库的Android Studio中进行编码。该应用程序可以在一段时间内正常运行,但稍后会崩溃。
项目级别文档
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven { url "https://jitpack.io" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
应用程序级别文件
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.admin.firstapp"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:support-annotations:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'de.hdodenhof:circleimageview:2.2.0'
api 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.google.firebase:firebase-firestore:17.1.5'
implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation 'com.google.firebase:firebase-crash:16.0.1'
implementation 'com.firebaseui:firebase-ui-storage:4.1.0'
implementation 'com.firebaseui:firebase-ui-database:4.1.0'
implementation 'com.github.jakebonk:NotifyMe:1.0.0'
implementation 'com.github.MAXDeliveryNG:slideview:1.1.0'
}
apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
错误
E/AndroidRuntime: FATAL EXCEPTION: TokenRefresher
Process: com.example.admin.firstapp, PID: 13467
java.lang.NoSuchFieldError: No field PREFER_HIGHEST_OR_REMOTE_VERSION_NO_FORCE_STAGING of type Lcom/google/android/gms/dynamite/DynamiteModule$VersionPolicy; in class Lcom/google/android/gms/dynamite/DynamiteModule; or its superclasses (declaration of 'com.google.android.gms.dynamite.DynamiteModule' appears in /data/app/com.example.admin.firestapp-hfO7_xvBp7yTRBLG4jEOKg==/split_lib_dependencies_apk.apk)
at com.google.android.gms.flags.FlagValueProvider.initialize(Unknown Source:7)
at com.google.android.gms.flags.FlagRegistry.initialize(Unknown Source:4)
at com.google.firebase.auth.internal.zzx.initialize(Unknown Source:3)
at com.google.firebase.auth.internal.zzt.run(Unknown Source:14)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.os.HandlerThread.run(HandlerThread.java:65)
E/UncaughtException: java.lang.NoSuchFieldError: No field PREFER_HIGHEST_OR_REMOTE_VERSION_NO_FORCE_STAGING of type Lcom/google/android/gms/dynamite/DynamiteModule$VersionPolicy; in class Lcom/google/android/gms/dynamite/DynamiteModule; or its superclasses (declaration of 'com.google.android.gms.dynamite.DynamiteModule' appears in /data/app/com.example.admin.firstapp-hfO7_xvBp7yTRBLG4jEOKg==/split_lib_dependencies_apk.apk)
at com.google.android.gms.flags.FlagValueProvider.initialize(Unknown Source:7)
at com.google.android.gms.flags.FlagRegistry.initialize(Unknown Source:4)
at com.google.firebase.auth.internal.zzx.initialize(Unknown Source:3)
at com.google.firebase.auth.internal.zzt.run(Unknown Source:14)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.os.HandlerThread.run(HandlerThread.java:65)
大约15/20分钟不活动后,应用程序崩溃。它不会涉及涉及火力场的碎片或活动。
产生错误的代码
public class ViewBankProfile extends AppCompatActivity {
private ImageButton editPic, cancel, confirmupdate;
private EditText bankname, description, contact, website;
private TextView bankusername;
private DatabaseReference mDatabase;
private String username;
private Button update;
private CircleImageView bankProfileImage;
private static final int GalleryPicK = 1;
private StorageReference bankProfileImageRef;
private ProgressDialog loadingbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_bank_profile);
bankusername = findViewById(R.id.view_bank_user_name);
bankname = findViewById(R.id.edit_bank_name);
description = findViewById(R.id.edit_bio);
website = findViewById(R.id.edit_website);
contact = findViewById(R.id.edit_bank_contact_no);
cancel = findViewById(R.id.cancel_edit_bank_profile);
confirmupdate = findViewById(R.id.confirm_edit_bank_profile);
update = findViewById(R.id.update_bank_profile);
bankProfileImage = findViewById(R.id.view_profile_pic);
editPic = findViewById(R.id.edit_profile_pic);
bankProfileImageRef = FirebaseStorage.getInstance().getReference().child("Bank Images");
loadingbar = new ProgressDialog(this);
SharedPreferences sharedPreferences = getSharedPreferences("BankData", Context.MODE_PRIVATE);
username = sharedPreferences.getString("UserName", "UserName");
if (!username.equals("UserName")) {
mDatabase = FirebaseDatabase.getInstance().getReference().child("Banks").child(username);
}
Toolbar profileToolbar = findViewById(R.id.profile_toolbar);
profileToolbar.setTitle("");
setSupportActionBar(profileToolbar);
editPic = findViewById(R.id.edit_profile_pic);
bankProfileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,GalleryPicK);
}
});
editPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,GalleryPicK);
}
});
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updatebankprofile();
}
});
confirmupdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updatebankprofile();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BankActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final SharedPreferences sharedPreferences = getSharedPreferences("BankData", Context.MODE_PRIVATE);
if (requestCode == GalleryPicK && resultCode == RESULT_OK && data != null) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode==RESULT_OK)
{
loadingbar.setTitle("Uploading");
loadingbar.setMessage("Please wait while your profile Image is Uploading...");
loadingbar.show();
final Uri resultUri = result.getUri();
final StorageReference filepath = bankProfileImageRef.child(username + ".jpg");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(getApplication(),"Profile Image Uploaded",Toast.LENGTH_SHORT).show();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), result.getUri());
String path = saveToInternalStorage(bitmap);
loadImageFromStorage(path);
SharedPreferences.Editor save = sharedPreferences.edit();
save.putString("Image",path);
save.apply();
} catch (IOException e) {
e.printStackTrace();
}
loadingbar.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(getApplication(),"Error: "+message,Toast.LENGTH_LONG).show();
loadingbar.dismiss();
}
}
});
}
}
}
@Override
protected void onStart() {
super.onStart();
SharedPreferences sharedPreferences = getSharedPreferences("BankData", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("Name", "Name");
String username = sharedPreferences.getString("UserName", "UserName");
String con = sharedPreferences.getString("Contact", "Contact");
String des = sharedPreferences.getString("Description", "Enter Information about the bank");
String web = sharedPreferences.getString("Website", "Website");
String path = sharedPreferences.getString("Image","N/A");
if(!path.equals("N/A"))
{
loadImageFromStorage(path);
}
bankusername.setText(username);
bankname.setText(name);
description.setText(des);
website.setText(web);
contact.setText(con);
}
private void updatebankprofile() {
SharedPreferences sharedPreferences = getSharedPreferences("BankData", Context.MODE_PRIVATE);
String name = bankname.getText().toString().trim();
String con = contact.getText().toString().trim();
String des = description.getText().toString().trim();
String web = website.getText().toString().trim();
HashMap<String, Object> update = new HashMap<>();
update.put("Name", name);
update.put("Contact", con);
update.put("Description", des);
update.put("Website", web);
mDatabase.updateChildren(update);
SharedPreferences.Editor save = sharedPreferences.edit();
save.putString("Name", name);
save.putString("Description", des);
save.putString("Contact", con);
save.putString("Website",web);
save.apply();
Intent intent = new Intent(getApplication(), BankActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private String saveToInternalStorage(Bitmap bitmap){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
CircleImageView img=(CircleImageView) findViewById(R.id.view_profile_pic);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplication(), BankActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
我添加了一个Java代码,但是无论涉及到Firebase数据库,都会产生此错误。