The data is not going to the Database. I need to send snake name and scientific name to the cloud. I am using android studio and there is no compilation error in this code, but real time database is not updated.
This my code:-
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText Snakename;
Button upload;
Spinner SciName;
DatabaseReference databaseSnake;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Snakename=(EditText)findViewById(R.id.snakeName);
upload=(Button)findViewById(R.id.upload);
SciName=(Spinner)findViewById(R.id.scientificName);
databaseSnake= FirebaseDatabase.getInstance().getReference("snake");
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSnake();
}
});
}
private void addSnake(){
String snakename=Snakename.getText().toString().trim();
String SCINAME=SciName.getSelectedItem().toString();
if(!TextUtils.isEmpty(snakename)){
String id=databaseSnake.push().getKey();
Snake snake=new Snake(id,snakename,SCINAME);
databaseSnake.child(id).setValue(snake);
Toast.makeText(this,"Snake Added",Toast.LENGTH_LONG).show();;
}
else{
Toast.makeText(this,"You Should enter a name",Toast.LENGTH_LONG).show();
}
}
}
and my snake class:-
public class Snake {
String snakeID;
String snakeName;
String scientificName;
public Snake()
{
}
public Snake(String snakeID, String snakeName, String scientificName) {
this.snakeID = snakeID;
this.snakeName = snakeName;
this.scientificName = scientificName;
}
public String getSnakeID() {
return snakeID;
}
public String getSnakeName() {
return snakeName;
}
public String getScientificName() {
return scientificName;
}
}
How to check whether data is saved or not in database at runtime ??
try this,
if(!TextUtils.isEmpty(snakename)){
String id=databaseSnake.push().getKey();
Snake snake=new Snake(id,snakename,SCINAME);
Map userInfo = new HashMap();
userInfo.put(id, snake);
databaseSnake.updateChildren(userInfo);
Toast.makeText(this,"Snake Added",Toast.LENGTH_LONG).show();;
}
Hope it's help full.
as the offical documentation says :
If you'd like to know when your data has been committed, you can add a completion listener. Both setValue() and updateChildren() take an optional completion listener that is called when the write has been committed to the database. If the call was unsuccessful for some reason, the listener will be passed an error object indicating why the failure occurred:
databaseSnake.child(id).setValue(snake, new Firebase.CompletionListener() {
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
if (firebaseError != null) {
Toast.makeText(this,"Data could not be saved. " +
firebaseError.getMessage(),Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this,""Data saved successfully.",Toast.LENGTH_LONG).show();
}
}
});
Related
i am trying to get session stored variable in to a class. please see my actual code for class
public class GetDataAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String ImageUrlName;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
public String getImageUrlName() {
return ImageUrlName;
}
public void setImageUrlNamee(String Imageurlname) {
this.ImageUrlName = Imageurlname;
}
}
now i stored a value in session and i want to use in above code. Imageurlname is a url fetching from database. i want to add extra to the url. for example
this is my URl Getting form database http://example.com?id=
i stored user id in session so combining both url should be http://example.com?id=5
please see my modified code
public class GetDataAdapter extends AppCompatActivity {
public String ImageServerUrl;
public String ImageTitleName;
public String ImageUrlName;
private Session session;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new Session(GetDataAdapter.this);
HashMap<String, String> user = session.getUserDetails();
final String Uid = user.get(session.KEY_UID);
}
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
public String getImageUrlName() {
return ImageUrlName;
}
public void setImageUrlNamee(String Imageurlname) {
this.ImageUrlName = Imageurlname + Uid;
}
}
Uid is getting error. i hope you understand.
Looks like the problem is with persisting the userid in your case it is because of this.
Using instance variable to store user id which you can get only if you are getting the same object
Here are the solution(s):
Solution 1:
Using Static Variables
public class Example {
//this is the default value which will there stored before we are setting our actual userId
public static String USER_ID="DefaultId";
}
You can set and access the values this way.
Log.d("Default Value",Example.USER_ID);
//setting user id here
Example.USER_ID = "Manikanta Garikipati";
Log.d("Updated value",Example.USER_ID);
Solution 2: Using Shared preferences.
As you already know about this i would explain anyway.
Comment below if your problem is still not solved.
Here is the brief summary of the problem
The problem is not in shared preferences neither any storage.
Instead of creating a bean alone and setting the values to it , bean is extended with Activity etc.. which made things haywire..
Those who want the complete solution can go through the conversation in question.
Application class is there for you. use it and save your application level data, like this:
public class WhatEverApp extends Application
{
String mApplicationLevelVar = "Hello";
}
WhatEverApp will be the name of your app used in manifest.xml
Look here for detailed discussion on Application class.
I have an Android app in which I'm getting data from an API. Now I need to save this data from the API into an ActiveAndroid table.
So I've got stuck on that part.
Here is my table Partners(Active Android):
#Table(name = "Partners")
public class Partners extends Model {
#Column(name = "Name")
public String name;
public Partners() {}
public Partners(String name) {
this.name = name;
}
}
This is my POJO model:
public class Partner {
#Expose
#Column(name = "name")
private List<String> name;
public List<String> getName() {
return name;
}
public void setName(List<String> name) {
this.name = name;
}
}
And here is part of code where I'm getting data and trying to save it into ActiveAndroid table:
public class DownloadMain extends Fragment implements Callback<Partner> {
private static final String TAG = DownloadMain.class.getSimpleName();
private Button dloadPartners;
private Call callPartners;
public DownloadMain() {}
public DownloadMain newInstance() { return new DownloadMain(); }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_main, container, false);
dloadPartners = (Button) view.findViewById(R.id.downloadPartners);
dloadPartners.setOnClickListener(btnListener);
callPartners = APIHelper.getApiService().getPartners();
return view;
}
Button.OnClickListener btnListener = (new Button.OnClickListener() {
#Override
public void onClick(View v) {
callPartners.clone().enqueue(DownloadMain.this);
insertPartners();
}
});
#Override
public void onResponse(Call call, Response response) {
if(response.body() == null) {
try {
response.errorBody().string();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "No Partners!", Toast.LENGTH_SHORT).show();
} else {
List<String> partners = (List<String>) response.body();
Log.d(TAG, "Number of partners received: " + partners.size());
Toast.makeText(getActivity(), "Partners downloaded!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call call, Throwable t) {
}
private void insertPartners() {
ActiveAndroid.beginTransaction();
try {
for (int i = 0; i < 100; i++) {
Partner partner = new Partner();
partner.getName();
//partner.save();
}
ActiveAndroid.setTransactionSuccessful();
} finally {
ActiveAndroid.endTransaction();
}
}
}
The problem is how to save data I get from the API into table, so I need few tips and advice how to properly do that.
Question: I need some tips how to save data I get from web with retrofit into ActiveAndroid table?
please check my old weather app project, where I'f already used ActiveAndroid.
Here's one of my saving to database methods:
public void saveCityDataToDatabase(Forecast forecast) {
ActiveAndroid.beginTransaction();
try {
if (WeatherApplication.getCityList().size() > 0) {
new Delete().from(City.class).execute();
}
forecast.getCity().getCoord().save();
forecast.getCity().save();
ActiveAndroid.setTransactionSuccessful();
} finally {
ActiveAndroid.endTransaction();
}
Log.d("DATABASE", "WeatherApplication: " + WeatherApplication.getCityList());
} }
From: https://github.com/piotrek1543/LocalWeather/blob/master/app/src/main/java/com/piotr/localweather/repositories/WeatherDatabaseRepository.java
With ActiveAndroid is really easy to save Objects like Weather or Wind, but for some purposes you would need to use TypeSerializer. In your example you would use it to deserialize and save List<String>.
As you may notice from its Github page: https://github.com/pardom/ActiveAndroid
this libary is not maintained more than two years, so I can say clearly that is deprecated and not good to use to fresh projects. It may have many bugs. For me, implementation of this lib was a pretty painful.
Instead of ActiveAndroid, I would recommend you to use Realm, greenDao or ORMLite library to store your data.
Hope it would help
First of all create a parameterless constructor and call super in it.
public Partners() {
super();
}
then a partern.save() should suffice.
To retreive all the parterns you could do something like
List<Partner> partners = new Select().from(Partner.class).execute());
if you get the Partner object fro web via retrofit, probably you are using Gson to put the json in partner object. so you can make that object extending model, put a paramterless constructor like above and put a #Table annotation.
I am getting error while i build android chat app using firebase. When i send message then it's ok but after send the message i get error. Error look like as below.
04-17 15:21:54.242 12961-12961/learning.firebase.app.learningfirebase E/AndroidRuntime: FATAL EXCEPTION: main
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at learning.firebase.app.learningfirebase.FirebaseListAdapter$1.onChildAdded(FirebaseListAdapter.java:63)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class learning.firebase.app.learningfirebase.Chat]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader#42285cd8; line: 1, column: 2]
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:984)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:276)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
... 13 more
My MainActivity.java
public class MainActivity extends ListActivity {
private static final String FIREBASE_URL = "https://bohrachat.firebaseio.com/";
private String mUsername;
private Firebase mFirebaseRef;
private ValueEventListener mConnectedListener;
private ChatListAdapter mChatListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUsername();
setTitle("Chatting as " + mUsername);
// Setup our Firebase mFirebaseRef
mFirebaseRef = new Firebase(FIREBASE_URL).child("chat");
// Setup our input methods. Enter key on the keyboard or pushing the send button
EditText inputText = (EditText) findViewById(R.id.messageInput);
inputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
sendMessage();
}
return true;
}
});
findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
#Override
public void onStart() {
super.onStart();
// Setup our view and list adapter. Ensure it scrolls to the bottom as data changes
final ListView listView = getListView();
// Tell our list adapter that we only want 50 messages at a time
mChatListAdapter = new ChatListAdapter(mFirebaseRef.limit(50), this, R.layout.chat_message, mUsername);
listView.setAdapter(mChatListAdapter);
mChatListAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
listView.setSelection(mChatListAdapter.getCount() - 1);
}
});
// Finally, a little indication of connection status
mConnectedListener = mFirebaseRef.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean connected = (Boolean) dataSnapshot.getValue();
if (connected) {
Toast.makeText(MainActivity.this, "Connected to Firebase", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Disconnected from Firebase", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
// No-op
}
});
}
#Override
public void onStop() {
super.onStop();
mFirebaseRef.getRoot().child(".info/connected").removeEventListener(mConnectedListener);
mChatListAdapter.cleanup();
}
private void setupUsername() {
SharedPreferences prefs = getApplication().getSharedPreferences("ChatPrefs", 0);
mUsername = prefs.getString("username", null);
if (mUsername == null) {
Random r = new Random();
// Assign a random user name if we don't have one saved.
mUsername = "JavaUser" + r.nextInt(100000);
prefs.edit().putString("username", mUsername).commit();
}
}
private void sendMessage() {
EditText inputText = (EditText) findViewById(R.id.messageInput);
String input = inputText.getText().toString();
if (!input.equals("")) {
// Create our 'model', a Chat object
Chat chat = new Chat(input, mUsername,"Today : ");
// Create a new, auto-generated child of that chat location, and save our chat data there
mFirebaseRef.push().setValue(chat);
inputText.setText("");
Bundle b=new Bundle();
b.putString("mUsername",mUsername);
b.putString("mMessage",input);
Intent intent = new Intent();
intent.putExtras(b);
intent.setAction("learning.firebase.app.learningfirebase.CUSTUM_INTENT");
sendBroadcast(intent);
}
}
}
Chat.java
public class Chat {
private String message;
private String author;
private String datetime;
// Required default constructor for Firebase object mapping
#SuppressWarnings("unused")
Chat(String message, String author,String datetime) {
this.message = message;
this.author = author;
this.datetime=datetime;
}
public String getMessage() {
return message;
}
public String getAuthor() {
return author;
}
public String getDatetime() {
return datetime;
}
}
ChatListAdapter.java
public class ChatListAdapter extends FirebaseListAdapter<Chat> {
// The mUsername for this client. We use this to indicate which messages originated from this user
private String mUsername;
public ChatListAdapter(Query ref, Activity activity, int layout, String mUsername) {
super(ref, Chat.class, layout, activity);
this.mUsername = mUsername;
}
/**
* Bind an instance of the <code>Chat</code> class to our view. This method is called by <code>FirebaseListAdapter</code>
* when there is a data change, and we are given an instance of a View that corresponds to the layout that we passed
* to the constructor, as well as a single <code>Chat</code> instance that represents the current data to bind.
*
* #param view A view instance corresponding to the layout we passed to the constructor.
* #param chat An instance representing the current state of a chat message
*/
#Override
protected void populateView(View view, Chat chat) {
// Map a Chat object to an entry in our listview
String author = chat.getAuthor();
TextView authorText = (TextView) view.findViewById(R.id.author);
authorText.setText(author + ": ");
// If the message was sent by this user, color it differently
if (author != null && author.equals(mUsername)) {
authorText.setTextColor(Color.RED);
} else {
authorText.setTextColor(Color.BLUE);
}
((TextView) view.findViewById(R.id.message)).setText(chat.getMessage());
((TextView) view.findViewById(R.id.datetime)).setText(chat.getDatetime());
}
}
My Firebase screenshot
Please help me about this. I follow firebase github chat project. After I just add one value, means date time, I get this error.
tl;dr: make the Chat class static and add a parameterless/default constructor to it.
Minimal code that works in a single file (Main.java):
public class Main {
public static class Chat {
private String message;
private String author;
private String datetime;
// Required default constructor for Firebase object mapping
public Chat() {}
public Chat(String message, String author, String datetime) {
this.message = message;
this.author = author;
this.datetime = datetime;
}
public String getMessage() { return message; }
public String getAuthor() { return author; }
public String getDatetime() { return datetime; }
}
public static void main(String[] args) throws Exception {
Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/36675151/-KFaDuobfEA1FLslYZMM");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue(Chat.class));
}
public void onCancelled(FirebaseError error) {
}
});
Thread.sleep(10000);
}
}
The JSON data:
"-KFaDuobfEA1FLslYZMM": {
"author": "user73181",
"datetime": "today heyy",
"message": "xjcjcj"
}
The things that are different from your code:
I removed everything that has nothing to do with the error message. For example this is a Java program, not an Android program. That simple change removes thousands of potential problems. But since your problem remained, it means that the problem is not related to Android. This sort of isolating the problem makes it a lot easier to find the cause. It's typically known as a minimal, complete/compilable verifiable example.
I included everything into a single file. Not only does this makes it easier to copy/paste, it also means interaction between files cannot be the cause. In this case, it did mean I had to make the Chat class static, which is likely one cause of your problem.
I had to add a parameterless/default constructor, which is what Kato pointed you to on [your previous question]. (Failed to bounce to type, Chat example error when adding another value,) and what I told you to add. This is likely the second cause of your problem.
I included the JSON as text, instead of as an image. This means that you can now copy/paste my JSON to see if your problem stems from that (it doesn't btw). You can easily get your JSON by clicking the Export button in your Firebase dashboard. Doing so saves me from having to type it.
Firstly I would like to apologize for my poor English.
I just started my adventure with android studio and followed some tutorials and I have a question about one of them. I was looking in many places for this answer but I found none that would satisfy my needs.
I created a chat app in android studio with FIREBASE as backend database but I would like to add some extra functionality to it. Namely remove item.
I’ll post my code here, can someone tell me how can I make it possible to delete Item that I pressed on from the FirebaseListAdapter.
MainActivity:
public class MainActivity extends ListActivity {
private Firebase mFirebaseRef;
FirebaseListAdapter<ChatMessage> mListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.getDefaultConfig().setPersistenceEnabled(true);
Firebase.setAndroidContext(this);
mFirebaseRef = new Firebase("https://shining-heat-1471.firebaseio.com");
final EditText textEdit = (EditText) this.findViewById(R.id.text_edit);
Button sendButton = (Button) this.findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = textEdit.getText().toString();
ChatMessage message = new ChatMessage("Android User", text);
mFirebaseRef.push().setValue(message);
textEdit.setText("");
}
});
mListAdapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class,
android.R.layout.two_line_list_item, mFirebaseRef) {
#Override
protected void populateView(View v, ChatMessage model) {
((TextView)v.findViewById(android.R.id.text1)).setText(model.getName());
((TextView)v.findViewById(android.R.id.text2)).setText(model.getText());
}
};
setListAdapter(mListAdapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
mListAdapter.cleanup();
}
ChatMessage:
public class ChatMessage {
private String name;
private String text;
public ChatMessage() {
// necessary for Firebase's deserializer
}
public ChatMessage(String name, String text) {
this.name = name;
this.text = text;
}
public String getName() { return name; }
public String getText() { return text; }
}
I'll leave it to you to figure out what item the user clicked on (but this might be a good start).
Once you know the position of the item the user clicked on, you can remove it from Firebase easily with:
Firebase itemRef = adapter.getRef(position);
itemRef.removeValue();
This will remove the item from the database and from the list adapter.
I am having trouble retrieving a List from the Firebase. I have no trouble storing it, but as soon as I try to cast dataSnapshot.getValue() to ArrayList my app crashes, giving an exception:
HashMap cannot be casted to ArrayList
But when I tried to cast it to a HashMap, it also crashes, giving exception:
ArrayList can't be casted to hashmap
Need help please! Here is the code that is creating the problem:
Fire.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<TaskDes> td = (ArrayList<TaskDes>) dataSnapshot.getValue()
notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
I want to retrieve all the data in the Firebase as one List. The class TaskDes contains three fields:
class TaskDes { // definition
boolean done
String taskDescription
String taskTitle
}
You need to create a GenericTypeIndicator object to pass as DataSnapshot.getValue() parameter.
Code:
GenericTypeIndicator<List<String>> t = new GenericTypeIndicator<List<String>>() {};
List<String> yourStringArray = dataSnapshot.getValue(t);
Your Model
public class TaskDes {
private boolean done;
private String taskDescription;
private String taskTitle;
public TaskDes() {
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getTaskTitle() {
return taskTitle;
}
public void setTaskTitle(String taskTitle) {
this.taskTitle = taskTitle;
}
}
You need to create a GenericTypeIndicator object to pass as DataSnapshot.getValue() parameter.
In Activity
private static final String TAG=MainActivity.class.getSimpleName();
private FirebaseDatabase database;
private DatabaseReference myRef=null;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database=FirebaseDatabase.getInstance();
myRef=database.getReference("ADD_YOUR_REFERECE");
myRef.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
/* This method is called once with the initial value and again whenever data at this location is updated.*/
long value=dataSnapshot.getChildrenCount();
Log.d(TAG,"no of children: "+value);
GenericTypeIndicator<List<TaskDes>> genericTypeIndicator =new GenericTypeIndicator<List<TaskDes>>(){};
List<TaskDes> taskDesList=dataSnapshot.getValue(genericTypeIndicator);
for(int i=0;i<taskDesList.size();i++){
Toast.makeText(MainActivity.this,"TaskTitle = "+taskDesList.get(i).getTaskTitle(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError error){
// Failed to read value
Log.w(TAG,"Failed to read value.",error.toException());
}
});
}
Make another item that contains a list for your item:
This is your item:
class TaskDes { // definition
boolean done
String taskDescription
String taskTitle
}
This is the list item
class TaskDesList { // definition
private ArreyList<TaskDes> yourlist
}
public TaskDesList(){
}
public ArrayList<TaskDes> getYourlist() {
return yourlist;
}
and when calling an EventListener
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
yourlist.clear();
taskDesList=dataSnapshot.getValue(TaskDesList.class);
if (taskDesList!=null) {
yourlist= taskDesList.getYourlist();
}
}
and now "yourlist" is a list that contains all of your "TaskDes" items
A bit late, but in case any one else needs this.
IF the list is inside another object.
The object
public class Question {
public Date date;
public String questionNumber;
public String questionText;
public QuestionType questionType;
public String multipleSelection1;
public String multipleSelection2;
public String multipleSelection3;
public Question() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
}
Then to get your array of question objects
GenericTypeIndicator<List<Question>> t = new GenericTypeIndicator<List<Question>>() {};
List<Question> questionList = dataSnapshot.getValue(t);
Apparently, the GenericTypeIndicator doesn't work for all List objects particularly when the object contains none primitive types like maps. So, if it didn't work for your use case as it didn't for me, try this alternate solution:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<TaskDes> tDlist = new ArrayList<>();
for (DataSnapshot d: dataSnapshot.getChildren()){
TaskDes tD = d.getValue(TaskDes.class);
tDlist.add(tD);
}
notifyDataSetChanged();
}
As mentioned in the previous answers make sure your class( like TaskDes in this case) has a public constructor which is empty so the getValue method can deserialize correctly to your java class.