How to get index from firebase node
I am working on an android application, and I am using Firebase database,
this database showing an Items list.
This is my code.
private DatabaseReference root;
ListView elementList;
ArrayAdapter<mdlItem> adapter;
ArrayList<mdlItem> itemsList;
Context context;
private void loadFireDataBase() {
root = FirebaseDatabase.getInstance().getReference().child("Offers");
root.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Add_Chat(dataSnapshot, "Add");
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Add_Chat(dataSnapshot, "Edit");
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Add_Chat(dataSnapshot , "Delete");
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//Log.i(tag, "onCreateView");
return creatList(inflater, container);
}
private View creatList(LayoutInflater inflater, @Nullable ViewGroup container) {
loadFireDataBase();
context = getActivity();
itemsList = new ArrayList<mdlItem>();
View view;
view = inflater.inflate(R.layout.freg_main_content, container, false);
elementList = (ListView) view.findViewById(R.id.customListView);
Collections.sort(itemsList, new Comparator<mdlItem>() {
@Override
public int compare(mdlItem data1, mdlItem data2) {
if (data1.getOfferIndex() > data2.getOfferIndex())
return 1;
else
return 0;
}
});
adapter = new offersArrayAdapter(context, R.layout.item_list_layout, itemsList);
elementList.setAdapter(adapter);
elementList.setOnItemClickListener(this);
return view;
}
private void Add_Chat(DataSnapshot dataSnapshot, String theCase) {
Map<String, Object> question = null;
try {
String theOfferCode = dataSnapshot.getKey();
question = (Map<String, Object>) dataSnapshot.getValue();
mdlItem mdl = new mdlItem();
mdl.setOfferCode(theOfferCode);
mdl.setRestCode(Integer.parseInt(String.valueOf(question.get("itemCode"))));
mdl.setRestName(question.get("itmeName").toString());
switch (theCase) {
case "Add":
itemsList.add(mdl);
break;
case "Delete":
itemsList.remove(mdl);
break;
case "Edit":
//??
break;
}
adapter.notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
The problem is I can't get any node index through 'dataSnapshot' object, to control the list when I make Delete and Update.
And another thing how to use Add_Chat method to add the mdl item in the top of other items list.
I already catch the Edit, delete and add in the database root but I can't control how to use these events in the right way
I think I need to get the 'dataSnapshot' object to remove it or set an update on it, or if there is another solution
Can any one help me in this.
java android firebase firebase-realtime-database
add a comment |
I am working on an android application, and I am using Firebase database,
this database showing an Items list.
This is my code.
private DatabaseReference root;
ListView elementList;
ArrayAdapter<mdlItem> adapter;
ArrayList<mdlItem> itemsList;
Context context;
private void loadFireDataBase() {
root = FirebaseDatabase.getInstance().getReference().child("Offers");
root.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Add_Chat(dataSnapshot, "Add");
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Add_Chat(dataSnapshot, "Edit");
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Add_Chat(dataSnapshot , "Delete");
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//Log.i(tag, "onCreateView");
return creatList(inflater, container);
}
private View creatList(LayoutInflater inflater, @Nullable ViewGroup container) {
loadFireDataBase();
context = getActivity();
itemsList = new ArrayList<mdlItem>();
View view;
view = inflater.inflate(R.layout.freg_main_content, container, false);
elementList = (ListView) view.findViewById(R.id.customListView);
Collections.sort(itemsList, new Comparator<mdlItem>() {
@Override
public int compare(mdlItem data1, mdlItem data2) {
if (data1.getOfferIndex() > data2.getOfferIndex())
return 1;
else
return 0;
}
});
adapter = new offersArrayAdapter(context, R.layout.item_list_layout, itemsList);
elementList.setAdapter(adapter);
elementList.setOnItemClickListener(this);
return view;
}
private void Add_Chat(DataSnapshot dataSnapshot, String theCase) {
Map<String, Object> question = null;
try {
String theOfferCode = dataSnapshot.getKey();
question = (Map<String, Object>) dataSnapshot.getValue();
mdlItem mdl = new mdlItem();
mdl.setOfferCode(theOfferCode);
mdl.setRestCode(Integer.parseInt(String.valueOf(question.get("itemCode"))));
mdl.setRestName(question.get("itmeName").toString());
switch (theCase) {
case "Add":
itemsList.add(mdl);
break;
case "Delete":
itemsList.remove(mdl);
break;
case "Edit":
//??
break;
}
adapter.notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
The problem is I can't get any node index through 'dataSnapshot' object, to control the list when I make Delete and Update.
And another thing how to use Add_Chat method to add the mdl item in the top of other items list.
I already catch the Edit, delete and add in the database root but I can't control how to use these events in the right way
I think I need to get the 'dataSnapshot' object to remove it or set an update on it, or if there is another solution
Can any one help me in this.
java android firebase firebase-realtime-database
Do you mean key for the node's address?
– jake
Nov 25 '18 at 13:49
yes when I delete node it sends this node to dataSnapshot, I want the index to delete it from itemsList
– ahmed mohamady
Nov 25 '18 at 13:57
add a comment |
I am working on an android application, and I am using Firebase database,
this database showing an Items list.
This is my code.
private DatabaseReference root;
ListView elementList;
ArrayAdapter<mdlItem> adapter;
ArrayList<mdlItem> itemsList;
Context context;
private void loadFireDataBase() {
root = FirebaseDatabase.getInstance().getReference().child("Offers");
root.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Add_Chat(dataSnapshot, "Add");
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Add_Chat(dataSnapshot, "Edit");
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Add_Chat(dataSnapshot , "Delete");
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//Log.i(tag, "onCreateView");
return creatList(inflater, container);
}
private View creatList(LayoutInflater inflater, @Nullable ViewGroup container) {
loadFireDataBase();
context = getActivity();
itemsList = new ArrayList<mdlItem>();
View view;
view = inflater.inflate(R.layout.freg_main_content, container, false);
elementList = (ListView) view.findViewById(R.id.customListView);
Collections.sort(itemsList, new Comparator<mdlItem>() {
@Override
public int compare(mdlItem data1, mdlItem data2) {
if (data1.getOfferIndex() > data2.getOfferIndex())
return 1;
else
return 0;
}
});
adapter = new offersArrayAdapter(context, R.layout.item_list_layout, itemsList);
elementList.setAdapter(adapter);
elementList.setOnItemClickListener(this);
return view;
}
private void Add_Chat(DataSnapshot dataSnapshot, String theCase) {
Map<String, Object> question = null;
try {
String theOfferCode = dataSnapshot.getKey();
question = (Map<String, Object>) dataSnapshot.getValue();
mdlItem mdl = new mdlItem();
mdl.setOfferCode(theOfferCode);
mdl.setRestCode(Integer.parseInt(String.valueOf(question.get("itemCode"))));
mdl.setRestName(question.get("itmeName").toString());
switch (theCase) {
case "Add":
itemsList.add(mdl);
break;
case "Delete":
itemsList.remove(mdl);
break;
case "Edit":
//??
break;
}
adapter.notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
The problem is I can't get any node index through 'dataSnapshot' object, to control the list when I make Delete and Update.
And another thing how to use Add_Chat method to add the mdl item in the top of other items list.
I already catch the Edit, delete and add in the database root but I can't control how to use these events in the right way
I think I need to get the 'dataSnapshot' object to remove it or set an update on it, or if there is another solution
Can any one help me in this.
java android firebase firebase-realtime-database
I am working on an android application, and I am using Firebase database,
this database showing an Items list.
This is my code.
private DatabaseReference root;
ListView elementList;
ArrayAdapter<mdlItem> adapter;
ArrayList<mdlItem> itemsList;
Context context;
private void loadFireDataBase() {
root = FirebaseDatabase.getInstance().getReference().child("Offers");
root.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Add_Chat(dataSnapshot, "Add");
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Add_Chat(dataSnapshot, "Edit");
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Add_Chat(dataSnapshot , "Delete");
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//Log.i(tag, "onCreateView");
return creatList(inflater, container);
}
private View creatList(LayoutInflater inflater, @Nullable ViewGroup container) {
loadFireDataBase();
context = getActivity();
itemsList = new ArrayList<mdlItem>();
View view;
view = inflater.inflate(R.layout.freg_main_content, container, false);
elementList = (ListView) view.findViewById(R.id.customListView);
Collections.sort(itemsList, new Comparator<mdlItem>() {
@Override
public int compare(mdlItem data1, mdlItem data2) {
if (data1.getOfferIndex() > data2.getOfferIndex())
return 1;
else
return 0;
}
});
adapter = new offersArrayAdapter(context, R.layout.item_list_layout, itemsList);
elementList.setAdapter(adapter);
elementList.setOnItemClickListener(this);
return view;
}
private void Add_Chat(DataSnapshot dataSnapshot, String theCase) {
Map<String, Object> question = null;
try {
String theOfferCode = dataSnapshot.getKey();
question = (Map<String, Object>) dataSnapshot.getValue();
mdlItem mdl = new mdlItem();
mdl.setOfferCode(theOfferCode);
mdl.setRestCode(Integer.parseInt(String.valueOf(question.get("itemCode"))));
mdl.setRestName(question.get("itmeName").toString());
switch (theCase) {
case "Add":
itemsList.add(mdl);
break;
case "Delete":
itemsList.remove(mdl);
break;
case "Edit":
//??
break;
}
adapter.notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
The problem is I can't get any node index through 'dataSnapshot' object, to control the list when I make Delete and Update.
And another thing how to use Add_Chat method to add the mdl item in the top of other items list.
I already catch the Edit, delete and add in the database root but I can't control how to use these events in the right way
I think I need to get the 'dataSnapshot' object to remove it or set an update on it, or if there is another solution
Can any one help me in this.
java android firebase firebase-realtime-database
java android firebase firebase-realtime-database
edited Nov 25 '18 at 13:55
Catalin Ghita
414414
414414
asked Nov 25 '18 at 13:12
ahmed mohamadyahmed mohamady
1481318
1481318
Do you mean key for the node's address?
– jake
Nov 25 '18 at 13:49
yes when I delete node it sends this node to dataSnapshot, I want the index to delete it from itemsList
– ahmed mohamady
Nov 25 '18 at 13:57
add a comment |
Do you mean key for the node's address?
– jake
Nov 25 '18 at 13:49
yes when I delete node it sends this node to dataSnapshot, I want the index to delete it from itemsList
– ahmed mohamady
Nov 25 '18 at 13:57
Do you mean key for the node's address?
– jake
Nov 25 '18 at 13:49
Do you mean key for the node's address?
– jake
Nov 25 '18 at 13:49
yes when I delete node it sends this node to dataSnapshot, I want the index to delete it from itemsList
– ahmed mohamady
Nov 25 '18 at 13:57
yes when I delete node it sends this node to dataSnapshot, I want the index to delete it from itemsList
– ahmed mohamady
Nov 25 '18 at 13:57
add a comment |
2 Answers
2
active
oldest
votes
Firebase snapshots are not index-based. If you need a mapping from the key in the database to the index in your adapter, you will need to maintain this mapping yourself.
For a simple version of this, have a look at the FirebaseArray
class in the FirebaseUI library. It maintains a list of all snapshots that are currently in the array:
private final List<DataSnapshot> mSnapshots = new ArrayList<>();
And then in the onChildAdded
methods adds, determines where the new item fits in the list and adds it:
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildKey) {
int index = 0;
if (previousChildKey != null) {
index = getIndexForKey(previousChildKey) + 1;
}
mSnapshots.add(index, snapshot);
notifyOnChildChanged(ChangeEventType.ADDED, snapshot, index, -1);
}
It does the equivalent for all other onChild...
methods, so that it can look up the index for a specific key when needed with its getIndexForKey
method:
private int getIndexForKey(@NonNull String key) {
int index = 0;
for (DataSnapshot snapshot : mSnapshots) {
if (snapshot.getKey().equals(key)) {
return index;
} else {
index++;
}
}
throw new IllegalArgumentException("Key not found");
}
add a comment |
Just For recording, This is the correct solution
int index = -1;
for (mdlItem item: itemsList) {
if (item.getIndex() == mdl.getIndex()) {
index = itemsList.indexOf(item);
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53467811%2fhow-to-get-index-from-firebase-node%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Firebase snapshots are not index-based. If you need a mapping from the key in the database to the index in your adapter, you will need to maintain this mapping yourself.
For a simple version of this, have a look at the FirebaseArray
class in the FirebaseUI library. It maintains a list of all snapshots that are currently in the array:
private final List<DataSnapshot> mSnapshots = new ArrayList<>();
And then in the onChildAdded
methods adds, determines where the new item fits in the list and adds it:
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildKey) {
int index = 0;
if (previousChildKey != null) {
index = getIndexForKey(previousChildKey) + 1;
}
mSnapshots.add(index, snapshot);
notifyOnChildChanged(ChangeEventType.ADDED, snapshot, index, -1);
}
It does the equivalent for all other onChild...
methods, so that it can look up the index for a specific key when needed with its getIndexForKey
method:
private int getIndexForKey(@NonNull String key) {
int index = 0;
for (DataSnapshot snapshot : mSnapshots) {
if (snapshot.getKey().equals(key)) {
return index;
} else {
index++;
}
}
throw new IllegalArgumentException("Key not found");
}
add a comment |
Firebase snapshots are not index-based. If you need a mapping from the key in the database to the index in your adapter, you will need to maintain this mapping yourself.
For a simple version of this, have a look at the FirebaseArray
class in the FirebaseUI library. It maintains a list of all snapshots that are currently in the array:
private final List<DataSnapshot> mSnapshots = new ArrayList<>();
And then in the onChildAdded
methods adds, determines where the new item fits in the list and adds it:
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildKey) {
int index = 0;
if (previousChildKey != null) {
index = getIndexForKey(previousChildKey) + 1;
}
mSnapshots.add(index, snapshot);
notifyOnChildChanged(ChangeEventType.ADDED, snapshot, index, -1);
}
It does the equivalent for all other onChild...
methods, so that it can look up the index for a specific key when needed with its getIndexForKey
method:
private int getIndexForKey(@NonNull String key) {
int index = 0;
for (DataSnapshot snapshot : mSnapshots) {
if (snapshot.getKey().equals(key)) {
return index;
} else {
index++;
}
}
throw new IllegalArgumentException("Key not found");
}
add a comment |
Firebase snapshots are not index-based. If you need a mapping from the key in the database to the index in your adapter, you will need to maintain this mapping yourself.
For a simple version of this, have a look at the FirebaseArray
class in the FirebaseUI library. It maintains a list of all snapshots that are currently in the array:
private final List<DataSnapshot> mSnapshots = new ArrayList<>();
And then in the onChildAdded
methods adds, determines where the new item fits in the list and adds it:
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildKey) {
int index = 0;
if (previousChildKey != null) {
index = getIndexForKey(previousChildKey) + 1;
}
mSnapshots.add(index, snapshot);
notifyOnChildChanged(ChangeEventType.ADDED, snapshot, index, -1);
}
It does the equivalent for all other onChild...
methods, so that it can look up the index for a specific key when needed with its getIndexForKey
method:
private int getIndexForKey(@NonNull String key) {
int index = 0;
for (DataSnapshot snapshot : mSnapshots) {
if (snapshot.getKey().equals(key)) {
return index;
} else {
index++;
}
}
throw new IllegalArgumentException("Key not found");
}
Firebase snapshots are not index-based. If you need a mapping from the key in the database to the index in your adapter, you will need to maintain this mapping yourself.
For a simple version of this, have a look at the FirebaseArray
class in the FirebaseUI library. It maintains a list of all snapshots that are currently in the array:
private final List<DataSnapshot> mSnapshots = new ArrayList<>();
And then in the onChildAdded
methods adds, determines where the new item fits in the list and adds it:
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildKey) {
int index = 0;
if (previousChildKey != null) {
index = getIndexForKey(previousChildKey) + 1;
}
mSnapshots.add(index, snapshot);
notifyOnChildChanged(ChangeEventType.ADDED, snapshot, index, -1);
}
It does the equivalent for all other onChild...
methods, so that it can look up the index for a specific key when needed with its getIndexForKey
method:
private int getIndexForKey(@NonNull String key) {
int index = 0;
for (DataSnapshot snapshot : mSnapshots) {
if (snapshot.getKey().equals(key)) {
return index;
} else {
index++;
}
}
throw new IllegalArgumentException("Key not found");
}
answered Nov 25 '18 at 15:05
Frank van PuffelenFrank van Puffelen
238k29382408
238k29382408
add a comment |
add a comment |
Just For recording, This is the correct solution
int index = -1;
for (mdlItem item: itemsList) {
if (item.getIndex() == mdl.getIndex()) {
index = itemsList.indexOf(item);
}
}
add a comment |
Just For recording, This is the correct solution
int index = -1;
for (mdlItem item: itemsList) {
if (item.getIndex() == mdl.getIndex()) {
index = itemsList.indexOf(item);
}
}
add a comment |
Just For recording, This is the correct solution
int index = -1;
for (mdlItem item: itemsList) {
if (item.getIndex() == mdl.getIndex()) {
index = itemsList.indexOf(item);
}
}
Just For recording, This is the correct solution
int index = -1;
for (mdlItem item: itemsList) {
if (item.getIndex() == mdl.getIndex()) {
index = itemsList.indexOf(item);
}
}
answered Nov 27 '18 at 15:17
ahmed mohamadyahmed mohamady
1481318
1481318
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53467811%2fhow-to-get-index-from-firebase-node%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Do you mean key for the node's address?
– jake
Nov 25 '18 at 13:49
yes when I delete node it sends this node to dataSnapshot, I want the index to delete it from itemsList
– ahmed mohamady
Nov 25 '18 at 13:57