Empty Row in Firebase UI with Condition? - android

I have a problem with Firebase when using FirebaseUI. It adds an unwanted empty row when the condition is not true.
I need to delete this Empty Row.
this is the image Show the problem :
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("*****");
FirebaseListAdapter<Opinions> firebaseListAdapter = new FirebaseListAdapter<Opinions>(this,Opinions.class,android.R.layout.two_line_list_item,databaseReference) {
#Override
protected void populateView(View v, Opinions model, int position) {
TextView textView1 = (TextView) v.findViewById(android.R.id.text1);
TextView textView2 = (TextView) v.findViewById(android.R.id.text2);
Typeface Myfont = Typeface.createFromAsset(getAssets(), "font/gernralfont.ttf");
textView1.setTypeface(Myfont);
textView2.setTypeface(Myfont);
textView2.setTextSize(17);
textView2.setTextColor(Color.parseColor("#6eaafc"));
textView1.setTextColor(Color.parseColor("#4d70a0"));
if (model.isApproval() == true)
{
textView1.setText( "\n" + model.getStu_name() + " / " + model.getStu_feild() + "\n" );
textView2.setText(model.getStu_comment() + "\n");
}
}
};
hilist.setAdapter(firebaseListAdapter);
How I can remove this empty line?

Your app is current reading all data at the location. But since you're only interested in showing data that is approved, you should only read those child nodes.
You can do this with a Firebase Database query, which you can then pass into the adapter instead of the current reference:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("*****");
Query query = databaseReference.orderByChild("approval").equalTo(true);
FirebaseListAdapter<Opinions> firebaseListAdapter =
new FirebaseListAdapter<Opinions>(this, Opinions.class,
android.R.layout.two_line_list_item, query) {
...

Related

How to sort an object from firebase?

Im getting an object from firebase, and there are two ways how i can get object
this one
text1
15.10.2021
text3
12.10.2021
text2
29.11.2021
text4
1.1.2022
or this one
{text = text1 , date = 15.10.2021}
{text = text3 , date = 12.10.2021}
{text = text2 , date = 29.11.2021}
{text = text4 , date = 1.1.2022}
I am need to sort this object by dates like that
text3 12.10.2021
text1 15.10.2021
text2 29.11.2021
text4 1.1.2022
I'm trying to add all into list but I don't know how to sort them.
in list it looks like this
[text1, 15.10.2021, text3, 12.10.2021, text2, 29.11.2021, text4, 1.1.2022]
Im doing that for RecyclerView, and initially im getting dates and strings from Firebase like that
List<String> reminder = new ArrayList<>();
List<String> date = new ArrayList<>();
dbf.child("Reminders").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
reminder.clear();
date.clear();
for(DataSnapshot child2 : snapshot.getChildren()) { // getting a data from DB to ArrayList for dropping into Adapter
for(DataSnapshot tChild : child2.getChildren()) {
if (tChild.getKey().equals("text")) {
reminder.add(tChild.getValue().toString());
rem = reminder.toArray(new String[reminder.size()]); // rem = String[]
}
if (tChild.getKey().equals("date")) {
date.add(tChild.getValue().toString());
dat = date.toArray(new String[date.size()]); // dat = String[]
}
}
mainRowAdapter rAdapter = new mainRowAdapter(MainActivity.this, rem,dat);
rv.setAdapter(rAdapter);
rv.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
and then in Adapter class im use method setText()
so, the question in the top
Your dates are stored as strings in a format that is unfortunately not chronologically sortable. If you want to sort on dates, I recommend storing them in ISO-8601 format, such as "2021-10-15" so that their lexicographical order matches their chronological order.
Once you have that format, you can retrieve the nodes from the database in the correct order with:
DatabaseReference reminders = dbf.child("Reminders");
Query remindersByDate = reminders.orderByChild("date");
remindersByDate.addValueEventListener(...
Also see:
Firebase sort by points depending on date
Firebase endAt() not working with date string?
Querying by range in firebase

Firebase on Android : DataSnapshot.getChildrenCount() is returning 0

This is my firebase realtime database :
This is my code :
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
EditText t1 = (EditText) findViewById(R.id.editText10);
final String s1 = t1.getText().toString();
mDatabase.child("users").orderByChild("name")
.equalTo(s1)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv2.setText(Long.toString(dataSnapshot.getChildrenCount()));
}
}
I am entering these values in EditText fields :
editText10 => Anupam Singh
dataSnapshot.getChildrenCount() should be 1 but it is coming to be 0.
What am I doing wrong?
In your database you have the following:
users
name_title_company_location
Therefore the attribute name_title_company_location is a direct child under nodeusers. When you are using orderByChild, you are not accessing that node.
What you need to do is add an id in the database:
users
id
name_title_company_location
Then your code will work.
Or you can change the code to the following, go one level up:
mDatabase.orderByChild("name_title_company_location").equalTo(...)
-the issue is in orderByChild.
-you have pass query and ask for single value event listener.
do as below :
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");
Query query = mDatabase.("name_title_company_location")
.equalTo(s1 + "_" + s2 + "_" + s3 + "_" + s4);
query.addSingleValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv2.setText(Long.toString(dataSnapshot.getChildrenCount()));
}
}
-it will return the data

Populating listview with FirebaseListAdapter in Android

I am using counter value for counting my ListView items. But when I am scrolling down and back scrolling up it still count value inside of my code and changes values.
This values should 1 and 2 instead of 7 and 8...
Here is my code
DatabaseReference myQuery = databaseReference.child("Tests").child(PIN).child("Questions");
FirebaseListAdapter<QuizStatistic_list> adapter = new FirebaseListAdapter<QuizStatistic_list>(this, QuizStatistic_list.class, R.layout.list_quiz_statistic, myQuery) {
#Override
protected void populateView(View v, QuizStatistic_list model, int position) {
TextView quizQuestion, questionNumber, ansA, ansB, ansC, ansD;
quizQuestion = (TextView) v.findViewById(R.id.textView_quizQuestion);
questionNumber = (TextView) v.findViewById(R.id.textView_questionNumber);
ansA = (TextView) v.findViewById(R.id.textView_ansA);
ansB = (TextView) v.findViewById(R.id.textView_ansB);
ansC = (TextView) v.findViewById(R.id.textView_ansC);
ansD = (TextView) v.findViewById(R.id.textView_ansD);
quizQuestion.setText(model.getQuestion());
questionNumber.setText(counter.toString());
ansA.setText("A: " + model.getAnswerA());
ansB.setText("B: " + model.getAnswerB());
ansC.setText("C: " + model.getAnswerC());
ansD.setText("D: " + model.getAnswerD());
//This value counts listview items
counter++;
}
};
questionsList.setAdapter(adapter);
use position instead of counter.!
questionNumber.setText(""+position+1);
position is index number of your array list .!
so it will start from 0 by adding one it will show your desired result first number will be index 0+1=1;
maybe it will help u like

Sorting the contents of ArrayAdapter or ArrayList

I am working on android project and am making using of a ListView that retrieves data from the SQLite database.
I am making a dataset using an ArrayList and then adding this ArrayList into an ArrayAdapter.
When the data is being retrieved from the database, I am telling SQLite to do the sorting so everything is in alphabetical order when it is added into the ListView. At certain times, the information will be added dynamically to to the ListView without it requiring to re-fetch everythin from the database again. However, I want to keep everything in alphabetical order.
How would I do this, do I sort the DataSet and then call the notifyDataSet Changes or do I do the sort directly on the ArrayAdapter. I've looked into performing the sort on the ArrayAdapter but this wants an argument that uses a Comparator but not sure what this is and can't find any working examples that may be of any help for what I want to achieve.
Below is the code that populates the array and sets the list adapter
ArrayList<Spanned> passwords = managePasswordList.getPasswordList();
if (passwords != null && passwords.size() > 0)
{
passwordArrayAdapter = new ArrayAdapter<Spanned>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_activated_1, passwords);
setListAdapter(passwordArrayAdapter);
myListView.setTextFilterEnabled(true);
txtNoRecords.setVisibility(View.GONE);
}
else
{
txtNoRecords.setVisibility(View.VISIBLE);
}
I am then adding data to the dataset and refreshing the list view using the following
String company = Encryption.decrypt(passwords.get(i).company);
String username = Encryption.decrypt(passwords.get(i).username);
details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
passwordArrayAdapter.notifyDataSetChanged();
Thanks for any help you can provide.
UPDATE 1
I've tried doing what Nick Bradbury suggested but I am having a problem with the comparator. I have the following code but I don't know where to go from here.
SQLiteDatabase myDb = null;
Cursor cursor = null;
ArrayList<Spanned> passwords = new ArrayList<Spanned>();
try
{
myDb = context.openOrCreateDatabase("PasswordManager", Context.MODE_PRIVATE, null);
cursor = myDb.rawQuery("SELECT * FROM password ASC", null);
while (cursor.moveToNext())
{
final String company = Encryption.decrypt(cursor.getString(2));
final String username = Encryption.decrypt(cursor.getString(4));
Spanned details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
Collections.sort(passwords, new Comparator<Spanned>() {
public int compare(Spanned lhs, Spanned rhs) {
return 0;
}
});
}
}
catch (SQLiteException ex)
{
common.showBasicAlertDialog("Unfortunately something has gone wrong.\n\nWe will fix this as soon as we can", false);
Log.e("Database Error", ex.toString());
return null;
}
In the return statement I have no idea what to do, I've tried return lhs.compareTo but the lhs and rhs variables don't have the compareTo function so I have not got a clue what to do.
Here's a simple example of sorting an ArrayList using Comparator. In this example, the ArrayList is defined as:
public class StatusList extends ArrayList<Status>
A sort routine for this ArrayList could look like this:
public void sort() {
Collections.sort(this, new Comparator<Status>() {
#Override
public int compare(Status item1, Status item2) {
return item2.getDate().compareTo(item1.getDate());
}
});
}
Replace <Status> with whatever object your ArrayList contains, then change the comparison to compare the values of the object you wish to sort by.

Set text color of a textview in a listview item? (Android)

Been scouring this site for any answers, no real easy solution I've found for this. I am creating an Android application that uses an sqlite database to look up a hex value by the color name typed in. I am dynamically creating a TextView, setting its text and text color, then adding it to the ArrayList, then the ArrayList is being added to the ListView. The text shows up in the ListView, but its color property is not being set. I'd really like to find a way to get the text color set for each listview item. Here is my code thus far:
Class Variables:
private ListView lsvHexList;
private ArrayList<String> hexList;
private ArrayAdapter adp;
In onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.color2hex);
lsvHexList = (ListView) findViewById(R.id.lsvHexList);
hexList = new ArrayList<String>();
In my Button Handler:
public void btnGetHexValueHandler(View view) {
// Open a connection to the database
db.openDatabase();
// Setup a string for the color name
String colorNameText = editTextColorName.getText().toString();
// Get all records
Cursor c = db.getAllColors();
c.moveToFirst(); // move to the first position of the results
// Cursor 'c' now contains all the hex values
while(c.isAfterLast() == false) {
// Check database if color name matches any records
if(c.getString(1).contains(colorNameText)) {
// Convert hex value to string
String hexValue = c.getString(0);
String colorName = c.getString(1);
// Create a new textview for the hex value
TextView tv = new TextView(this);
tv.setId((int) System.currentTimeMillis());
tv.setText(hexValue + " - " + colorName);
tv.setTextColor(Color.parseColor(hexValue));
hexList.add((String) tv.getText());
} // end if
// Move to the next result
c.moveToNext();
} // End while
adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexList);
lsvHexList.setAdapter(adp);
db.close(); // close the connection
}
You are not adding the created TextView to the list at all, you just add the String to the list, thus it doesn't matter what method you called on the TextView:
if(c.getString(1).contains(colorNameText)) {
// ...
TextView tv = new TextView(this);
tv.setId((int) System.currentTimeMillis());
tv.setText(hexValue + " - " + colorName);
tv.setTextColor(Color.parseColor(hexValue));
hexList.add((String) tv.getText()); // apend only the text to the list
// !!!!!!!!!!!!!! lost the TextView !!!!!!!!!!!!!!!!
}
What you need to do is to store the colors in another array, and when creating the actual list view, set the color of each TextView according to the appropriate value in the list.
To do that, you will need to extend ArrayAdapter and add the logic of the TextView color inside.

Categories

Resources