I am testing Firebase on two items. I am hoping to update a recyclerview to add an item, with the firebase onChildAdded() listener prompting the recyclerview to update. Here is the code where I write to Firebase:
mSubmitPollCreation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: Need to determine if this is proper epoch - i.e. does it account for time zones
Calendar c = Calendar.getInstance();
final String epochTime = String.valueOf(c.getTimeInMillis());
//TODO: Need to check if poll requirements are added, i.e. Question, Answer, ......
//check if image has been loaded first
if (resultImageURL != null){
mBaseRef.child("Polls").child(epochTime).child("Image_URL").setValue(resultImageURL);
} else {
Toast.makeText(getApplicationContext(),getResources().getString(R.string.no_image_selected),Toast.LENGTH_LONG).show();
return;
}
//Add Answer Counter defaulted to 0
Map<String, Object> pollAnswerCounter = new HashMap<String, Object>();
pollAnswerCounter.put("Vote_Count", 0);
mBaseRef.child("Polls").child(epochTime).updateChildren(pollAnswerCounter);
//Add Question
Map<String, Object> pollQuestion = new HashMap<String, Object>();
pollQuestion.put("Question", mCreatePollQuestion.getText().toString());
mBaseRef.child("Polls").child(epochTime).updateChildren(pollQuestion);
if (mNumberOfPollAnswersCreatedByUser > 5){
Toast.makeText(getApplicationContext(),getResources().getText(R.string.poll_answers_greater_than_five),Toast.LENGTH_LONG).show();
mNumberOfPollAnswersCreatedByUser = 5;
}
//add answers to Firebase
for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++){
EditText editText = (EditText) mEditTextAnswerLayout.findViewWithTag(getResources().getString(R.string.created_answer_editText_id)+String.valueOf(i+1));
String editTextInputForAnswer = String.valueOf(editText.getText());
final String answerLabel = "Answer";
Map<String, Object> answerChoice = new HashMap<String, Object>();
answerChoice.put(answerLabel, editTextInputForAnswer);
mBaseRef.child("Polls").child(epochTime).child("Answers").child(String.valueOf(i+1)).updateChildren(pollAnswerCounter);
mBaseRef.child("Polls").child(epochTime).child("Answers").child(String.valueOf(i+1)).updateChildren(answerChoice);
Toast.makeText(getApplicationContext(),editTextInputForAnswer,Toast.LENGTH_SHORT).show();
}
Intent toHomeActivity = new Intent(CreateActivity.this, HomeActivity.class);
toHomeActivity.putExtra("viewpager_position", 2);
startActivity(toHomeActivity);
}
});
Here is the code, in a separate fragment, that I use to retrieve the data from Firebase:
#Override
public void onStart() {
super.onStart();
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String newPollEpoch = dataSnapshot.getKey();
Log.v("Child_Added", "The new child is " + newPollEpoch);
String newPollImageURL = dataSnapshot.child(IMAGE_URL).getValue().toString();
String newPollQuestion = dataSnapshot.child(QUESTION_STRING).getValue().toString();
mNewPollsAray.add(0, new Poll(newPollQuestion, newPollImageURL, newPollEpoch));
mNewPollsAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mPollsRef.addChildEventListener(mChildEventListener);
}
#Override
public void onStop() {
super.onStop();
mPollsRef.removeEventListener(mChildEventListener);
}
And here is the error. It is quite odd, as the error is prompting on the "String newPollQuestion." I use the exact same method to write the "newPollImageURL" to Firebase, and that object is not null. Also, there are 2 devices, A and B. A creates and writes the item to Firebase, and then reads it fine. B is the device that is displaying the following:
12-03 16:21:20.255 21043-21043/com.troychuinard.fanpolls E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.troychuinard.fanpolls, PID: 21043
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.troychuinard.fanpolls.Fragment.NewFragment$1.onChildAdded(NewFragment.java:159)
at com.google.android.gms.internal.zzaip.zza(Unknown Source)
at com.google.android.gms.internal.zzakp.zzcxi(Unknown Source)
at com.google.android.gms.internal.zzaks$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
--------- beginning of system
I do not understand why, but changing:
String newPollQuestion = dataSnapshot.child(QUESTION_STRING).getValue.toString;
to:
String newPollQuestion = dataSnapshot.child(QUESTION_STRING).getValue(String.class);
Successfully removed the NullPointer. Any idea why?
Related
I am trying to get url from text obtained from firebase data base and pass to another actvity and play it in videoview,
in my adapter
holder.animPlayer.setText(mAnmList.get(position).getVideourl());
in my firstActivity
private void data() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference smsRef = database.getReference("Movies");
smsRef.keepSynced(true);
smsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot newsSnapshot : dataSnapshot.getChildren()) {
TopItems item = newsSnapshot.getValue(TopItems.class);
mSmsList.add(item);
}
mSmsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onMovieClick(AnimationItem animationItem, ImageView animImage) {
final String videoUrl = animationItem.getVideourl();
Intent intentAnimation = new Intent(MainActivity.this, MovieDetails.class);
//putextra
intentAnimation.putExtra("Video", videoUrl);
}
in my secondActivity
moviePlayer = findViewById(R.id.player_view);
Bundle b = getIntent().getExtras();
String id = b.getString("Video");
moviePlayer.setVideoPath(id);
ProgressBar progressBar = new ProgressBar(MovieDetails.this);
MediaController mediaController = new MediaController(MovieDetails.this);
mediaController.setAnchorView(moviePlayer);
moviePlayer.setMediaController(mediaController);
moviePlayer.requestFocus();
moviePlayer.start();
in AnimationItem
private String videourl;
public AnimationItem( String videourl) {
this.videourl = videourl;
}
public AnimationItem() {
}
public String getVideourl() {
return videourl;
}
public void setVideourl(Uri videourl) {
this.videourl = String.valueOf(videourl);
}
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.smschecker, PID: 24016
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.smschecker/com.example.smschecker.MovieDetails}:
java.lang.NullPointerException: uriString
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2865)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2955)
at android.app.ActivityThread.-wrap12(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6719)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:449)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.(Uri.java:476)
at android.net.Uri$StringUri.(Unknown Source:0)
at android.net.Uri.parse(Uri.java:438)
at android.widget.VideoView.setVideoPath(VideoView.java:248)
at com.example.smschecker.MovieDetails.iniViews(MovieDetails.java:131)
at com.example.smschecker.MovieDetails.onCreate(MovieDetails.java:95)
it crashes when i start secondActivity, help
In MovieDetails activity, change from moviePlayer.setVideoPath(id); to moviePlayer.setVideoPath(Uri.parse(id));
I want to get list of LatLng from Firebase database. Previously, I've insert Polygon list by this code, mMarkerPoints.add(new LatLng(latitude, longitude)); and by this databaseReference.child("Area").child(pushId).child("region").setValue(mMarkerPoints); the databse sturcture as,
Now, I want to get this mMarkerPoints from database. for this, I wrote code, List<LatLng> areaRegion = (ArrayList) dataSnapshot.child(key).child("region").getValue();, this code give me exception. How to get this list?
code:
databaseReference.child("Area").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String key = dataSnapshot1.child(dataSnapshot1.getKey()).getKey();
String areaName = dataSnapshot.child(key).child("name").getValue(String.class);
List<LatLng> areaRegion = (ArrayList<LatLng>) dataSnapshot.child(key).child("region").getValue();
for(int i = 0; i<values.size();i++) {
Log.d("sdfljdjw", values.get(i));
}
Little bit solution:
i got this result {longitude=71.43064320087433, latitude=32.392359285468686} by this code:
Object value = dataSnapshot.child(key).child("region").getValue();
if(value instanceof List) {
List<Object> sdfsd = (List<Object>) value;
for(int i = 0; i<sdfsd.size();i++) {
Log.d("sdfljdjw", sdfsd.get(i)+"");
}
}
else {
Log.d("sdfljdjw", "no");
}
now how to convert this values to LatLng object?
10-10 14:20:30.539
11935-11935/com.example.salesman.salesmantrackingsystem
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.google.android.gms.maps.model.LatLng
at com.example.salesman.salesmantrackingsystem.LoginActivity$1$1$1$1.onDataChange(LoginActivity.java:154)
at com.google.android.gms.internal.zzegf.zza(Unknown Source)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5086)
At a guess (untested), replace:
List<LatLng> areaRegion = (ArrayList<LatLng>) dataSnapshot.child(key).child("region").getValue();
with something like:
List<LatLng> areaRegion = new ArrayList<>();
List<Object> locations = (List<Object>) dataSnapshot.child(key).child("region").getValue();
for (Object locationObj : locations) {
Map<String, Object> location = (Map<String, Object>) locationObj;
LatLng latLng = new LatLng((Double) location.get("latitude")), (Double) location.get("longitude"));
areaRegion.add(latLng);
}
Try something like this
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
List<Object> values = td.values();
2 examples: first example read one object (defined key "clave2") from hashmap( String,Alumno) and second example read all objects from hashmap(String,Alumno) (valid for HashMap/List)
DatabaseReference myRefalumnos1 = database.getReference("alumnoshashmap");
myRefalumnos1.child("clave2").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.
Alumno value = dataSnapshot.getValue(Alumno.class);
System.out.println(value.toString());
Log.i( "firebase1", value.toString());
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.i( "firebase1", String.valueOf(error.toException()));
}
});
DatabaseReference myRefalumnos2 = database.getReference("alumnoshashmap");
myRefalumnos2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<String> keys = new ArrayList<String>();
List<Alumno> alumnos = new ArrayList<Alumno>();
for (DataSnapshot keynode : snapshot.getChildren()) {
keys.add(keynode.getKey());
alumnos.add(keynode.getValue(Alumno.class));
}
for (String k : keys) {
System.out.println(k);
Log.i("firebase1", "clave leida " + k);
}
for (Alumno a : alumnos) {
System.out.println(a.toString());
Log.i("firebase1", "alumno leido " + a.toString());
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.i( "firebase1", String.valueOf(error.toException()));
}
});
** SOLVED **** SOLUTION IN BELOW POST ******* SOLUTION IN BELOW POST ******* **
Classmate's i get a headcache to how resolve to remove duplicate data in a listview with firebase. I need only 1 item data to show in listview.
Showing to example in screen shot
Actual Code:
ArrayList<ShowCliente> myList = new ArrayList<>();
final ArrayAdapter<ShowCliente> arrayAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1, myList);
newListView.setAdapter(arrayAdapter);
gDatabase.child("cliente").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ShowCliente show = dataSnapshot.getValue(ShowCliente.class);
myList.add(show);
//myList.clear();
//*********************************
arrayAdapter.notifyDataSetChanged();
checkEmpty();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Last trying code: This my attemps on this day to resolve this problem, any Don't work, post it to you knowledge :(
//*************************************23/03/2018 **** **************** ATTEMP 1
//VARIABLES
ArrayList<ShowCliente> myList = new ArrayList<>();
List<ShowCliente> myShow = new ArrayList<>();
ArrayList<ShowCliente> mList1 = new ArrayList<>(new HashSet<ShowCliente>(myList));
//HashSet<ShowCliente> myHash = new HashSet<>();
//LEE TODOS DATOS DE LOS CHILD DE LA BASE DE DATOS
ShowCliente show = dataSnapshot.getValue(ShowCliente.class);
//DISMINUIR A 1 LOS CLIENTES REPETIDOS EN LISTA
Iterator<ShowCliente> iteShow = myList.iterator();
while(iteShow.hasNext()){
ShowCliente ite = iteShow.next();
if(ite.equals(show)) iteShow.remove();
}
myList.add(show);
//ShowCliente key = dataSnapshot.getKey();
//mKeys.add(key);
arrayAdapter.notifyDataSetChanged();
checkEmpty();
//****************************************************************** ATTEMP 2
for(DataSnapshot shot : dataSnapshot.getChildren()){
ShowCliente show = shot.getValue(ShowCliente.class);
String compare = String.valueOf(show.getRazonsoc());
if(show.getRazonsoc() != compare){
myList.add(show);
}
}
//****************************************** ATTEMP 3
ShowCliente show = dataSnapshot.getValue(ShowCliente.class);
//myList.clear();
myList.add(show);
if(myList.indexOf(show) == myList.lastIndexOf(show)){
myList.clear();
}
arrayAdapter.notifyDataSetChanged();
checkEmpty();
//************************************** ATTEMP 4
ShowCliente show = dataSnapshot.getValue(ShowCliente.class);
myShow.add(show);
HashSet<ShowCliente> hashSet = new HashSet<>();
hashSet.addAll(myShow);
myShow.clear();
myShow.addAll(hashSet);
//************************************ ATTEMP 5
for(DataSnapshot shot : dataSnapshot.getChildren()){
ShowCliente show = shot.getValue(ShowCliente.class);
String value = show.getRazonsoc();
stringList.clear();
stringList.add(value);
}
Gratefully for your comments and solutions
Create a new List, do for loop over the old one and for each item in the old one, check if the new list contains the item, if it doesn't, add it to the new list.
This works if you have a good hashCode method on your model, if you don't, your two identical objects might have different hashCodes, thus making this technique (and other techniques that use hashCodes) ineffective.
In that case you either have to override the model's hashCode or if they have a unique field like id, use that to check for equality. (in the for loop above, for each item, do another for loop on the new list and check if none of the items in the new list does not equal the item's id, add it to the list.)
SOLUTION (WORK FINE):
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren()) {
ShowCliente show = data.getValue(ShowCliente.class);
myList.add(show);
System.out.println("Duplicate:"+myList);
}
for(int i=0; i < myList.size(); i++){
for(int j=0; j < myList.size(); j++){
if(myList.get(i).equals(myList.get(j))){
myList.remove(j);
//j;
}
}
}
arrayAdapter.notifyDataSetChanged();
checkEmpty();
In my app, I'm storing a list of data for each user with this ConnectionInformation.java.
package trickandroid.fulllogin;
/**
* Created by Simon Peter on 19-May-17.
*/
public class ConnectionInformation {
String due, selectArea, connectionNum, doorNum, conName, phoneNum, aadharNum, rationNum;
public ConnectionInformation(){
}
public ConnectionInformation(String due, String selectArea, String connectionNum, String doorNum, String conName, String phoneNum, String aadharNum, String rationNum) {
this.connectionNum = connectionNum;
this.doorNum = doorNum;
this.conName = conName;
this.phoneNum = phoneNum;
this.aadharNum = aadharNum;
this.rationNum = rationNum;
this.selectArea = selectArea;
this.due = due;
}
public String getDue() {
return due;
}
public void setDue(String due) {
this.due = due;
}
public String getSelectArea() {
return selectArea;
}
public void setSelectArea(String selectArea) {
this.selectArea = selectArea;
}
public String getConnectionNum() {
return connectionNum;
}
public void setConnectionNum(String connectionNum) {
this.connectionNum = connectionNum;
}
public String getDoorNum() {
return doorNum;
}
public void setDoorNum(String doorNum) {
this.doorNum = doorNum;
}
public String getConName() {
return conName;
}
public void setConName(String conName) {
this.conName = conName;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getAadharNum() {
return aadharNum;
}
public void setAadharNum(String aadharNum) {
this.aadharNum = aadharNum;
}
public String getRationNum() {
return rationNum;
}
public void setRationNum(String rationNum) {
this.rationNum = rationNum;
}
}
Adding data to the firebase works very fine. This is my database structure.
This is my showData() method where .getDoorNum() is called to display it on the ListView.
private void showData(DataSnapshot dataSnapshot) {
if (expandableListView.getVisibility()==View.VISIBLE) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ConnectionInformation cInfo = new ConnectionInformation();
cInfo.setDoorNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getDoorNum());
cInfo.setPhoneNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getPhoneNum());
cInfo.setAadharNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getAadharNum());
cInfo.setRationNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getRationNum());
ArrayList<String> users = new ArrayList<>();
users.add(cInfo.getDoorNum());
users.add(cInfo.getPhoneNum());
users.add(cInfo.getAadharNum());
users.add(cInfo.getRationNum());
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, users);
expandableListView.setAdapter(adapter);
}
}
}
I use this code for deleting the child.
disBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mdata.child(oldArea).child(key).removeValue();
connection.child(oldArea).child(key).removeValue();
toast("Connection Number " + oldNum + " Disconnected Successfully");
startActivity(new Intent(DisconnectActivity.this,AreaGridActivity.class));
}
});
The code works fine in the database but my app crashes with this error...
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String trickandroid.fulllogin.ConnectionInformation.getDoorNum()' on a null object reference
at trickandroid.fulllogin.DetailsActivity.showData(DetailsActivity.java:449)
at trickandroid.fulllogin.DetailsActivity.access$100(DetailsActivity.java:33)
at trickandroid.fulllogin.DetailsActivity$3.onDataChange(DetailsActivity.java:129)
at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
https://gist.github.com/SimonPeter1909/d70be328dd6d9b099a8a96454922432fDetailsActivity.java
I have tried many ways but I can't pass the error...
The situation here is that you have a ValueEventListener which is triggered once when the listener is added, and then again any time the data changes. The listener is explicitly expecting to find an entry with a certain areaName and key.
This is fine the first time the listener runs, but then on button click you delete the entry with that areaName and key. This triggers the listener again(you changed the data), the listener tries to do something with the entry at that areaName and key, it doesn't exist, you get a NullPointerException.
There are a number of ways to avoid this, but you probably need to rethink the flow and exactly what you want to happen.
A quick fix here could be to try checking if the entry is there before trying to use it:
if(ds.child(userID).child("Connection Detail").child(areaName).child(key).exists()) {
ConnectionInformation cInfo = new ConnectionInformation();
cInfo.setDoorNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getDoorNum());
cInfo.setPhoneNum(ds.child(userID).child("Connection Detail").child(areaName).child(key).getValue(ConnectionInformation.class).getPhoneNum());
...
...
} else {
//that entry doesn't exist, do something else
}
not enough info, but i think you are callig getDoorNum, when there is no string in there . try
if (!yourmodelclassobject.getDoorNum()==null)
{
//then print your value or whatever is that you do}
or please post little more info
I'm creating a simple library app where books can be added and a list of books can be viewed.
here is my book class
public class Book {
private int _id;
private String _bookTitle;
private String _bookAuthor;
private int _bookISBN;
private Map<String, Object> mp;
public Book() {
}
public Book(String _bookTitle, String _bookAuthor, int _bookISBN) {
this._id = _id;
this._bookTitle = _bookTitle;
this._bookAuthor = _bookAuthor;
this._bookISBN = _bookISBN;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_bookTitle() {
return _bookTitle;
}
public void set_bookTitle(String _bookTitle) {
this._bookTitle = _bookTitle;
}
public String get_bookAuthor() {
return _bookAuthor;
}
public void set_bookAuthor(String _bookAuthor) {
this._bookAuthor = _bookAuthor;
}
public int get_bookISBN() {
return _bookISBN;
}
public void set_bookISBN(int _bookISBN) {
this._bookISBN = _bookISBN;
}
public Map<String, Object> toMap() {
mp = new HashMap<>();
mp.put("bookTitle", this._bookTitle);
mp.put("bookAuthor", this._bookAuthor);
mp.put("bookISBN", this._bookISBN);
return mp;
} }
and here is where I am trying to read from the values which are already written into firebase
public class ViewBook extends AppCompatActivity {
ArrayList<String> myArrayList = new ArrayList<>();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
// DatabaseReference mPostReference = ref.child("books");
DatabaseReference temp = ref.child("books");
ArrayAdapter<String> adapter;
#Override
public void onStart(){
super.onStart();
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Book book = postSnapshot.getValue(Book.class);
myArrayList.add(book.get_bookTitle() + "\n" + book.get_bookAuthor() + "\n" + book.get_bookISBN());
}
ListView lv = (ListView)findViewById(R.id.list);
adapter = new ArrayAdapter<String>(ViewBook.this, android.R.layout.simple_list_item_1, myArrayList);
lv.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Getting Post failed, log a message
Log.w("VIEWBOOKS", "loadPost:onCancelled", databaseError.toException());
}
};
temp.addValueEventListener(postListener);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_book);
}}
the error I am getting is
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.taylorcampos.androidfirebasedatabase, PID: 25339
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.taylorcampos.androidfirebasedatabase.Book
at com.google.android.gms.internal.zzbtg.zze(Unknown Source)
at com.google.android.gms.internal.zzbtg.zzb(Unknown Source)
at com.google.android.gms.internal.zzbtg.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.example.taylorcampos.androidfirebasedatabase.ViewBook$1.onDataChange(ViewBook.java:38)
at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
at com.google.android.gms.internal.zzbqx.zzZT(Unknown Source)
at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Someone please explain why this is happening and how I could get the list view to list these books that have been put into firebase.
dataSnapshot.getChildren() is going to return you a list of attributes for a book, not a Book object itself. One of those is a String, thus the error
You need another level of data in the database, or if all you're storing is a list of books, remove child("books") and use a generated unique key instead of the string "books"
Additionally, Firebase is going to try to set your fields using camelCase methods and variables (like those in the database), not underscores like those in your Java class. In other words, they should match
Your code:
DatabaseReference ref = database.getReference();
DatabaseReference temp = ref.child("books");
Updated code with correction to solve error:
DatabaseReference ref = database.getReference();
DatabaseReference temp = ref.child("books").toString();
Your doing it wrong this is how you get it
databasereference reference = FirebaseDatabase.getInstance().getReference("books")
if you have a child on that then just add
.child( "like fuser.getUid() something like this" )
once that's done then add a Listener for it, now go to onDataChange add your code like this
String userName = snapshot.child("Data Name").getValue().toString();