Firebase onClick list in android - android

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.
}}

Related

Firebase real database values differ from the retrieved ones

So, in realtime database I have:
When I retrieve data from database I get:
Model class looks like:
public class User implements Parcelable {
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
#Override
public User createFromParcel(Parcel source) {
return new User(source);
}
#Override
public User[] newArray(int size) {
return new User[size];
}
};
...
private String hasToPayFromPastRides;
private String didNotPayCount;
...;
public User() {
}
public User(..., String didNotPayCount, String hasToPayFromPastRides) {
...
this.didNotPayCount = didNotPayCount;
this.hasToPayFromPastRides = hasToPayFromPastRides;
}
protected User(Parcel in) {
...
this.didNotPayCount = in.readString();
this.hasToPayFromPastRides = in.readString();
}
...
public String getDidNotPayCount() {
return didNotPayCount;
}
public void setDidNotPayCount(String didNotPayCount) {
this.didNotPayCount = didNotPayCount;
}
public String hasToPayFromPastRides() {
return hasToPayFromPastRides;
}
public void setHasToPayFromPastRides(String hasToPayFromPastRides) {
this.hasToPayFromPastRides = hasToPayFromPastRides;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.userId);
dest.writeString(this.userFullName);
dest.writeString(this.userEmail);
dest.writeString(this.userPhoneNumber);
dest.writeString(this.userAvatarUrl);
dest.writeString(this.userLocalAvatar);
dest.writeString(this.userAddress);
dest.writeString(this.userCity);
dest.writeString(this.userArea);
dest.writeString(this.userPostalCode);
dest.writeString(this.userRating);
dest.writeString(this.userTotalRating);
dest.writeString(this.totalTrips);
dest.writeString(this.riskCount);
dest.writeString(this.isBlocked);
dest.writeString(this.isDefaulter);
dest.writeString(this.pendingRating);
dest.writeParcelable(this.pendingRateObj, flags);
dest.writeString(this.didNotPayCount);
dest.writeString(this.hasToPayFromPastRides);
}
}
What surprises me is that one value gets read correctly "didNotPayCount" when "hasToPayFromPastRides" is null. Any ideas?
Your getter isn't named correctly:
public String hasToPayFromPastRides()
It should be:
public String getHasToPayFromPastRides()

How can i stop Listview repeating the titles?

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!

Firebase Retrieve Data

I'm trying to display from data from my Firebase database show in Firebase Recyclerview , This my Database
And i try use the same as tutorial code from
Firebase UI
I'm try and get this result
I'm fairly new to Android and programming in general, so any help would be appreciated. Here is the relevant code.
PostlistFragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mActivity = getActivity();
final Dialog mDialog = new Dialog(mActivity, R.style.NewDialog);
mDialog.addContentView(
new ProgressBar(mActivity),
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
);
mDialog.setCancelable(true);
mDialog.show();
// Set up Layout Manager, reverse layout
LinearLayoutManager mManager = new LinearLayoutManager(mActivity);
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
// Set up FirebaseRecyclerAdapter with the Query
Query postsQuery = getQuery(mDatabase);
mAdapter = new FirebaseRecyclerAdapter<PostMainboard, MainboardViewHolder>(PostMainboard.class, R.layout.mainboard_list, MainboardViewHolder.class, postsQuery) {
#Override
public void onDataChanged() {
super.onDataChanged();
mDialog.dismiss();
}
#Override
protected void populateViewHolder(final MainboardViewHolder viewHolder, final PostMainboard model, final int position) {
final DatabaseReference postRef = getRef(position);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, MainboardDetailActivity.class);
intent.putExtra(MainboardDetailActivity.EXTRA_POST_KEY, postRef.getKey());
startActivity(intent);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.cleanup();
}
}
public abstract Query getQuery(DatabaseReference databaseReference);
And result of my detail activity got same not show every one
Here My Detail Activity Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_mainboard_detail);
mBodyView = (TextView)findViewById(R.id.post_detail);
mAuthorView = (TextView)findViewById(R.id.txt_author);
mTitleView = (TextView)findViewById(R.id.post_topic);
mDateView = (TextView)findViewById(R.id.post_date_time);
mCommentsRecycler = (RecyclerView) findViewById(R.id.recycler_comments);
mCommentsRecycler.setLayoutManager(new LinearLayoutManager(this));
mCommentField = (EditText) findViewById(R.id.comment_field);
Button mCommentButton = (Button) findViewById(R.id.button_post_comment);
mCommentButton.setOnClickListener(this);
// Get post key from intent
String mPostKey = getIntent().getStringExtra(EXTRA_POST_KEY);
if (mPostKey == null) {
throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
}
// Initialize Database
mPostReference = FirebaseDatabase.getInstance().getReference().child("mainboard").child(mPostKey);
mCommentsReference = FirebaseDatabase.getInstance().getReference().child("cm-mainboard").child(mPostKey);
}
#Override
public void onStart() {
super.onStart();
// Add value event listener to the post
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
PostMainboard post = dataSnapshot.getValue(PostMainboard.class);
User user = dataSnapshot.getValue(User.class);
mAuthorView.setText(user.uid);
mTitleView.setText(post.postTopic);
mBodyView.setText(post.postDetail);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
Toast.makeText(MainboardDetailActivity.this, "Failed to load post.", Toast.LENGTH_SHORT).show();
}
};
mPostReference.addValueEventListener(postListener);
// Keep copy of post listener so we can remove it when app stops
mPostListener = postListener;
// Listen for comments
mAdapter = new CommentAdapter(this, mCommentsReference);
mCommentsRecycler.setAdapter(mAdapter);
}
#Override
public void onStop() {
super.onStop();
if (mPostListener != null) {
mPostReference.removeEventListener(mPostListener);
}
mAdapter.cleanupListener();
}
Post Class
public class PostMainboard{
public String uid;
public String auther;
public String postTopic;
public String postDetail;
public String postImageUrl;
public String postID;
private String postlatlon;
public long timeCreated;
public PostMainboard(){
}
public PostMainboard(String uid, String auther , String postTopic , String postDetail,long timeCreated)
{
this.uid = uid;
this.auther = auther;
this.postTopic = postTopic;
this.postDetail = postDetail;
this.postImageUrl = postImageUrl;
this.postID = postID;
this.timeCreated = timeCreated;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("mb_id", uid);
result.put("mb_auther" , auther);
result.put("mb_title", postTopic);
result.put("mb_body", postDetail);
result.put("mb_create", timeCreated);
return result;
}
User class
public class User {
public String uid;
public String user_fname;
private String user_lname;
private String user_idcard;
private String email;
private String user_phone;
public User(){
}
public User(String uid ,String user_fname, String user_lname, String user_idcard, String email, String user_phone) {
this.uid = uid;
this.user_fname = user_fname;
this.user_lname = user_lname;
this.user_idcard = user_idcard;
this.email = email;
this.user_phone = user_phone;
}
ViewHolder
public class MainboardViewHolder extends RecyclerView.ViewHolder {
private TextView authorView;
private TextView bodyView;
private TextView titleView;
private TextView dateView;
public MainboardViewHolder(View itemView) {
super(itemView);
authorView = (TextView)itemView.findViewById(R.id.txt_author);
bodyView = (TextView)itemView.findViewById(R.id.post_detail);
titleView = (TextView)itemView.findViewById(R.id.post_topic);
dateView = (TextView)itemView.findViewById(R.id.post_date_time);
}
public void bindToPost (PostMainboard postMainboard)
{
authorView.setText(postMainboard.auther);
bodyView.setText(postMainboard.postDetail);
titleView.setText(postMainboard.postTopic);
dateView.setText((int) postMainboard.timeCreated);
}
Mainboard fragment
public class MainboardFragment extends PostListFragment{
public MainboardFragment() {
// Required empty public constructor
}
#Override
public Query getQuery(DatabaseReference databaseReference) {
return databaseReference.child("mainboard").orderByKey();
}
It looks like you have forgotten to populate the ViewHolder (MainboardViewHolder).
In "PostlistFragment" under "populateViewHolder" you need to call viewHolder.bindToPost(model) to bind the data to your textviews and so forth.
Try this:
#Override
protected void populateViewHolder(final MainboardViewHolder viewHolder, final PostMainboard model, final int position) {
final DatabaseReference postRef = getRef(position);
viewHolder.bindToPost(model);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mActivity, MainboardDetailActivity.class);
intent.putExtra(MainboardDetailActivity.EXTRA_POST_KEY, postRef.getKey());
startActivity(intent);
}
});
}
Also, your getQuery method is abstract and empty. It should probably look like this:
#Override
public Query getQuery(DatabaseReference databaseReference) {
return databaseReference.getReference("mainboard").orderByKey();
}
I'm saying "probably" because I can't see how you have initialized mDatabase. In the future, please paste complete code if you wan't better and faster answers.

No setter/field for warning Firebase Database Retrieve Data Populate Listview

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.

Passing ArrayLists in Android

I'm trying to pass array lists between activities in Android. The lists contains strings. I've read a lot about Parcelable. Would I need to create a Parcelable to pass a String array list? As of now I am using putStringArrayListExtra() and getSringArrayListExtra() to pass the lists through intents.
Here is some of my code.
Intent load = new Intent(getApplicationContext(), HelloTabWidget.class);
load.putStringArrayListExtra("albums", albums);
load.putStringArrayListExtra("songs", songs);
load.putStringArrayListExtra("artists", artists);
load.putStringArrayListExtra("fileName", fileName);
This is my onCreate method for the acticity which obtains the array list.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songlist);
Bundle extras = getIntent().getExtras();
isArtists = extras.getBoolean("artists");
isAlbums = extras.getBoolean("albums");
isSongs = extras.getBoolean("songs");
Intent get = getIntent();
songs = get.getStringArrayListExtra("songs");
artists = get.getStringArrayListExtra("artists");
albums = get.getStringArrayListExtra("albums");
fileName = get.getStringArrayListExtra("fileName");
if(isArtists == true)
updateArtistsList();
else if(isAlbums == true)
updateAlbumsList();
else if(isSongs == true)
updateSongList();
}
The class which retrieves the list is supposed to create a listView from the data in the lists. Whenever I run the code i get nullPointerExceptions when trying to make the lists. I know that my listView code works, so I have narrowed down the problem to the intents which pass the array lists.
Thanks in advance.
EDIT:
Here are the first few lines from the logcat.
12-28 03:03:42.313: E/AndroidRuntime(873): FATAL EXCEPTION: main
12-28 03:03:42.313: E/AndroidRuntime(873): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adam.mediaplayer/com.adam.mediaplayer.HelloTabWidget}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adam.mediaplayer/com.adam.mediaplayer.MakeListActivity}: java.lang.NullPointerException
It depends on the type of arraylist
putIntegerArrayListExtra(String name, ArrayList<Integer> value)
putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)
putStringArrayListExtra(String name, ArrayList<String> value)
putCharSequenceArrayListExtra(String name, ArrayList<CharSequence> value)
Then you can read from you next activity by replacing put with get with key string as argument,eg
myIntent.getStringArrayListExtra("arrayListName");
Here is how you can pass an ArrayList :
MyListClass.java - Custom class
public class MyListClass implements Parcelable{
private int test;
public MyListClass()
{}
public MyListClass(Parcel read){
test = read.readInt();
}
public int getTest() {
return test;
}
public void setTest(int test) {
this.test = test;
}
public static final Parcelable.Creator<MyListClass> CREATOR =
new Parcelable.Creator<MyListClass>() {
#Override
public MyListClass createFromParcel(Parcel source) {
return new MyListClass(source);
}
#Override
public MyListClass[] newArray(int size) {
return new MyListClass[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeInt(test);
}
}
MyParcelable.java
public class MyParcelable implements Parcelable {
private List<MyListClass> arrList = new ArrayList<MyListClass>();
private int myInt = 0;
private String str = null;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public List<MyListClass> getArrList() {
return arrList;
}
public void setArrList(List<MyListClass> arrList) {
this.arrList = arrList;
}
public int getMyInt() {
return myInt;
}
public void setMyInt(int myInt) {
this.myInt = myInt;
}
MyParcelable() {
// initialization
arrList = new ArrayList<MyListClass>();
}
public MyParcelable(Parcel in) {
myInt = in.readInt();
str = in.readString();
in.readTypedList(arrList, MyListClass.CREATOR);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel outParcel, int flags) {
outParcel.writeInt(myInt);
outParcel.writeString(str);
outParcel.writeTypedList(arrList);
}
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
#Override
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
#Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
}
MainAcitivty.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrList.add(new MyListClass());
arrList.get(0).setTest(200);
MyParcelable object = new MyParcelable();
object.setMyInt(100);
object.setArrList(arrList);
Intent intent = new Intent(MainActivity.this,ReceiverParcel.class);
intent.putExtra("parcel", object);
startActivity(intent);
}
ReceiverParcel.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
MyParcelable object = b.getParcelable("parcel");
System.out.println(object.getArrList().get(0).getTest());
System.out.println(object.getMyInt());
}

Categories

Resources