I managed to get data from the Firebase Database and show it in an alphabetical order in my ListView.
Now I want to show the value from my database, if I click on an item in the ListView. As an example in my database it says "BB" as a name and the value is "Bye, bye".
So after an onClick event in the ListView a Toast message should show the value. How can I do this?
HereĀ“s my database:
To show the value after you click on an item:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final String selectedFromList = (String) list.getItemAtPosition(position);
ref.orderByChild(selectedFromList).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String retrievedValue=dataSnapshot.child(selectedFromList).getValue().toString();
Toast.makeText(activity_name.this, "Value: "+retrievedValue, Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Assuming you have a listview with the following:
Afk
MFG
After clicking on an item, get the item at that postion and use it in a query orderByChild and retrieve it's value.
The sample code 'Peter Haddad' provided in his answer basically works fine... IF you design your database in a better way I did back then.
If you use his code, you get the value of the database entry (so the text on the right side in the console database, but I wanted to get the left one.
I recommend using a structure like in the Firebase Docs about Structuring.
It could look something like this:
Here are two posts about searching and querying those kind of databases:
How to do a simple search in string in Firebase database?
Query based on multiple where clauses in Firebase
If you anyways want to do it in the way I tried, it`s possible:
In the sample code from 'Peter Haddad' simply replace dataSnapshot.child(selectedFromList).getValue().toString() with dataSnapshot.child(selectedFromList).getKey().toString().
The key represents the text on the left side of the console database structure.
Related
I'm not using FirebaseAdapter or any Firebase-UI dependency, I have made this completly native for now, but I'm getting a problem at this line trying to pass extras:
mRootDatabase = getAdapter(mContext).getItem(position);
Required DatabaseReference , Found UserPojo
public void clickListItems(ListView listView,final DatabaseReference mRootDatabase) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(mContext, "Clicked: " + getmList().get(position), Toast.LENGTH_SHORT).show();
mRootDatabase = getAdapter(mContext).getItem(position);
Intent intent = new Intent(mContext, UserEdit.class);
intent.putExtra("uid", mRootDatabase.getKey());
intent.putExtra("Name",getAdapter(mContext).getItem(position).getName());
intent.putExtra("Email", getAdapter(mContext).getItem(position).getEmail());
intent.putExtra("Pay", getAdapter(mContext).getItem(position).getPay());
intent.putExtra("LastCon", getAdapter(mContext).getItem(position).getLastCon());
intent.putExtra("FirstCon", getAdapter(mContext).getItem(position).getFirstCon());
mContext.startActivity(intent);
}
});
}
In FirebaseListAdapter you can use getRef() in order to do this faster, but im wondering how to approach the same without it because my app does not have implemented any FirebaseAdapters , and I dont want to redo all my code again
Edit:
This is how I got my adapter
public ArrayAdapter<UserPojo> getAdapter(Context adapterContext) {
return new ArrayAdapter<UserPojo>(adapterContext,android.R.layout.simple_list_item_1,getmList());
}
Thanks!
To solve this, you need to change the following line of code:
mRootDatabase = getAdapter(mContext).getItem(position);
to
mRootDatabase = adapter.getRef(position);
In which adapter variable is the actual adapter that you are using to display the data.
Edit:
You cannot use getRef() method, unless you are using Firebase-UI library. You cannot get the DatabaseReference object from the ArrayAdapter object. None of the methods inside this class return a DatabaseReference object. The only way in which you can achieve this is to use Firebase-UI library.
It looks like you're trying to assign a Pojo to a Database Reference, instead you would need to assign it to the actual pojo and reference it that way
Something like this
UserPojo User = adapter.getItem(position);
I have a app in building proccess in some where i need to get data from FirebaseDatabase and show them in custom list view here my code part of it for onDataChange method
myDatabase=FirebaseDatabase.getInstance();
myRef= myDatabase.getReference().child("TvSeries");
myAuth = FirebaseAuth.getInstance();
myUser = myAuth.getCurrentUser();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot currentData : dataSnapshot.getChildren()){
if(currentData.child("tCategory").child("tPrimary").getValue().toString().equals("Aksiyon")){ }
selectedCategoryList.add(new DataForRow(currentData.getKey(),
currentData.child("tCategory").child("tPrimary").getValue().toString(),
currentData.child("tReleaseDate").getValue().toString()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Integer size =selectedCategoryList.size();
Log.d("Size:", size.toString());
When i put in breakpoint onDataChange method it works but otherwise it didnt any suggestion is very helpful. Have a nice day all.
Your selectedCategoryList list is always empty because onDataChange() method has an asynchronous behaviour which means that is called even before you are try to add those objects of DataForRow class to the list. A quick solve for this problem would be to declare and use your selectedCategoryList list only inside the onDataChange() method or if you want to use it outside, you need to create your own callback and for that, I recommend you see the last part of my answer from this post.
Firebase works asynchronously. You probably got the data from firebase after you program executed the line with Log. As Tristan mentioned, if you put your Log inside of the listener, it will work
I have custom adapter and an ArrayList<String> called groceries containing whatever user puts there.
This is my method saving the listView whenever the user puts something there or deletes:
public void saveGroceriesList() {
sharedPreferences = getContext().getSharedPreferences("com.me.application", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(groceries);
sharedPreferences.edit().putStringSet("Groceries", set).apply();
}
And here I set text strikethrough and change color onClick for listView:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
list_content = (TextView) view.findViewById(R.id.list_content);
if (!isChecked){
isChecked = true;
list_content.setPaintFlags(list_content.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
list_content.setTextColor(Color.parseColor("#a7a7a7"));
saveGroceriesList();
} else {
isChecked = false;
list_content.setPaintFlags(list_content.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
list_content.setTextColor(Color.parseColor("#000000"));
saveGroceriesList();
}
}
});
where list_content is my TextView for listView. The problem is, that the saveGroceriesList(); method wont save the color.
How can I save the color and strikethrough text with sharedPreferences?
I cannot see where are you adding color values into the Set, I think it is that problem
The best solution, by far IMHO, is to use a better data storage model. For example, you could use a SQLite database, with columns for the various properties (name, checked). Or, you could store your data in a JSON file, or an XML file, or a CSV file, or some other form of simple file.
If, for whatever reason, you are sure that you want to use SharedPreferences, you could:
Create a GroceryItem class that knows the name and checked state information
Hold an ArrayList<GroceryItem> that is your in-memory representation of your data model
Use Gson, Jackson, or some other JSON parser to convert the ArrayList<GroceryItem> to and from a String representation
Save the String in SharedPreferences
I have set up a basic entity class in my App Engine backend.
`#Entity`
`public class Club {`
`#Id`
`private int id;`
`private String clubName;`
`public Club() {`
`}`
`public int getId() {`
`return id;`
`}`
`public void setId(int id){
this.id =id;
}`
`public String getClubName() {
return clubName;
}`
`public void setClubName(String clubName) {
this.clubName = clubName;
}
}`
I have generated the cloud endpoint class and generated the cloud endpoint library.
I want to be able to populate the clubName from the datastore into a listview in android but not sure how to do this.
I'm trying to follow this https://developers.google.com/appengine/docs/java/endpoints/consume_android but so far I am unable to understand what to do. I'm new to this and would be greatful if anyone lead me in the right direction please.
You can use the below steps to achieve your objective:
1, As mentioned in the google doc on consuming cloud endpoints in android, ready your app by adding the required libraries and make API calls and then on getting data from your backend, you can store that data into a SQL database. You can do this step in the onpostexecute method of your asynch task
protected void onPostExecute(ScoreCollection scores) {
// Do something with the result. maybe the store the data to sqlite database
}
}
To know how to store data in SQLITe database please refer http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
http://www.vogella.com/articles/AndroidSQLite/article.html
2, Now query data from your SQLITE db into a cursor and then use a simplecursoradapter to display the data from cursor on a listview in your layout or activity screen
An approximate piece of code will have steps like below:
yourcursor = yourdatabase.query; //this is the cursor returned from querying your db
adapter = new SimpleCursorAdapter(this.getActivity(), R.layout.onerowinalistview, yourcursor, FROM, TO,0); // this connects the columns of your DB mentioned in FROM array to the elements in a row of your list as mentioned in TO array
ListView yourlistview = (ListView) view.findViewById(R.id.yourlistview);//this is the listview element in your screen layout
yourlistview.setAdapter(adapter); // setting the adapter to the listview
Hope this helps
I'm trying to figure out how to capture data from a form using EditText & Spinner's and insert it into a SQLite database. I am able to write the hard coded attributes but when I try to use R.id.fieldName it throws an error due to being an Integer vice a String.
public class PetAdd extends Activity {
DBAdapter db = new DBAdapter(this);
private OnClickListener btnPetAddListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
db.open();
long id;
id = db.insertPet("name", "type", "breed", "sex", "notes");
/**id = db.insertPet(R.id.petName, R.id.SpinnerPetType, R.id.petBreed, R.id.SpinnerPetGender, R.id.EditTextPetAddOptions);*/
db.close();
}
};
I'm still trying to learn all this stuff and my brain is fried from looking at a plethora of online tutorials, examples and Google documentation. If anyone can show me how to do this or direct me to a barney style tutorial that breaks it down for me to understand what's going on, it'd be greatly appreciated.
R.id.fieldName is a numeric reference to the item in your Activity (provided it's part of your layout).
You'll need to call findViewById(R.id.fieldName) to get a refererene to it. You'll also need to cast it to the correct type of view (in your case EditText) and then call getText().toString() on the whole thing.
Putting it all together...
EditText myField = (EditText)findViewById(R.id.userName); //assuming you have a field named userName in your XML
String userNameValue = myField.getText().toString();
Oh, and welcome to Stack... don't forget to mark answers as correct and up-vote them when they're helpful.
If you use R.id.name you are in fact using internally generated int that Android uses. You need the raw data your spinner has.
I suggest you play with getItem and getItemId in your Spinner. If you are using a SimpleAdapter you can expect to get the ID of your item with getItemId.
The implementation of getItem is up to you. I usually use BaseAdapter or in the case of Spinners, ArrayAdapter, which has several convenient methods.
And with the EditText you need to call getText() to the EditText.