I have this problem when i open the view of "Eventos", im trying to delete from de database the selected items from the listview.
public class ShowData extends AppCompatActivity {
DatabaseReference databaseReference;
ListView listView;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
Button btnDelete;
Module module;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
databaseReference = FirebaseDatabase.getInstance().getReference("Eventos");
listView = (ListView) findViewById(R.id.listViewShow);
btnDelete = (Button) findViewById(R.id.btnBorrarElemento);
module=((Module)getApplication());
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter); .....
... listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paramAdapterView, View view, int position, long id) {
module.setGvalue_titulo(arrayList.get(position));
module.setGvalue_descripcion(arrayList.get(position));
module.setGvalue_fecha(arrayList.get(position));
module.setGvalue_url(arrayList.get(position));
}
});
btnDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
final String str = module.getGvalue_titulo().substring(0, 6);
if(str == ""){
Toast.makeText(ShowData.this, "No se ha seleccionado ningun elemento para eliminar", Toast.LENGTH_SHORT).show();
}
else {
databaseReference.child("Eventos").child(str).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
databaseReference.child(str).removeValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Toast.makeText(ShowData.this, "Evento Eliminado", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),ShowData.class);
startActivity(intent);
}
}
}); ....
The module has the getters and setters necessaries:
In my manifest, I have this:
Your problem is that you are trying to cast your Application to Module, but it's not Module. Well, have you registered your Module as custom application implementation in your AndroidManifest.xml? If the answer is "no" than this is the exact reason! Follow this answer to check how to do it easily.
Related
I'm working on a project where there's an activity which contains 3 spinners( Nested). I need the 2nd spinner to have the data based on the selected item of the 1st spinner and the data is retrieved from Firebase
The 1st spinner is going to have all "Gouv" values , the 2nd one is going to have the "Deleg" values where "Gouv" value is equal to the selected item "Gouv" of the 1st spinner .
Here is the code that i tried and i keep get in the log Null .
public class RechCode extends AppCompatActivity {
DatabaseReference spinnerRef;
Query spinnerRefG;
Spinner spinnerG;
Spinner spinnerD;
Spinner spinnerL;
ArrayAdapter<String> adapterG;
ArrayAdapter<String> adapterL;
ArrayAdapter<String> adapterD;
ArrayList<String> spinnerDList;
ArrayList<String> spinnerGList;
ArrayList<String> spinnerLOList;
Query spinnerRefD;
private String ChoixG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rech_code);
spinnerG = findViewById(R.id.SpinnerGouv);
spinnerD = findViewById(R.id.SpinnerDeleg);
spinnerL = findViewById(R.id.SpinnerLoc);
spinnerRef = FirebaseDatabase.getInstance().getReference().child("CodePostale");
//Query queryD = spinnerG.("state", "CA");
spinnerGList = new ArrayList<>();
spinnerDList = new ArrayList<>();
spinnerLOList = new ArrayList<>();
adapterD= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerDList);
adapterL= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerLOList);
adapterG= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerGList);
spinnerG.setAdapter(adapterG);
spinnerD.setAdapter(adapterD);
spinnerL.setAdapter(adapterL);
ShowdataGouv();
spinnerRefG= FirebaseDatabase.getInstance().getReference("CodePostale").child("Deleg").orderByChild("Gouv").equalTo(ChoixG);
ShowdataDeleg();
spinnerG.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ChoixG = spinnerGList.get(i);
Toast.makeText(getApplicationContext(), "Gouvernorat:" + ChoixG, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
Button retour = (Button) findViewById(R.id.return_btn);
retour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetourMenu();
}
});
}
private void ShowdataLoc(String text) {
spinnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
for (DataSnapshot item:snapshot1.getChildren()){
spinnerLOList.add(item.child("Loc").getValue().toString());
}
adapterD.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ShowdataDeleg() {
spinnerRefG.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot2) {
for (DataSnapshot item:snapshot2.getChildren()){
spinnerDList.add(item.child("Deleg").getValue().toString());
}
Log.d("Value","BBBBBBBB"+ snapshot2);
adapterD.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ShowdataGouv() {
spinnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot3) {
for (DataSnapshot item:snapshot3.getChildren()){
spinnerGList.add(item.child("Gouv").getValue().toString());
Log.d("Value","AAAAAAAAA"+ snapshot3);
}
adapterG.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void RetourMenu() {
Intent intent = new Intent(getApplicationContext(), Menus.class);
startActivity(intent);
}
}
The problem is in the way you construct the query here:
spinnerRefG= FirebaseDatabase.getInstance()
.getReference("CodePostale")
.child("Deleg")
.orderByChild("Gouv")
.equalTo(ChoixG);
You're asking to load child nodes of /CodePostale/Deleg that have a Gouv property with a value of ChoixG. But if we check the screenshot of the data, there is no /CodePostale/Deleg, so no data is returned.
What you want instead is to check the child nodes of /CodePostale and return the ones where their Deleg/Gouv property has a value of ChoixG, which you can do with:
spinnerRefG= FirebaseDatabase.getInstance()
.getReference("CodePostale")
.orderByChild("Deleg/Gouv")
.equalTo(ChoixG);
In my firebase I have questions and their answers stored. Each answer has an id, which it got from push(). But I am unable to show the list of all the users who have answered the question. Please help.
Here is the code:
ListView listView;
ArrayList<String> answerers = new ArrayList<>();
ArrayAdapter arrayAdapter;
String askedBy, question, likes;
FirebaseAuth mAuth;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_answers);
listView = findViewById(R.id.answersListView);
Intent intent = getIntent();
askedBy = intent.getStringExtra("askedBy");
question = intent.getStringExtra("question");
likes = intent.getStringExtra("numberOfLikes");
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("questions").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
if (dataSnapshot.child("question").getValue().toString().equals(question) && dataSnapshot.child("askedBy").getValue().toString().equals(askedBy)
&& dataSnapshot.child("likes").getValue().toString().equals(likes)) {
dataSnapshot.child("answers").getRef().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshots) {
if (snapshots.exists()){
for (DataSnapshot dataSnapshots : snapshots.getChildren()){
String id = dataSnapshot.getRef().push().getKey();
answerers.add(dataSnapshots.child(id).child("answeredBy").getValue().toString());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
arrayAdapter = new ArrayAdapter<>(ViewAnswersActivity.this, android.R.layout.simple_list_item_1, answerers);
listView.setAdapter(arrayAdapter);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent1 = new Intent(ViewAnswersActivity.this, AnswerActivity.class);
intent1.putExtra("askedBy", askedBy);
intent1.putExtra("answeredBy", answerers.get(i));
intent1.putExtra("question", question);
intent1.putExtra("numberOfLikes", likes);
startActivity(intent1);
}
});
}
When I am running the app, the listView is coming empty, indicating value hasn't been stored.
Try to set adapter within onDataChange()
#Override
public void onDataChange(#NonNull DataSnapshot snapshots) {
if (snapshots.exists()){
for (DataSnapshot dataSnapshots : snapshots.getChildren()){
String id = dataSnapshot.getRef().push().getKey();
answerers.add(dataSnapshots.child(id).child("answeredBy").getValue().toString());
}
arrayAdapter = new ArrayAdapter<> (ViewAnswersActivity.this, android.R.layout.simple_list_item_1, answerers);
listView.setAdapter(arrayAdapter);
}
}
In my ChatListActivity, I am getting emails of users and showing them in a listView using Firebase. There is value in Firebase because when the arraylist is showing its data when I use log, but isn't showing in ListView. Please help.
public class ChatListActivity extends AppCompatActivity {
ListView userListView;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> users = new ArrayList<>();
FirebaseAuth mAuth;
DatabaseReference databaseReference;
Button signOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_list);
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
userListView = findViewById(R.id.userListView);
signOut = findViewById(R.id.signOut);
databaseReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
String email = dataSnapshot.child("email").getValue().toString();
if (!email.equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
users.add(email);
Log.i("Log", Arrays.toString(new ArrayList[]{users}));
}
}
arrayAdapter = new ArrayAdapter<>(ChatListActivity.this, android.R.layout.simple_list_item_1, users);
userListView.setAdapter(arrayAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ChatListActivity.this, "Failed to load users", Toast.LENGTH_SHORT).show();
}
});
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
Intent intent = new Intent(ChatListActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
Here is my log.
Do set an empty adapter before network call, like this
arrayAdapter = new ArrayAdapter<>(ChatListActivity.this, android.R.layout.simple_list_item_1, users);
userListView.setAdapter(arrayAdapter);
after you receive original response, reset the adapter with new data. That should work.
now "users" will have some data
arrayAdapter = new ArrayAdapter<>(ChatListActivity.this, android.R.layout.simple_list_item_1, users);
userListView.setAdapter(arrayAdapter);
I am a beginner in android development.I faces a problem with arraylist.I declared arraylist city as global variable and I added elements to it from firebase.But.,after that when i access this elements out side of the addchildevent listener method,the array list become empty.How can i declare the array list to get elements globally.?
My code snippet is,
public class BookingDetails extends Fragment {
private RecyclerView recyclerView;
private DatabaseReference dataRef;
private FirebaseAuth mAuth;
ArrayList<String> uids=new ArrayList<String>();
private ArrayList<String> dates=new ArrayList<>();
private int hour;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
InputMethodManager in=(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
final View v=inflater.inflate(R.layout.activity_booking_details,container,false);
recyclerView = (RecyclerView) v.findViewById(R.id.book_detail_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
mAuth=FirebaseAuth.getInstance();
final String user=mAuth.getCurrentUser().getUid();
dataRef= FirebaseDatabase.getInstance().getReference();
dataRef.child("Users").child(user).child("booked docters").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data:dataSnapshot.getChildren()) {
uids.add(data.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(getActivity(),uids.get(0), Toast.LENGTH_SHORT).show();
return v;
}
}
This gives me empty.But when i use this toast on the method value event listener gives correct elements.How to fix this problem.?
Mehmed's reason on what's going wrong is correct. You'll need to move the code that needs access to the uids into the `onDataChange method. One way to do so is:
dataRef= FirebaseDatabase.getInstance().getReference();
dataRef.child("Users").child(user).child("booked docters").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data:dataSnapshot.getChildren()) {
uids.add(data.getKey());
}
Toast.makeText(getActivity(),uids.get(0), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Firebase listeners are asynchronous, so use your arraylist inside your Firebase listener after it is filled with data as follows:
ArrayList<String> itemList;
private void someFunction() {
itemList = new ArrayList<>();
someDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : snapshot.getChildren()) {
String item = child.getKey();
itemList.add(item);
}
// Now your itemList is filled and ready to be used...
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// If you try to use itemList here then you may get error since it is empty...
}
I would like to link custom adapter which includes Text and Image, with Firebase, In Order to retrieve both of (Text , Image) in listView item from Firebase.
This is my current code:
// Get ListView object from xml
final ListView listView = (ListView) findViewById(R.id.listView);
// Create a new Adapters
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
R.layout.custom_list_view_item, R.id.text);
final ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, R.id.text);
final ArrayAdapter<String> adapter3 = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, R.id.text);
listView.setAdapter(adapter);
// Enabling Offline
if (Firebase.getDefaultConfig().isPersistenceEnabled() == false)
Firebase.getDefaultConfig().setPersistenceEnabled(true);
// Use Firebase
Firebase.setAndroidContext(this);
new Firebase(firebaseURL)
.addChildEventListener(new ChildEventListener() {
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
adapter.add((String) dataSnapshot.child("text").getValue());
adapter2.add((String) dataSnapshot.child("image0").getValue());
adapter3.add((String) dataSnapshot.child("image1").getValue());
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
adapter.remove((String) dataSnapshot.child("text").getValue());
adapter2.remove((String) dataSnapshot.child("image0").getValue());
adapter3.remove((String) dataSnapshot.child("image1").getValue());
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
public void onCancelled(FirebaseError firebaseError) {
}
});
// Open details when items when clicked
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
new Firebase(firebaseURL)
.orderByChild("text")
.equalTo((String) listView.getItemAtPosition(position))
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChildren()) {
DataSnapshot firstChild = dataSnapshot.getChildren().iterator().next();
firstChild.getRef();
String d = adapter.getItem(position);
String image0 = adapter2.getItem(position);
String image1 = adapter3.getItem(position);
Intent i = new Intent(List_mall.this, Details_malls.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("text", d);
i.putExtra("image0", image0);
i.putExtra("image1", image1);
startActivity(i);
}
}
public void onCancelled(FirebaseError firebaseError) {
}
});
}
});