I've got input city form, where it has 2 element, EditText for city name and Spinner a that has been populate Province Data from Firebase database. I want to make nodes structure in Firebase like this:
database{
provinces{
provinceId_1{
provinceId_1 : value
provinceName_1 : value
}
provinceId_2{
provinceId_2 : value
provinceName_2 : value
}
}
cities{
provinceId_1{
cityId_1{
cityId_1 : value
cityName_1 : value
}
cityId_2{
cityId_2 : value
cityName_2 : value
}
}
provinceId_2{
cityId_3{
cityId_3 : value
cityName_3 : value
}
}
}
}
But i do not know how to acquire provinces id and store it to cities table in firebase database, here's my code :
public class AddCityActivity extends AppCompatActivity {
private EditText inputCity;
private Button btnAddCity, btnClearText;
private MaterialSpinner spinnerProvinces;
private DatabaseReference databaseCities, databaseProvinces;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_city);
inputCity = (EditText) findViewById(R.id.add_city_edit_text);
btnAddCity = (Button) findViewById(R.id.action_add_city_button);
btnClearText = (Button) findViewById(R.id.action_clear_text_button);
spinnerProvinces = (MaterialSpinner) findViewById(R.id.provinceSpinner);
databaseProvinces = FirebaseDatabase.getInstance().getReference().child("provinces");
databaseProvinces.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> provinces = new ArrayList<String>();
for (DataSnapshot provinceSnapshot : dataSnapshot.getChildren()) {
String provinceName = provinceSnapshot.child("provinceName").getValue(String.class);
provinces.add(provinceName);
}
MaterialSpinner provincesSpinner = (MaterialSpinner) findViewById(R.id.provinceSpinner);
ArrayAdapter<String> provincesAdapter = new ArrayAdapter<String>(AddCityActivity.this, android.R.layout.simple_spinner_item, provinces); provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
provincesSpinner.setAdapter(provincesAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnClearText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputCity.setText("");
}
});
btnAddCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addCity();
}
});
}
private void addCity() {
String name = inputCity.getText().toString().trim();
databaseCities = FirebaseDatabase.getInstance().getReference("cities");
if (!TextUtils.isEmpty(name)) {
String id = databaseCities.push().getKey();
City city = new City(id, name);
databaseCities.child(id).setValue(city);
Toast.makeText(this, "City Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Enter City Name", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
startActivity(new Intent(AddCityActivity.this, LandingActivity.class));
finish();
}
}
Related
I am fetching data and adding it to List from firebase database.
Now i want to sort the list data based on time so that latest data will appear first on the list and then setting the updated list into my RecyclerView.Adapter. I have tried layoutmanager.setReverseLayout(true); and layoutmanager.setStackFromEnd(true); for reversing the RecyclerView but it always shows data from the middle and also I don't want to follow this method.
How can i do that.
public class HistoryActivity extends AppCompatActivity{
private String customerOrDriver, userId;
private String doctorId, patientId, pharmacyId, userDriverOrCustomer;
private Long timestamp;
private String name, service;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView mHistoryRecyclerView;
private RecyclerView.Adapter mHistoryAdapter;
private RecyclerView.LayoutManager mHistoryLayoutManager;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
customerOrDriver = getIntent().getExtras().getString("customerOrDriver");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(HistoryActivity.this);
userId = sharedPreferences.getString("UID","");
mHistoryRecyclerView = (RecyclerView) findViewById(R.id.historyRecyclerView);
mHistoryAdapter = new HistoryAdapter(getDataSetHistory(), HistoryActivity.this);
mHistoryLayoutManager = new LinearLayoutManager(HistoryActivity.this);
mHistoryRecyclerView.setLayoutManager(mHistoryLayoutManager);
mHistoryRecyclerView.setHasFixedSize(true);
/*// sort the recycler view to descending order
((LinearLayoutManager) mHistoryLayoutManager).setReverseLayout(true);
((LinearLayoutManager) mHistoryLayoutManager).setStackFromEnd(true);*/
mHistoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
mHistoryRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
mHistoryRecyclerView.setAdapter(mHistoryAdapter);
getUserHistoryIds();
}
private void getUserHistoryIds() {
//swipeRefreshLayout.setRefreshing(true);
DatabaseReference userHistoryDatabase = FirebaseDatabase.getInstance().getReference().child(Common.user_table).child(customerOrDriver).child(userId).child(Common.history_table);
userHistoryDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot history : dataSnapshot.getChildren()){
FetchRideInformation(history.getKey());
//swipeRefreshLayout.setRefreshing(false);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//swipeRefreshLayout.setRefreshing(false);
}
});
}
private void FetchRideInformation(String rideKey) {
DatabaseReference historyDatabase = FirebaseDatabase.getInstance().getReference().child(Common.history_table).child(rideKey);
historyDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String rideId = dataSnapshot.getKey();
timestamp = 0L;
for(DataSnapshot child : dataSnapshot.getChildren()){
if (child.getKey().equals("timestamp")){
timestamp = Long.valueOf(child.getValue().toString());
}
}
getRideInformation(rideId, timestamp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getRideInformation(final String rideId, final Long timestamp) {
DatabaseReference historyRideInfoDb = FirebaseDatabase.getInstance().getReference().child(Common.history_table).child(rideId);
historyRideInfoDb.addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getKey().equals("patient")) {
patientId = child.getValue().toString();
if (!patientId.equals(userId)) {
userDriverOrCustomer = "Doctors";
getUserInformation("Patients", patientId, rideId, timestamp);
}
}
else if (child.getKey().equals("patient")) {
patientId = child.getValue().toString();
if (!patientId.equals(userId)) {
userDriverOrCustomer = "Phamacys";
getUserInformation("Patients", patientId, rideId, timestamp);
}
}
if (child.getKey().equals("doctor")) {
doctorId = child.getValue().toString();
if (!doctorId.equals(userId)) {
userDriverOrCustomer = "Patients";
getUserInformation("Doctors", doctorId, rideId, timestamp);
}
}
else if (child.getKey().equals("pharmacy")) {
pharmacyId = child.getValue().toString();
if (!pharmacyId.equals(userId)) {
userDriverOrCustomer = "Patients";
getUserInformation("Pharmacys", pharmacyId, rideId, timestamp);
}
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getUserInformation(String otherUserDriverOrCustomer, String otherUserId, final String rideId, final Long timestamp) {
DatabaseReference mOtherUserDB = FirebaseDatabase.getInstance().getReference().child(Common.user_table).child(otherUserDriverOrCustomer).child(otherUserId);
mOtherUserDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if (map.get("name") != null) {
name = (map.get("name").toString());
}
if(map.get("service") == null)
{
service = (map.get("phone").toString());
}
else if (map.get("service") != null) {
service = (map.get("service").toString());
}
HistoryObject obj = new HistoryObject(rideId, name, service, getDate(timestamp));
resultsHistory.add(obj);
mHistoryAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private String getDate(Long time) {
Calendar cal = Calendar.getInstance(Locale.getDefault());
cal.setTimeInMillis(time*1000);
String date = DateFormat.format("MMMM dd yyyy, hh:mm a", cal).toString();
return date;
}
private ArrayList resultsHistory = new ArrayList<HistoryObject>();
private ArrayList<HistoryObject> getDataSetHistory() {
return resultsHistory;
}
}
Simply use myList.sort() then read it the way its needed like ascending or descending amd put it in the RecyclerView
You can sort your by following way
Her i just showed you an Student object but in your case you can check with datetime
Using Lambda expression: The Java 8 equivalent code using Lambda expression would look like this:
studentlist.sort((Student s1, Student s2)->s1.getName().compareTo(s2.getName()));
hi guys I would like as a title to read a single node created previously in my realtime firebase database, the database is thus created:
Users
---- UID1
---- Email:
---- Fullname:
---- Phone:
---- Coins:
---- UID2
---- Email:
---- Fullname:
---- Phone:
---- Coins:
so my database has a structure like the one shown and I need to read in onDataChange and then write the data in a TextView.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this method I used doesn't work as I can't get it to take the data I need.
I need to take the Coins value: within each different logged user, so each logged in user reads his data.
I the UID value that identifies each user, I created it based on his mobile number, so each user has his own mobile number that identifies him as UID.
this is all my code, as you can see the data that saves the UID is contained in mPhone, which was saved and then brought into this activity through the SharedPreferences.
public class PageCoins_Activity extends AppCompatActivity implements RewardedVideoAdListener {
private static final String TAG = MainActivity.class.getName();
private FirebaseAuth mAuth;
private AdView mBannerTop;
private AdView mBannerBot;
private RewardedVideoAd mRewardedVideoAd;
public double Coins;
double coinsOp = 0.00;
double coinsCl = 0.00;
double coinssum = 0.00;
Button mButton;
Button mPhonebtn;
TextView mCoinscounter;
TextView mCoins;
FirebaseDatabase mDatabase;
EditText mPhoneEdt;
TextView mPhone;
#Override
protected void onStart(){
super.onStart();
updateUI();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_coins_);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Utenti");
myRef.child("Rapp Coins %").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String coinsRapp = dataSnapshot.getValue(String.class);
mCoins.setText(coinsRapp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mAuth = FirebaseAuth.getInstance();
initFirebase();
//counter CRD
mCoinscounter = (TextView)findViewById(R.id.Textcoins);
mButton = (Button)findViewById(R.id.btn2);
mPhoneEdt = (EditText)findViewById(R.id.NumberPhEdt);
mPhone = (TextView) findViewById(R.id.NumberPhTxt);
mCoins = (TextView)findViewById(R.id.txtGen);
mPhonebtn = (Button)findViewById(R.id.buttonPhone);
//mPhoneEdt.setVisibility(View.GONE);
//mPhone.setVisibility(View.VISIBLE);
findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins Day %").setValue(mCoinscounter.getText().toString());
}
});
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
//Set Orientation Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Banner Top View Coins
mBannerTop = (AdView) findViewById(R.id.adViewTopcoins);
AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerTop.loadAd(adRequest);
// Banner Bot View Coins
mBannerBot = (AdView) findViewById(R.id.adViewBotcoins);
AdRequest adRequest1 = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
mBannerBot.loadAd(adRequest1);
getnumberprefs();
//ADMob Video
loadRewardedVideoAd();
}
private void getnumberprefs() {
SharedPreferences numb = getSharedPreferences(Register_Activity.NUMB, MODE_PRIVATE);
String numberphn = numb.getString(Register_Activity.KEY_NUMB,null);
mPhone.setText(numberphn);
}
//boolean changepgcoins = true;
public void changeNumber(View view) {
/*if (changepgcoins == true){
mPhoneEdt.setVisibility(View.GONE);
mPhone.setVisibility(View.VISIBLE);
changepgcoins = false;
}else{
mPhoneEdt.setVisibility(View.VISIBLE);
mPhone.setVisibility(View.GONE);
changepgcoins = true;
}*/
}
private void initFirebase() {
mDatabase = FirebaseDatabase.getInstance();
}
public void HomeClick(View view){
Intent intenthome = new Intent(this, MainActivity.class);
finish();
startActivity(intenthome);
}
public void displayCrd (double amount){
mCoinscounter.setText(String.format("%.2f", amount));
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
public void logout(View view) {
mAuth.signOut();
updateUI();
}
private void updateUI() {
FirebaseUser currentuser = mAuth.getCurrentUser();
if(currentuser == null){
Intent intTologin = new Intent(this, Login_Activity.class);
finish();
startActivity(intTologin);
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d(TAG, "Video Caricato");
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, " RAPp " + " COINS " + " : " + rewardItem.getAmount(), Toast.LENGTH_LONG).show();
Coins += rewardItem.getAmount();
displayCrd(Coins/40200*100);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Log.d(TAG, "Caricamento Fallito");
}
#Override
public void onRewardedVideoCompleted() {
loadRewardedVideoAd();
}
#Override
protected void onDestroy() {
if (!isEmpty(mCoins)){
String coinsopen = mCoins.getText().toString();
String coinscounter = mCoinscounter.getText().toString();
coinsOp = Double.parseDouble(String.format(coinsopen.replace(',', '.'), "%.2f"));
coinsCl = Double.parseDouble(String.format(coinscounter.replace(',', '.'), "%.2f"));
coinssum = (coinsOp + coinsCl);
mCoinscounter.setText(String.valueOf(coinssum));
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}else{
// Write a message to the database
DatabaseReference myRef = mDatabase.getReference();
myRef.child("Utenti").child(mPhone.getText().toString()).child("Rapp Coins %").setValue(mCoinscounter.getText().toString());
}
super.onDestroy();
}
private boolean isEmpty(TextView mCoins) {
String input = mCoins.getText().toString();
return input.length() == 0.00;
}
}
I really ask for help on the solution of this thing because it's the last thing I need to finish and I can't thank you.
{
"Utenti" : {
"3********4" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
"3********1" : {
"E-Mail" : "",
"Full Name" : "",
"Phone" : "",
"Rapp Coins %" : "",
"Rapp Coins Day %" : ""
},
}
}
this is my database so composed.
I am working on recommendation application I using firebase to store information about user.I have used checkboxes for health status information.
I want to save all the checkbox values I selected.but in my code if I check more then one checkbox it always save the last checkbox.
This is my code How can I fix it to store all checked values?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Toolbar toolbar =findViewById(R.id.toolbarotherpages);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
databaseUser = FirebaseDatabase.getInstance("https://bonappetit-808c5.firebaseio.com").getReference("users");
users = new ArrayList<>();
addusername= findViewById(R.id.editTextname);
addphone=findViewById(R.id.editTextphone2);
mFirstCheckBox=findViewById(R.id.cbox1);
mSecondCheckBox=findViewById(R.id.cbox2);
mThirdCheckBox=findViewById(R.id.cbox3);
addhealthstatus=findViewById(R.id.editTexthealthstatus);
btnsignup =findViewById(R.id.buttonsignup2);
btnsignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Signup dosignup = new Signup(); // this is the Asynctask
dosignup.execute("");
}
});
}
protected void onStart() {
super.onStart();
//attaching value event listener
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
users.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
users user = postSnapshot.getValue(users.class);
//adding artist to the list
users.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class Signup extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String username = addusername.getText().toString();
String phone = addphone.getText().toString();
String healthstatus = addhealthstatus.getText().toString();
#Override
protected String doInBackground(String... params) {
if (username.trim().equals("") || phone.trim().equals("")) {
z += "Please fill in all fields";
} else {
int count = 0;
for (users user2 : users) {
if (user2.getPhonenumber().equals(phone)) {
count = 1;
}
}
if (count == 0) {
try {
if(mFirstCheckBox.isChecked()) {
users user = new users(username, phone,"Diabetes");
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
if(mSecondCheckBox.isChecked()) {
users user = new users(username, phone, "pressure");
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
if(mThirdCheckBox.isChecked()) {
users user = new users(username, phone,
healthstatus);
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
z = "Account created";
isSuccess = true;
}
catch (Exception ex) {
z = "Mobile number was used";
isSuccess = false;
}
}
}
return z;
}
}
To get the selected checked values you can use Switch case following code
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkBox1:
....
break;
case R.id.checkBox2:
......
break;
case R.id.checkBox3:
......
break;`
The app is about making a simple survey with checkboxes. The checkbox values come from REST Api as list like ["option1", "option2"...]
I will post selected checkboxes as also a list. All set and working except for removing unselected items. How can I get and remove 'unselected' data from list?
(User may make changes) I tried with List and HashMap, couldn't make it. Thanks in advance!
public class MainActivity extends AppCompatActivity {
LinearLayout linear_checkbox;
List<String> answerList= new ArrayList<>();
List<String> checkedList = new ArrayList<>();
Map<String,String> map = new HashMap<>();
Button button_send;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
linear_checkbox = (LinearLayout)findViewById(R.id.linear_checkbox);
button_send= (Button)findViewById(R.id.button_send);
//
answerList.add("Photography");
answerList.add("Music");
answerList.add("Skateboard");
listChoices(cevapList);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(MainActivity.this, "LIST: "+"\n"+ checkedList.toString(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this, ""+map.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void listChoices(List<String> textList){
textList = answerList;
for(j=0; j<textList.size(); j++){
final CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(textList.get(j));
cb.setTextColor(Color.parseColor("#E7740D"));
linear_checkbox.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
Toast.makeText(MainActivity.this, ""+cb.getText()+" selected", Toast.LENGTH_SHORT).show();
String key = String.valueOf(j);
//map.put(key,cb.getText().toString());
secilenlerList.add(cb.getText().toString());
}else{
Toast.makeText(MainActivity.this, ""+cb.getText()+" unselected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Update your code its working fine. You didn't make changes when user unselect any check box item.
public class MainActivity extends AppCompatActivity {
LinearLayout linear_checkbox;
List<String> answerList = new ArrayList<>();
List<String> checkedList = new ArrayList<>();
Map<String, String> map = new HashMap<>();
Button button_send;
int j;
private ArrayList<String> secilenlerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
linear_checkbox = (LinearLayout) findViewById(R.id.linear_checkbox);
button_send = (Button) findViewById(R.id.button_send);
//
answerList.add("Photography");
answerList.add("Music");
answerList.add("Skateboard");
listChoices(answerList);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "LIST: " + "\n" + secilenlerList.toString(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this, ""+map.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void listChoices(List<String> textList) {
textList = answerList;
secilenlerList = new ArrayList<>();
for (j = 0; j < textList.size(); j++) {
final CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(textList.get(j));
cb.setTextColor(Color.parseColor("#E7740D"));
linear_checkbox.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
if (ischecked) {
Toast.makeText(MainActivity.this, "" + cb.getText() + " selected", Toast.LENGTH_SHORT).show();
String key = String.valueOf(j);
//map.put(key,cb.getText().toString());
if (!secilenlerList.contains(cb.getText().toString()))
secilenlerList.add(cb.getText().toString());
} else {
if (secilenlerList.contains(cb.getText().toString()))
secilenlerList.remove(cb.getText().toString());
Toast.makeText(MainActivity.this, "" + cb.getText() + " unselected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
I have implemented a FirebaseRecyclerAdapter to populate cities from the database in to the RecyclerView. After several fails to implement a search feature I am seeking for help. I would like to let users search for a particular city by typing the city's name (postName). The idea is to populate all of the available cities at the beginning and the desired city after its name is typed in the search field.
My code to populate the view is:
searchField = view.findViewById(R.id.search_field);
searchButton = view.findViewById(R.id.imageButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String search_field = searchField.getText().toString().trim();
initialiseScreen(view, search_field);
Toast.makeText(getContext(), search_field, Toast.LENGTH_SHORT).show();
}
});
String search_field = null;
initialiseScreen(view, search_field);
return view;
}
private void initialiseScreen(final View view, String searchText) {
Query postQuery = mDataRef.orderByChild("postName").startAt(searchText).endAt(searchText + "\uf8ff");
mDataRef.keepSynced(true);
recyclerView = view.findViewById(R.id.post_RV);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(mPostViewAdapter);
FirebaseRecyclerOptions postOptions = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(postQuery, Post.class).build();
mPostViewAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(postOptions) {
#Override
protected void onBindViewHolder(PostViewHolder holder, int position, final Post model) {
final String post_key = getRef(position).getKey();
holder.setPostCityImage(model.getImageURL());
holder.setPostCityName(model.getPostName());
holder.setLikeBtn(post_key);
//When is clicked once go to city fragment
holder.cityImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Add code here
Intent singlePostIntent = new Intent(getActivity(), CitiesActivity.class);
singlePostIntent.putExtra("blog_id", post_key);
startActivity(singlePostIntent);
}
});
//Likes button
holder.likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProccessLike = true;
String postId = model.getmUid();
mDatabaseLikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(mProccessLike) {
if (dataSnapshot.child(post_key).hasChild(current_user_id)) {
mDatabaseLikesRef.child(post_key).child(current_user_id).removeValue();
mProccessLike = false;
} else {
mDatabaseLikesRef.child(post_key).child(current_user_id).setValue("RandomValue");
mProccessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//
}
Btw it populates only one city if instead of String search_field = null; I write something like String search_field = "Calp, Spain";