How to add click Counter, Store in Firebase and Retrieve [duplicate] - android

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

Related

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!

Passing firebase data to another activity in form of ArrayList (Android)

The problem is that it always gives "List:NULL" Toast in MainActivity and list is not passed I suppose. Please help, trying for 2 days. Help me!!
I am confused as to how I should pass the ArrayList from Firebase database to my MainActivity.
Before doing the below thing, I tried to pass ArrayList in onCreate of Splash activity after it fetched from firebase but myWebLinks always came null when I used in onCreate except on onDataChange of ValueEventListener so I couldn't pass in next activity.
This is my SplashActivity.class
public class SplashActivity extends AppCompatActivity {
private static final String TAG = "abcd";
//1 Firebase database object
//entry point for the app to access our database
private FirebaseDatabase mFirebaseDatabase;
//2 is a class that reference a specific part of the database, references 'link' portion of DB
private DatabaseReference mDatabaseReference;
//To read from DB, attach ChildEventListener object to the reference. Allows to listen and have code triggered whenever
//changes occur on the node.
private ValueEventListener mValueEventListener;
private AVLoadingIndicatorView aviIV;
private ArrayList<WebLinks> mywebLinks;
public GenericTypeIndicator<ArrayList<WebLinks>> genericTypeIndicator;
private long seed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
aviIV = findViewById(R.id.avi);
aviIV.smoothToShow();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference().child("weblinks");
if (mValueEventListener == null) {
valueEventListener();
}
}
#Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause: ");
//14 Removing
if (mValueEventListener != null) {
mDatabaseReference.removeEventListener(mValueEventListener);
mValueEventListener = null;
}
}
#Override
protected void onResume() {
super.onResume();
if (mValueEventListener == null) {
valueEventListener();
mDatabaseReference.addValueEventListener(mValueEventListener);
}
}
void valueEventListener() {
final long[] value = {0};
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
/* This method is called once with the initial value and again whenever data at this location is updated.*/
value[0] = dataSnapshot.getChildrenCount();
genericTypeIndicator = new GenericTypeIndicator<ArrayList<WebLinks>>() {
};
mywebLinks = dataSnapshot.getValue(genericTypeIndicator);
seed = System.nanoTime();
Collections.shuffle(mywebLinks, new Random(seed));
Toast.makeText(SplashActivity.this, "" + mywebLinks.get(0).getName(), Toast.LENGTH_SHORT).show();
Log.i(TAG, "getWebLinksFirebaseeee: on");
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.putParcelableArrayListExtra("web_links", mywebLinks);
startActivity(intent);
SplashActivity.this.finish();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
};
mDatabaseReference.addValueEventListener(mValueEventListener);
}
}
This is my MainActivity.class
public class MainActivity extends AppCompatActivity {
private WebView myWebView;
private WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
private Toolbar mtoolBar;
private ShineButton mFavBtn;
private BoomMenuButton leftBmb;
public static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
leftBmb = (BoomMenuButton) findViewById(R.id.action_bar_left_bmb);
mFavBtn = (ShineButton) findViewById(R.id.favBtn);
mFavBtn.init(this);
mtoolBar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(mtoolBar);
if (getSupportActionBar() != null) {
getSupportActionBar().setElevation(0);
}
ArrayList<WebLinks> myList = getIntent().getParcelableExtra("web_links");
if(myList==null)
Toast.makeText(this, "LIST:NULL", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "LIST:"+myList.get(1).getName(), Toast.LENGTH_SHORT).show();
myWebView = findViewById(R.id.webView);
initWebSettings();
initSwipeRefresh();
initLeftBtn();
}
This is my class
public class WebLinks implements Parcelable {
private String name;
private String link;
public WebLinks() {
}
public WebLinks(String webName, String webLink) {
this.name = webName;
this.link = webLink;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public static final Parcelable.Creator<WebLinks> CREATOR = new Creator<WebLinks>() {
public WebLinks createFromParcel(Parcel source) {
WebLinks fields = new WebLinks();
fields.name = source.readString();
fields.link = source.readString();
return fields;
}
public WebLinks[] newArray(int size) {
return new WebLinks[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(name);
parcel.writeString(link);
}
}

retrieving firebase data to listview with a unique ID using android studio

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

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.

How to add data to list and use its data on next page and show in listview

I have 2 class one is login_class second is student_class which is showing details of student.
What i have to do is when i login. In response i get the students details like
student_name,student_srno,student_father_name,student_mother_name etc.
This is my bean(Getter Setter) class
package com.smartschoolapp;
public class Bean {
String username, password, srno, studentname, classname, sec, contact,
father_name, mother_name, dob;
public Bean(String username,String password,String srno,String studentname,String classname,String sec,String contact,String father_name,String mother_name,String dob) {
this.username=username;
this.password= password;
this.srno=srno;
this.studentname=studentname;
this.classname=classname;
this.sec=sec;
this.contact=contact;
this.father_name=father_name;
this.mother_name=mother_name;
this.dob =dob;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSrno() {
return srno;
}
public void setSrno(String srno) {
this.srno = srno;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getSec() {
return sec;
}
public void setSec(String sec) {
this.sec = sec;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getFather_name() {
return father_name;
}
public void setFather_name(String father_name) {
this.father_name = father_name;
}
public String getMother_name() {
return mother_name;
}
public void setMother_name(String mother_name) {
this.mother_name = mother_name;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public Bean() {
}
}
And this is my login_class where i add data of the student in list.
class login_class extends activity{
Bean beanobj;
List student_detail_list;
.....
{
String name = getting data from response;
......... so on
beanobj = new Bean();
beanobj.studentname(name);
beanobj.student_parent_name(parentname);
.............so on
}
order_list.add(beanobj); // the details to list
}
Now the next activity student_class where i want to show the student in listview
public class student_class extends Activity {
ListView student_listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_list);
student_listview = (ListView) findViewById(R.id.student_listview);
}
}
*==>> in login_class i have created List student_detail_list how can i get it in my student_class class and retrieve data .
Thanks
There are a lot a ways to do that. 1.Recommended Solution : How to pass an object from one activity to another on Android you can serialize your objects and put it into the intent. This is the recommended solution but there are some problems here. If your data contains a lot of memory, it might crash your application in runtime.
2. You can save your array into the file, send file path to other activity as with URL. In the second activity read the file and create the array in second activity as well.
3. My favourite solution is create a singleton class for student array, reach the class in any activity you want. But you should be careful because singleton pattern has some issues by design also it will stay in memory all the time
Realize the "class Bean implements Parcelable". When go to "student_class" from "login_class", just put the "student bean data" inside the Intent. After going to student_class, you can get the "student bean data" from the intent, here the sample code:
Intent intent = new Intent(login_class.this, student_class.class)
intent.putParcelableArrayListExtra("content", student_detail_list);
startActivity(intent);
In "student_class":
student_detail_list = getIntent().getParcelableArrayListExtra("content");

Categories

Resources