Hello im new in coding and i´m creating an app and need a little help from you guys!
My First row of the table view is repeating always when i have data to show.
This is the output of my app:
I want it to be like a normal table like this:
Im gonna show you my code:
My "main activity":
public class Administracao extends AppCompatActivity {
private static final String[] MATRICULA = new String[]{
"10-NX-68", "21-30-XJ", "54-HI-11", "90-29-VE"
};
private AutoCompleteTextView editText_Matric;
//Referencias base de dados
DatabaseReference reff2;
private FirebaseDatabase database;
Spinner spinner;
String selected_item;
//Testes Firebase listview apagar se der erro
List<Dados_Administracao> administracao_adapter;
ListView listViewCondutores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_administracao);
editText_Matric = findViewById(R.id.actv);
Button btn = findViewById(R.id.btn_seguinte);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, MATRICULA);
editText_Matric.setAdapter(adapter);
//TESTES FIREBASE list view
listViewCondutores = (ListView) findViewById(R.id.listView1);
administracao_adapter = new ArrayList<>();
editText_Matric.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Mostrar todos os registos
reff2 = database.getInstance().getReference().child("Registo Inicial e Final");
reff2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
administracao_adapter.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Dados_Administracao dt = ds.getValue(Dados_Administracao.class);
if(ds.child("matricula").getValue().equals(editText_Matric.getText().toString())) {
administracao_adapter.add(dt);
}
}
Administracao_adapter adapter2 = new Administracao_adapter(Administracao.this, administracao_adapter);
listViewCondutores.setAdapter(adapter2);
// adapter2.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Handle possible errors.
Log.e("The read failed: " ,databaseError.getMessage());
}
});
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
The Activity where i store the data:
public class Dados_Administracao {
private String observacoes,matricula,datainicio,horainicio,datafim,horafim,nomecondutor,marca,codprojeto,latfinal,longfinal,obsfinal,latitude,longitude,kminicial,kmfinal;
public Dados_Administracao(){
}
public Dados_Administracao(String observacoes, String matricula, String datainicio, String horainicio, String datafim, String horafim, String nomecondutor, String marca, String codprojeto, String latfinal, String longfinal, String obsfinal, String latitude, String longitude, String kminicial, String kmfinal) {
this.observacoes = observacoes;
this.matricula = matricula;
this.datainicio = datainicio;
this.horainicio = horainicio;
this.datafim = datafim;
this.horafim = horafim;
this.nomecondutor = nomecondutor;
this.marca = marca;
this.codprojeto = codprojeto;
this.latfinal = latfinal;
this.longfinal = longfinal;
this.obsfinal = obsfinal;
this.latitude = latitude;
this.longitude = longitude;
this.kminicial = kminicial;
this.kmfinal = kmfinal;
}
public String getObservacoes() {
return observacoes;
}
public String getMatricula() {
return matricula;
}
public String getDatainicio() {
return datainicio;
}
public String getHorainicio() {
return horainicio;
}
public String getDatafim() {
return datafim;
}
public String getHorafim() {
return horafim;
}
public String getNomecondutor() {
return nomecondutor;
}
public String getMarca() {
return marca;
}
public String getCodprojeto() {
return codprojeto;
}
public String getLatfinal() {
return latfinal;
}
public String getLongfinal() {
return longfinal;
}
public String getObsfinal() {
return obsfinal;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
public String getKminicial() {
return kminicial;
}
public String getKmfinal() {
return kmfinal;
}
}
If you're set on using a ListView then it directly supports adding headers to your list, have a look at addHeaderView(View v).
So what you would do in this case is separate the header part from your row layout into a new layout file, inflate it and call listViewCondutores.addHeaderView(inflatedView).
However a RecyclerView might better suit your needs here and is generally recommended over ListView. Then even though this doesn't directly support header views, it supports multiple view types!
Related
This question already has answers here:
How to save users score in firebase and retrieve it in real-time in Android studio
(3 answers)
Closed 3 years ago.
I'm beginner for developing.
I'm using Android studio, I've created App that retrieve data from Firebase Realtime database.
I know how to add operation for the click counter but it is not save
EX:"when i click on the button the TextView change to ++1, but if i closed the application and reopen it again it's show me 0 as I didn't any thing before, or even if I moved to other activity".
what I want to do is "count the click ++1 and store in firebase at the same time its update for all users who are using the application ((Retrieve data)).
So: my question is how to make the Click counter Store and Retrieve in a TextView?.
Here's the Image of what i want:
https://vigor-ads.com/wp-content/uploads/2018/11/TEST.png
And RealTimeDataBase:
https://vigor-ads.com/wp-content/uploads/2018/11/FireBase-RealTime.png
PharPolice.java
public class PharPolice extends Fragment {
private int ClicksCounter = 0;
private TextView counter;
DatabaseReference clicksref;
ListView listView;
FirebaseDatabase database;
DatabaseReference myRef;
ArrayList<String> list;
PolicePharmacies policePharmacies ;
FirebaseListAdapter adapter;
public PharPolice() {
// Required empty public constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phar_police, container, false);
}
//---------------------F I R E B A S E------------------------
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Query query = FirebaseDatabase.getInstance().getReference("PharmaciesDB").child("PolicePharmacies");
FirebaseListOptions<PolicePharmacies> options = new FirebaseListOptions.Builder<PolicePharmacies>()
.setLayout(R.layout.pharinfo)
.setQuery(query, PolicePharmacies.class)
.build();
clicksref = FirebaseDatabase.getInstance().getReference("PharmaciesDB").child("PolicePharmacies");
policePharmacies = new PolicePharmacies();
listView = view.findViewById(R.id.pharpoliceListView);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("PolicePharmacies");
list = new ArrayList<>();
adapter = new FirebaseListAdapter(options) {
#Override
protected void populateView(View v, final Object model, int position) {
CardView cv = v.findViewById(R.id.pharcard);
counter = v.findViewById(R.id.SACounter);
TextView Name = v.findViewById(R.id.SAName);
TextView Address = v.findViewById(R.id.SAAddress);
Name.setText(((PolicePharmacies) model).getName());
Address.setText(((PolicePharmacies) model).getAddress());
counter.setText(((PolicePharmacies) model).getClickCounter());
cv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visits();
Intent intent = new Intent(getActivity(), PharPoliceScreen.class);
intent.putExtra("Name", ((PolicePharmacies) model).getName());
intent.putExtra("Address", ((PolicePharmacies) model).getAddress());
intent.putExtra("Phone1", ((PolicePharmacies)model).getPhone1());
intent.putExtra("Phone2", ((PolicePharmacies)model).getPhone2());
intent.putExtra("Phone3", ((PolicePharmacies)model).getPhone3());
intent.putExtra("Offer", ((PolicePharmacies)model).getOffer());
intent.putExtra("Facebook", ((PolicePharmacies)model).getFacebook());
startActivity(intent);
}
});
}
};
listView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
private void Visits ()
{
ClicksCounter ++;
counter.setText(Integer.toString(ClicksCounter));
String clickCounter = counter.getText().toString().trim();
PolicePharmacies saveData = new PolicePharmacies(clickCounter);
clicksref.push().setValue(saveData);
}
//---------------------F I R E B A S E------------------------
PolicePharmacies.class
public class PolicePharmacies {
private String Name;
private String Address;
private String Phone1;
private String Phone2;
private String Phone3;
private String Offer;
private String Facebook;
private String ClickCounter;
public PolicePharmacies() {
}
public PolicePharmacies(String name, String address, String phone1, String phone2, String phone3, String offer, String facebook) {
Name = name;
Address = address;
Phone1 = phone1;
Phone2 = phone2;
Phone3 = phone3;
Offer = offer;
Facebook = facebook;
}
public PolicePharmacies(String clickCounter) {
ClickCounter = clickCounter;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getPhone1() {
return Phone1;
}
public void setPhone1(String phone1) {
Phone1 = phone1;
}
public String getPhone2() {
return Phone2;
}
public void setPhone2(String phone2) {
Phone2 = phone2;
}
public String getPhone3() {
return Phone3;
}
public void setPhone3(String phone3) {
Phone3 = phone3;
}
public String getOffer() {
return Offer;
}
public void setOffer(String offer) {
Offer = offer;
}
public String getFacebook() {
return Facebook;
}
public void setFacebook(String facebook) {
Facebook = facebook;
}
public String getClickCounter() {
return ClickCounter;
}
public void setClickCounter(String clickCounter) {
ClickCounter = clickCounter;
}
The problem is not in the code. The problem is in the logic. Try to imagine that there are two separate parts in this process. First step increase the number Second step show the result. So first step you can easy implement after reading this article about WRITING into firebase https://firebase.google.com/docs/database/admin/save-data
Now about second step how to show the result. First what you have to understand that TextView is not saving any data it just showing it. So to show the data you suppose to read it from firebase which you saved it on first step. The same article also showed how to read data. So when it is saved and when you received it ONLY after that you could show it in TextView.
Hope it helps
Hi guys I am trying to save objects with relations in Backendless via API. I have two classes namely Task and Reminder. A task can be associated with many reminders hence I want a 1:N relationship between the Task table and Reminder table in Backendless. My Task class is as follows:
public class Task {
public Date created;
public Date updated;
private List<Reminder> reminders = null;
private String ownerId;
#PrimaryKey
#NonNull
private String objectId;
#NonNull
private String taskTitle;
#NonNull
private Date deadline;
#NonNull
private int isCompleted = 0;
#NonNull
private int isExpired = 0;
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
#NonNull
public String getObjectId() {
return objectId;
}
public void setObjectId(#NonNull String objectId) {
this.objectId = objectId;
}
public List<Reminder> getReminders() {
return reminders;
}
public void setReminders(List<Reminder> reminders) {
this.reminders = reminders;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
#NonNull
public int getIsCompleted() {
return isCompleted;
}
public void setIsCompleted(#NonNull int isCompleted) {
this.isCompleted = isCompleted;
}
#NonNull
public int getIsExpired() {
return isExpired;
}
public void setIsExpired(#NonNull int isExpired) {
this.isExpired = isExpired;
}
public String getTaskTitle() {
return taskTitle;
}
public void setTaskTitle(String taskTitle) {
this.taskTitle = taskTitle;
}
public Date getDeadline() {
return deadline;
}
public void setDeadline(Date deadline) {
this.deadline = deadline;
}
}
Reminder Class:
public class Reminder {
private String title;
private Date time;
private String objectId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
}
I am saving the objects and setting up the relation as below:
public void saveTaskToServer(final Task task) {
List<Reminder> remindersList = new ArrayList<>();
remindersList = task.getReminders();
final List<Reminder> savedReminders = new ArrayList<>();
if(remindersList!=null && remindersList.size()!=0) {
for
(Reminder reminder : remindersList) {
reminder.setTitle(task.getTaskTitle());
Backendless.Persistence.save(reminder, new AsyncCallback<Reminder>() {
#Override
public void handleResponse(Reminder response) {
savedReminders.add(response);
}
#Override
public void handleFault(BackendlessFault fault) {
Log.i("error saving remidners", fault.toString());
}
});
}
}
Backendless.Persistence.save(task, new AsyncCallback<Task>() {
#Override
public void handleResponse(Task response) {
newTask = response;
Log.i("id is ", newTask.getObjectId());
insertTask(response);
snackbarMessage.postValue("Task Created Successfully.");
}
#Override
public void handleFault(BackendlessFault fault) {
Log.i("error", fault.getMessage());
}
});
Backendless.Persistence.of(Task.class).addRelation(task, "reminders", savedReminders, new AsyncCallback<Integer>() {
#Override
public void handleResponse(Integer response) {
Log.i("response", "added" + response);
newTask.setReminders(savedReminders);
}
#Override
public void handleFault(BackendlessFault fault) {
Log.i("response", "error" + fault.toString());
}
});
}
I have tried saving the relation using the tablename:Class:n instead of the parentColumnName. Also tried saving the objectids of the reminders instead of the reminder objects themselves.The task and reminder objects get saved properly in the backendless console in their respective tables but the reminder column in the Task table still remains empty and no relations get added. Relations count in the backendless call in Android Studio also returns 0. Any advice is really appreciated. I have been following this example.
My relations were not getting saved because I was using the async callbacks in backendless!! I dont know why I didnt see that before. Since the save calls were being made before the async callbacks could finish I was ending up with null values. Fixed it by making the calls synchronous and wrapping them in an async task.
How can I retrieve my data from firebase to android studio listview? I watch many tutorials on youtube. I use the codes of what did the tutorial gave, but it doesn't work on mine and also every data in my firebase has a unique ID to separate each data.
Here are the codes that I used:
public class ExisActivity extends AppCompatActivity {
private DatabaseReference mdatabase;
private ListView mListView;
private ArrayList<String> marralist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exis);
mdatabase = FirebaseDatabase.getInstance().getReference();
mListView = (ListView)findViewById(R.id.lvexist);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,marralist);
mListView.setAdapter(arrayAdapter);
}
}
and this is the other code that i used to get the data:
public class SaveData {
public String getEtOwnername() {
return etOwnername;
}
public void setEtOwnername(String etOwnername) {
this.etOwnername = etOwnername;
}
public String getEtAnimalname() {
return etAnimalname;
}
public void setEtAnimalname(String etAnimalname) {
this.etAnimalname = etAnimalname;
}
public String getEtAddress() {
return etAddress;
}
public void setEtAddress(String etAddress) {
this.etAddress = etAddress;
}
public String getEtContactNo() {
return etContactNo;
}
public void setEtContactNo(String etContactNo) {
this.etContactNo = etContactNo;
}
public String getEtDobAge() {
return etDobAge;
}
public void setEtDobAge(String etDobAge) {
this.etDobAge = etDobAge;
}
public String getEtEmail() {
return etEmail;
}
public void setEtEmail(String etEmail) {
this.etEmail = etEmail;
}
public String getEtClinicalNotes() {
return etClinicalNotes;
}
public void setEtClinicalNotes(String etClinicalNotes) {
this.etClinicalNotes = etClinicalNotes;
}
public String getEtMedication() {
return etMedication;
}
public void setEtMedication(String etMedication) {
this.etMedication = etMedication;
}
public String getEtPayMent() {
return etPayMent;
}
public void setEtPayMent(String etPayMent) {
this.etPayMent = etPayMent;
}
public SaveData(String etOwnername, String etAnimalname, String etAddress, String etContactNo, String etDobAge, String etEmail, String etClinicalNotes, String etMedication, String etPayMent) {
this.etOwnername = etOwnername;
this.etAnimalname = etAnimalname;
this.etAddress = etAddress;
this.etContactNo = etContactNo;
this.etDobAge = etDobAge;
this.etEmail = etEmail;
this.etClinicalNotes = etClinicalNotes;
this.etMedication = etMedication;
this.etPayMent = etPayMent;
}
this is my DB structure of my fire base i'm also new to fire base
{
"rules":{
".read": true,
".write": true,
}
}
Can any help me? please provide some link
PLEASE RESPECT MY POST
My goal is to create an app that in basics have two different activities, one in which the user creates a "protocol" (EditorActivity) and on in which the user can view them in a listview(CatalogActivity). If there is something wrong with a protocol, the user must be able to press one of the list view items in the listview, and from there go back in to the EditorActivity and edit the specific item.
My problem is that I have not figured out how to get the old data from the CatalogActivity in to the EditorActivity.
From firebase console:
[Firebase structure][1]
CustomProtocol:
public class CustomProtocol {
public String dateDrill;
public String pileID;
public boolean cleaned;
public CustomProtocol() {
}
public CustomProtocol(String pileID,
String dateDrill,
boolean cleaned) {
this.pileID = pileID;
this.dateDrill = dateDrill;
this.cleaned = cleaned;
}
public void setPileID(String pileID) {
this.pileID = pileID;
}
public String getPileID() {
return pileID;
}
public void setDateDrill(String dateDrill) {
this.dateDrill = dateDrill;
}
public String getDateDrill() {
return dateDrill;
}
}
Snippet from CatalogActivity:
final String projectNumber = projectPrefs.getString(getString(R.string.settings_project_number_key), getString(R.string.settings_project_number_by_default));
mFirebaseDatabase = FirebaseDatabase.getInstance();
mProtocolDatabaseReference = mFirebaseDatabase.getReference().child(projectNumber);
List<CustomProtocol> protocols = new ArrayList<>();
mProtocolAdapter = new ProtocolAdapter(this, R.layout.item_protocol, protocols);
mProtocolListView.setAdapter(mProtocolAdapter);
attachDatabaseReadListener();
mProtocolListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
intent.putExtra("Exiting protocol", EXISTING_PROTOCOL);
}
});
}
EditorActivty:
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
EXISTING_PROTOCOL = intent.getBooleanExtra("Exiting protocol", false);
mEditorFirebaseDatabase = FirebaseDatabase.getInstance();
mEditorProtocolDatabaseReference =
mEditorFirebaseDatabase.getReference().child(projectNumber);
if (EXISTING_PROTOCOL)
mProtocolDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//WHAT GOES HERE SO THAT I CAN POPULATE THE TEXTVIEWS IN THE ACTIVITY_EDITOR WITH THE EXISTING VALUES?
}}
And after this I'm stuck. I guess that I must add something more to the databasereference in the EditorActivity, but I cannot figure out what? Since I don't know the pileID until after the listitem has been clicked? Is there an easier way to do this?
Thank you in advance!
1]: https://i.stack.imgur.com/Bt1mZ.png
You can pass List<CustomProtocol> through intent.
Your CustomProtocol must be implement Parcelable.
Same question is here
1.Make CustomProtocol Parcelable, IDE can do it automatically
public class CustomProtocol implements Parcelable {
public String dateDrill;
public String pileID;
public boolean cleaned;
public CustomProtocol() {
}
public CustomProtocol(String pileID,
String dateDrill,
boolean cleaned) {
this.pileID = pileID;
this.dateDrill = dateDrill;
this.cleaned = cleaned;
}
protected CustomProtocol(Parcel in) {
dateDrill = in.readString();
pileID = in.readString();
cleaned = in.readByte() != 0;
}
public static final Creator<CustomProtocol> CREATOR = new Creator<CustomProtocol>() {
#Override
public CustomProtocol createFromParcel(Parcel in) {
return new CustomProtocol(in);
}
#Override
public CustomProtocol[] newArray(int size) {
return new CustomProtocol[size];
}
};
public void setPileID(String pileID) {
this.pileID = pileID;
}
public String getPileID() {
return pileID;
}
public void setDateDrill(String dateDrill) {
this.dateDrill = dateDrill;
}
public String getDateDrill() {
return dateDrill;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(dateDrill);
parcel.writeString(pileID);
parcel.writeByte((byte) (cleaned ? 1 : 0));
}
}
2.Pass clicked protocol from CatalogActivity to EditorActivity using intent,
mProtocolListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
intent.putExtra("Exiting protocol", EXISTING_PROTOCOL);
intent.putExtra("Clicked protocol object", protocols.get(position));
}
});
3.In editor activity read the clicked protocol though intent.
EXISTING_PROTOCOL = intent.getBooleanExtra("Exiting protocol", false);
protocol = intent.getParcelableExtra("Clicked protocol object");
4.
public void onDataChange(DataSnapshot dataSnapshot) {
//WHAT GOES HERE SO THAT I CAN POPULATE THE TEXTVIEWS IN THE ACTIVITY_EDITOR WITH THE EXISTING VALUES?
// Ans: Find text views by id and set corresponding text from protocol read above.
}}
I'm simply just trying to populate data from Firebase Database into my listview. The logs are showing the data is being retrieved, but the adapter won't set the values to the text in a single list item in the list? All it says is "No setter/field for INSERT VALUE". Which makes me think that I didn't have my setters made correctly but there were auto generated by Android Studio. I don't know what I am missing here. Any help is appreciated.
NODE OBJECT
package com.megliosolutions.ipd.Objects;
import android.graphics.Bitmap;
/**
* Created by Meglio on 6/13/16.
*/
public class NodeObject {
public String mStaticAddress;
public String mLat;
public String mLong;
public NodeObject(){
//needed for firebase
}
public NodeObject(String address, String lat, String Long){
this.mStaticAddress = address;
this.mLat = lat;
this.mLong = Long;
}
public String getmStaticAddress() {
return mStaticAddress;
}
public void setmStaticAddress(String mStaticAddress) {
this.mStaticAddress = mStaticAddress;
}
public String getmLat() {
return mLat;
}
public void setmLat(String mLat) {
this.mLat = mLat;
}
public String getmLong() {
return mLong;
}
public void setmLong(String mLong) {
this.mLong = mLong;
}
}
STATIC LISTADAPTER
/**
* Created by Meglio on 6/14/16.
*/
public class StaticListAdapter extends ArrayAdapter<NodeObject> {
public static String TAG = StaticListAdapter.class.getSimpleName();
public Context mContext;
public List<NodeObject> mNodes;
public class ViewHolder {
TextView mStaticAddress;
TextView mLAT;
TextView mLONG;
}
#Override
public int getCount() {
return mNodes.size();
}
public StaticListAdapter(Context context, List<NodeObject> objects) {
super(context, R.layout.activity_main, objects);
this.mContext = context;
this.mNodes = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
NodeObject node = mNodes.get(position);
if (convertView == null) {
convertView = LayoutInflater.from(this.mContext).inflate(R.layout.node_item, null);
holder.mLONG = (TextView) convertView.findViewById(R.id.node_item_LONG);
holder.mStaticAddress = (TextView) convertView.findViewById(R.id.node_item_IP);
holder.mLAT = (TextView) convertView.findViewById(R.id.node_item_LAT);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mStaticAddress.setText(node.getStaticAddress());
holder.mLONG.setText(node.getLongitude());
holder.mLAT.setText(node.getLatitude());
return convertView;
}
}
MAINACTIVITY
public class MainActivity extends AppCompatActivity {
public static String TAG = MainActivity.class.getSimpleName();
public ListView main_ListView;
public FirebaseAuth mAuth;
public FirebaseUser mUser;
public DatabaseReference mDatabase;
//Strings
public String static_ip;
public String lat = "5.0";
public String mLong = "4.0";
public String currentUser;
//Adapters
public StaticListAdapter listAdapter;
//Node Object
NodeObject node;
public List<NodeObject> nodesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instances
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
currentUser = mUser.getUid();
main_ListView = (ListView)findViewById(R.id.Main_listview);
//Toolbar
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//[End of Toolbar]
nodesList = new ArrayList<>();
retrieveData();
listAdapter = new StaticListAdapter(getApplicationContext(),nodesList);
main_ListView.setAdapter(listAdapter);
Log.i(TAG, "USER: " + currentUser);
}
private void retrieveData() {
mDatabase.child("nodes").child(mUser.getUid())
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
NodeObject nodeObject = dataSnapshot.getValue(NodeObject.class);
listAdapter.add(nodeObject);
listAdapter.setNotifyOnChange(true);
}
#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) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.getGPS:
//nothing
return true;
case R.id.addNode:
addNode();
return true;
case R.id.logout:
signOut();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void signOut() {
mAuth.signOut();
Intent intent = new Intent(MainActivity.this, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Toast.makeText(getApplicationContext(), "Logging Out.", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
private void addNode() {
//AlertDialog
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Dude, assign something...");
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.main_add_node_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editText = (EditText)
dialogView.findViewById(R.id.static_et);
dialogBuilder.setPositiveButton("Assign", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
static_ip = editText.getText().toString();
String ip = static_ip;
node = new NodeObject(ip, lat, mLong);
mDatabase.child("nodes").child(currentUser).push().setValue(node);
Toast.makeText(getApplicationContext(), "Static IP: " + static_ip + " assigned!"
, Toast.LENGTH_SHORT).show();
}
}).
setNegativeButton("Or Not...", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Fine, nvm then..."
, Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.create().show();
}
}
Debugging shows that I am able to get everything client side. Logs show this as well.
06-18 18:25:42.981 12962-12962/com.megliosolutions.ipd D/MainActivity: zHF4TGnRvkeXEbKiLegiUNLGHX12:{-KKLeBAe9pV1Umm3qQMo={mStaticAddress=26161910494949, mLong=3.0, mLat=2.0}, -KKG_ACFvdX7aJOR98-o={mStaticAddress=10.223.22.250, mLong=3.0, mLat=2.0}, -KKWKMZS7WkE_xWbL3rC={mStaticAddress=, mLong=4, mLat=5}, -KKQQLITf9-7iMFlqEWR={mStaticAddress=123123123123, mLong=3.0, mLat=2.0}, -KKG_J6PKwogjBFdk52Z={mStaticAddress=10.333.555.888, mLong=3.0, mLat=2.0}}
UPDATE
The part that didn't make sense to me, but I'm sure makes sense to those who know it very well. Is comprehending what I'm reading the firebase documentation. I read over it a few time, but I guess it just wasn't clicking. I figured out that structuring the data in firebase is KEY. Without that you can't code properly because everything relies on that. Firebase makes it easy to use now that I see it working. I will be making a blog post on this to explain my troubles and how to surpass them so no one else runs into this mess. The below code will build a functional listview with firebase backend!
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
NodeObject nodeObject = dataSnapshot.getValue(NodeObject.class);
listAdapter.add(nodeObject);
listAdapter.setNotifyOnChange(true);
}
In retrieveData(), you should be using a ChildEventListener, not a ValueEventListener. You are adding Node objects as children of node/$uid with the keys generated by push(). The ValueEventListener is returning a Map<String,Object> containing all of the Nodes. That is shown in the logcat output you posted. You can use the onChildAdded() callback of ChildEventListener to get each Node as it is created and then add it to your adapter.
The warning is because the casing mismatches between your field and you setter.
Following the examples in the Firebase documentation, this seems like the better way to model the Java class:
public class NodeObject {
public String staticAddress;
public String lat;
public String lon;
public NodeObject(){
//needed for firebase
}
public NodeObject(String address, String lat, String lon){
this.staticAddress = address;
this.lat = lat;
this.lon = lon;
}
}
As an added bonus this will lead to more sensible JSON property names too.
I had the same issue just now & the answer was pretty frustrating.
I think that the issue is with your naming convention. For example, it looks like you named a variable mLat, and then your accessors/mutators are getmLat() and setmLat(). I think when Firebase is doing the deserialization, they rely on certain naming. For example, if you have a member variable named lat, you will need to have getLat() and setLat().
For your case, you might just be able to change your methods to be getMLat() and setMLat(). Although I'd suggest changing up your conventions a bit in general.
As a side note, know that your naming is typically against convention. Generally, variables prefixed by m are private member variables, accessed & mutated by public methods (like yours).
I was getting an error because I was accessing wrong variable(parent variable)
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
list.add(snapshot.getValue(CategoryModel.class));
// Here in list I should have added dataSnapshot.getValue(CategoryModel.class)
}
}
It may help.