我正在尝试构建一个显示有关图书信息的Android应用程序(使用Google图书API)。我最近在应用程序中添加了firebase。
此时我可以登录或注册到应用程序(新用户出现在FB控制台中),我可以搜索书籍(带有搜索视图),并为ListView中列出的每本书添加了一个按钮来自查询。
接下来,我在按钮中添加了功能:按钮(如果按下)应该将当前图书(在Listview中)添加到当前用户"库"中的FireBase。 我已经在我的自定义AdapterClass中编写了这段代码,所以我可以像这样添加当前的书(来自ListView):
CustomAdapter类:
public class BookAdapter extends ArrayAdapter<BookObject> implements View.OnClickListener {
BookObject mCurrentBook;
public BookAdapter(Activity context, List<BookObject> books) {
super(context, 0, books); // 2nd par is 0 because we inflate manually
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
...
}
BookObject currentBook = getItem(position);
mCurrentBook = currentBook;
TextView TitleTextView = (TextView) listItemView.findViewById(R.id.Title_text_view);
TitleTextView.setText(currentBook.getTitle());
...
ImageView ThumbnailImageView = (ImageView) listItemView.findViewById(R.id.book_image_id);
Picasso.with(UserActivity.mMainActivity).load(currentBook.getImageURL()).into(ThumbnailImageView);
Button SaveBookbutton = (Button) listItemView.findViewById(R.id.button_id);
SaveBookbutton.setOnClickListener(this);
return listItemView;
}
@Override
public void onClick(View v) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference bookRef = FirebaseDatabase
.getInstance()
.getReference(Constants.FIREBASE_CHILD_BOOKS) // this constant is "books"
.child(uid);
DatabaseReference pushRef = bookRef.push();
String pushId = pushRef.getKey();
mCurrentBook.setPushId(pushId);
pushRef.setValue(mCurrentBook);
Toast.makeText(getContext(), "Saved", Toast.LENGTH_SHORT).show();
}
}
Build.gradle(app)
apply plugin: 'com.android.application'
android {
...
}
dependencies {
...
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-database:11.0.2'
compile 'com.google.firebase:firebase-auth:11.0.2'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
Firebase规则和数据标签
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
当我按下按钮时(在ListView中显示的某个BookObject上,我收到了Toast消息,但我在Firebase中的数据选项卡没有更新。(因此没有将该书添加到数据库中) )。我做错了什么?
注意:(在显示图书之后,我可以按下按钮之前)我在Android Studio中收到以下通知:
V/FA: Inactivity, disconnecting from the service
BookObject.java的要点: Gist with BookObject.java
感谢您对我的问题感兴趣以及任何帮助。
答案 0 :(得分:1)
在CustomAdapterClass
private String mTitle;
private String mSubTitle;
private String mAuthors;
检索所有数据并将其存储在字符串
中BookObject currentBook = getItem(position);
mTitle = currentBook.getTitle();
mSubTitle = currentBook.getSubTitle();
mAuthors = currentBook.getAuthors();
并在OnClick
方法
DatabaseReference pushRef = bookRef.push();
String pushId = pushRef.getKey();
mCurrentBook.setPushId(pushId);
pushRef.child("Title").setValue(mTitle);
pushRef.child("SubTitle").setValue(mSubTitle);
pushRef.child("Authors").setValue(mAuthors);