我的问题与这个问题how to check favorite item document is exist from firestore类似,但就我而言,它是Java上的Firebase实时数据库。我添加了将收藏夹添加到Firebase数据库的功能,但问题仅在于替换工具栏上的收藏夹按钮。如下图所示的详细活动页面
当我单击列表recyclerview上的项目时,详细信息活动必须知道数据是否存储在“收藏夹”节点上。当我单击detailActivity工具栏上的“收藏夹”按钮时,数据已成功存储,但是当我再次打开存储在“收藏夹”中的项目时,尽管“收藏夹”按钮的颜色没有变化,即使它已存储在“收藏夹”节点上。
这是我尝试进行详细活动的代码。
DetailEducationActivity.java
/*
* Copyright 2019 RONINGRUM. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.id.roningrum.dolanapptugasakhir.ui.detailactivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.Objects;
import co.id.roningrum.dolanapptugasakhir.R;
import co.id.roningrum.dolanapptugasakhir.handler.GPSHandler;
import co.id.roningrum.dolanapptugasakhir.handler.HaversineHandler;
import co.id.roningrum.dolanapptugasakhir.model.TourismItem;
public class DetailEducatioActivity extends AppCompatActivity implements OnMapReadyCallback {
public static final String EXTRA_WISATA_KEY = "edukasi_key";
private static final String MAP_VIEW_KEY = "mapViewBundle";
private final static String TAG = "Pesan";
private GoogleMap educationGoogleMap;
private MapView educationMapView;
private DatabaseReference educationDetailRef;
private GPSHandler gpsHandler;
private ValueEventListener valueEventListener;
private TextView tvNameEducationDetail, tvAddressEducationDetail,
tvDescEducation, tvDistanceEducation;
private ImageView imgEducation;
private CollapsingToolbarLayout collapsingToolbarLayout;
private double startLat;
private double startlng;
private double endlat;
private double endLng;
private double distance;
boolean isFavorite;
TourismItem tourismItem = new TourismItem();
String eduKey;
private FirebaseAuth firebaseAuth;
private FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_education_category);
tvNameEducationDetail = findViewById(R.id.name_place_education_detail);
tvAddressEducationDetail = findViewById(R.id.address_place_education_detail);
tvDescEducation = findViewById(R.id.info_place_education_detail);
tvDistanceEducation = findViewById(R.id.distance_place_education_detail);
imgEducation = findViewById(R.id.img_nature_education_detail);
educationMapView = findViewById(R.id.loc_edu_map);
collapsingToolbarLayout = findViewById(R.id.collapseToolbar);
Toolbar toolbarEducation = findViewById(R.id.toolbar_education_detail);
setSupportActionBar(toolbarEducation);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_24dp);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_KEY);
}
educationMapView.onCreate(mapViewBundle);
educationMapView.getMapAsync(this);
eduKey = getIntent().getStringExtra(EXTRA_WISATA_KEY);
if (eduKey == null) {
throw new IllegalArgumentException("Must pass Extra");
}
educationDetailRef = FirebaseDatabase.getInstance().getReference().child("Tourism").child(eduKey);
Query eduQuery = educationDetailRef.orderByChild("category_tourism").equalTo("edukasi");
gpsHandler = new GPSHandler(this);
LoadEducationDetail();
}
private void LoadEducationDetail() {
if (gpsHandler.isCanGetLocation()) {
ValueEventListener eventListener = new ValueEventListener() {
@SuppressLint("SetTextI18n")
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
tourismItem = dataSnapshot.getValue(TourismItem.class);
startLat = gpsHandler.getLatitude();
startlng = gpsHandler.getLongitude();
assert tourismItem != null;
endlat = tourismItem.getLat_location_tourism();
endLng = tourismItem.getLng_location_tourism();
distance = HaversineHandler.calculateDistance(startLat, startlng, endlat, endLng);
@SuppressLint("DefaultLocale") String distanceFormat = String.format("%.2f", distance);
tvDistanceEducation.setText("" + distanceFormat + " km");
tvNameEducationDetail.setText(tourismItem.getName_tourism());
tvAddressEducationDetail.setText(tourismItem.getLocation_tourism());
tvDescEducation.setText(tourismItem.getInfo_tourism());
Glide.with(getApplicationContext()).load(tourismItem.getUrl_photo()).into(imgEducation);
AppBarLayout appBarLayout = findViewById(R.id.app_bar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.BaseOnOffsetChangedListener() {
boolean isShow = true;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbarLayout.setTitle(tourismItem.getName_tourism());
isShow = true;
} else {
collapsingToolbarLayout.setTitle(" ");
isShow = false;
}
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Firebase Database Error" + databaseError.getMessage());
}
};
educationDetailRef.addValueEventListener(eventListener);
valueEventListener = eventListener;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_KEY, mapViewBundle);
}
educationMapView.onSaveInstanceState(mapViewBundle);
}
@Override
public void onMapReady(GoogleMap googleMap) {
educationGoogleMap = googleMap;
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
tourismItem = dataSnapshot.getValue(TourismItem.class);
assert tourismItem != null;
double lattitude = tourismItem.getLat_location_tourism();
double longitude = tourismItem.getLng_location_tourism();
LatLng location = new LatLng(lattitude, longitude);
educationGoogleMap.addMarker(new MarkerOptions().position(location));
educationGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 16.0f));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(TAG, "Firebase Database Error" + databaseError.getMessage());
}
};
educationDetailRef.addValueEventListener(eventListener);
valueEventListener = eventListener;
}
@Override
protected void onResume() {
super.onResume();
educationMapView.onResume();
}
@Override
protected void onStart() {
super.onStart();
LoadEducationDetail();
educationMapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
educationMapView.onStop();
educationDetailRef.removeEventListener(valueEventListener);
}
@Override
protected void onPause() {
super.onPause();
educationMapView.onPause();
}
//the button of favorite
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.favorite_menu, menu);
MenuItem favorite = menu.findItem(R.id.add_to_favorite);
if (isFavorite) {
favorite.setIcon(R.drawable.ic_bookmarkadded_24dp);
// isFavorite = false;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
// Respond to the action bar's Up/Home button
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
if (item.getItemId() == R.id.add_to_favorite) {
//this code when the button favorite click
final String uid = user.getUid();
final DatabaseReference favoritedb = FirebaseDatabase.getInstance().getReference("Favorite");
favoritedb.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (uid.equals(dataSnapshot.child(uid).getKey())) {
if(isFavorite){
item.setIcon(R.drawable.ic_unbookmarked_24dp);
favoritedb.getRef().child(uid).child(eduKey).removeValue();
isFavorite = false;
}
else{
item.setIcon(R.drawable.ic_bookmarkadded_24dp);
favoritedb.getRef().child(uid).child(eduKey).setValue(true);
isFavorite = true;
}
} else {
item.setIcon(R.drawable.ic_bookmarkadded_24dp);
favoritedb.getRef().child(uid).child(eduKey).setValue(true);
isFavorite = true;
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
}
和列表活动
EducationCategoryActivity.java
/*
* Copyright 2019 RONINGRUM. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.id.roningrum.dolanapptugasakhir.ui.categoryactivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.util.ArrayList;
import java.util.Arrays;
import co.id.roningrum.dolanapptugasakhir.R;
import co.id.roningrum.dolanapptugasakhir.handler.GPSHandler;
import co.id.roningrum.dolanapptugasakhir.handler.NetworkHelper;
import co.id.roningrum.dolanapptugasakhir.handler.PermissionHandler;
import co.id.roningrum.dolanapptugasakhir.model.TourismItem;
import co.id.roningrum.dolanapptugasakhir.ui.detailactivity.DetailEducatioActivity;
import co.id.roningrum.dolanapptugasakhir.ui.mapsactivity.EducationCategoryMaps;
import co.id.roningrum.dolanapptugasakhir.viewholder.categoryviewholder.EducationViewHolder;
public class EducationCategoryActivity extends AppCompatActivity {
private RecyclerView rvEducationList;
private ShimmerFrameLayout shimmerFrameLayout;
private FirebaseRecyclerAdapter<TourismItem, EducationViewHolder> educationFirebaseAdapter;
private GPSHandler gpsHandler;
private PermissionHandler permissionHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_education);
rvEducationList = findViewById(R.id.tourism_education_list);
Toolbar toolbarEducation = findViewById(R.id.toolbar_top_education);
shimmerFrameLayout = findViewById(R.id.shimmer_view_container);
rvEducationList.setLayoutManager(new LinearLayoutManager(this));
ArrayList<TourismItem> tourismItems = new ArrayList<>();
setSupportActionBar(toolbarEducation);
checkConnection();
}
private void checkConnection() {
if (NetworkHelper.isConnectedToNetwork(getApplicationContext())) {
showData();
} else {
Toast.makeText(this, "Check your connection", Toast.LENGTH_SHORT).show();
}
}
private void showData() {
if (havePermission()) {
DatabaseReference educationCategoryDB = FirebaseDatabase.getInstance().getReference();
Query educationQuery = educationCategoryDB.child("Tourism").orderByChild("category_tourism").equalTo("edukasi");
FirebaseRecyclerOptions<TourismItem> educationOptions = new FirebaseRecyclerOptions.Builder<TourismItem>()
.setQuery(educationQuery, TourismItem.class)
.build();
educationFirebaseAdapter = new FirebaseRecyclerAdapter<TourismItem, EducationViewHolder>(educationOptions) {
@NonNull
@Override
public EducationViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
return new EducationViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_education_category_menu, viewGroup, false));
}
@Override
protected void onBindViewHolder(@NonNull EducationViewHolder holder, int position, @NonNull TourismItem model) {
final DatabaseReference educationCategoryRef = getRef(position);
final String eductaionKey = educationCategoryRef.getKey();
Log.d("Check eduKey", ""+eductaionKey);
gpsHandler = new GPSHandler(getApplicationContext());
if (gpsHandler.isCanGetLocation()) {
double latitude = gpsHandler.getLatitude();
double longitude = gpsHandler.getLongitude();
Log.i("Message", "CurLoc :" + latitude + "," + longitude);
shimmerFrameLayout.stopShimmer();
shimmerFrameLayout.setVisibility(View.GONE);
holder.showEducationTourismData(model, latitude, longitude);
holder.setOnClickListener(new EducationViewHolder.ClickListener() {
@Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getApplicationContext(), DetailEducatioActivity.class);
intent.putExtra(DetailEducatioActivity.EXTRA_WISATA_KEY, eductaionKey);
startActivity(intent);
}
});
} else {
gpsHandler.stopUsingGPS();
gpsHandler.showSettingsAlert();
}
}
// @NonNull
// @Override
// public ShoppingViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
// View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_menu_shopping_category_tourism, viewGroup, false);
// return new ShoppingViewHolder(view);
// }
};
educationFirebaseAdapter.notifyDataSetChanged();
rvEducationList.setAdapter(educationFirebaseAdapter);
}
}
private boolean havePermission() {
if (Build.VERSION.SDK_INT >= 23) {
permissionHandler = PermissionHandler.getInstance(this);
if (permissionHandler.isAllPermissionAvailable()) {
Log.d("Pesan", "Permissions have done");
} else {
permissionHandler.setActivity(this);
permissionHandler.deniedPermission();
}
} else {
Toast.makeText(this, "Check your permission", Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int i : grantResults) {
if (i == PackageManager.PERMISSION_GRANTED) {
Log.d("test", "Permission" + Arrays.toString(permissions) + "Success");
} else {
//denied
permissionHandler.deniedPermission(Manifest.permission.ACCESS_FINE_LOCATION);
permissionHandler.deniedPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.petaMenu) {
startActivity(new Intent(EducationCategoryActivity.this, EducationCategoryMaps.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
shimmerFrameLayout.startShimmer();
if (educationFirebaseAdapter != null) {
educationFirebaseAdapter.startListening();
}
}
@Override
protected void onPause() {
super.onPause();
shimmerFrameLayout.stopShimmer();
if (educationFirebaseAdapter != null) {
educationFirebaseAdapter.stopListening();
}
}
@Override
protected void onStart() {
super.onStart();
if (educationFirebaseAdapter != null) {
educationFirebaseAdapter.startListening();
}
}
@Override
protected void onStop() {
super.onStop();
if (educationFirebaseAdapter != null) {
educationFirebaseAdapter.stopListening();
}
}
}
我希望数据存储在收藏夹中时的状态。我尝试添加代码datasnapshot.exist
,但无法更改“收藏夹”按钮的颜色。谢谢