I'm developing an app and in first activity it has card view layout. I'm retrieving data from a webservice and relevant data are showed in card view. It's working well. Now when a user clicks a particular card view I need to go for another activity. I'm getting relevant ID for that card view and passing it to the second activity. In second activity I need to show the content according to that unique Id. But I'm not getting any thing. This is what I tried.
Pojo class
public class PromoDetails {
String PromoId;
String PromoName;
String PromoImg;
String promoDetails;
String promoValidty;
public PromoDetails(String PromoId, String PromoName, String PromoImg , String promoDetails , String promoValidity) {
this.PromoId = PromoId;
this.PromoName = PromoName;
this.PromoImg = PromoImg;
this.promoDetails = promoDetails;
this.promoValidty = promoValidity;
}
public String getPromoId() {
return PromoId;
}
public void setPromoId(String promoId) {
PromoId = promoId;
}
public String getPromoName() {
return PromoName;
}
public void setPromoName(String promoName) {
PromoName = promoName;
}
public String getPromoImg() {
return PromoImg;
}
public void setPromoImg(String promoImg) {
PromoImg = promoImg;
}
public String getPromoDetails() {
return promoDetails;
}
public void setPromoDetails(String promoDetails) {
this.promoDetails = promoDetails;
}
public String getPromoValidty() {
return promoValidty;
}
public void setPromoValidty(String promoValidty) {
this.promoValidty = promoValidty;
}}
ApiInterface
public interface ApiInterface {
#POST("ap/promotions.php")
Call<List<Promotions>> getPromotions();
#GET("test.php/promotions/{PromoId}")
Call<List<PromoDetails>> getPromotDetails(#Path("PromoId") String PromoId) ;}
New Activity class
public class PromotionsInside extends Activity {
private ApiInterface apiInterface;
private List<PromoDetails> promoDetails;
TextView prDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.promo_inside);
Bundle extras = getIntent().getExtras();
String promoId = "";
if (extras != null) {
promoId = extras.getString("PROMO_ID");
getPromotionUpdate(promoId);
}
}
private void getPromotionUpdate(String myPromoId) {
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<PromoDetails>> call = apiInterface.getPromotDetails(myPromoId);
call.enqueue(new Callback<List<PromoDetails>>() {
#Override
public void onResponse(Call<List<PromoDetails>> call, Response<List<PromoDetails>> response) {
promoDetails = response.body();
runOnUiThread(new Runnable() {
#Override
public void run() {
prDescription = (TextView)findViewById(R.id.promoDescriptionsss) ;
prDescription.setText(promoDetails.get(0).getPromoName());
}
});
}
#Override
public void onFailure(Call<List<PromoDetails>> call, Throwable t) {
}
});
}}
I have similar case. Try to use this to start second activity:
Intent intent = new Intent(this, PromotionsInside.class);
//Make sure that you put String id in intent
intent.putExtra("PROMO_ID", id);
startActivity(intent);
And this in second activity:
if (getIntent().hasExtra("PROMO_ID")) {
String id = getIntent().getStringExtra("PROMO_ID", null);
//next steps that you need
}
Hope it will help you
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
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);
}
}
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
I want to retrieve data from a web service to textview. Web service works well. I'm using retrofit for network. But I'm getting null in prmoDetails here response.body. I have checked and tried all past solutions as well. But still it's not working. Please help me to solve this.
POJO class
public class PromoDetails {
private String PromoId;
private String PromoName;
private String Category;
private String PromoImg;
private String promoDetails;
private String promoValidty;
public PromoDetails(String PromoId, String PromoName, String Category , String PromoImg , String promoDetails , String promoValidity) {
this.PromoId = PromoId;
this.PromoName = PromoName;
this.Category = Category;
this.PromoImg = PromoImg;
this.promoDetails = promoDetails;
this.promoValidty = promoValidity;
}
public String getPromoId() {
return PromoId;
}
public void setPromoId(String promoId) {
PromoId = promoId;
}
public String getPromoName() {
return PromoName;
}
public void setPromoName(String promoName) {
PromoName = promoName;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getPromoImg() {
return PromoImg;
}
public void setPromoImg(String promoImg) {
PromoImg = promoImg;
}
public String getPromoDetails() {
return promoDetails;
}
public void setPromoDetails(String promoDetails) {
this.promoDetails = promoDetails;
}
public String getPromoValidty() {
return promoValidty;
}
public void setPromoValidty(String promoValidty) {
this.promoValidty = promoValidty;
}}
Api Interface
public interface ApiInterface {
#POST("ap/promotions.php")
Call<List<PromoDetails>> getPromotions();}
MainActivity
public class MainActivity extends AppCompatActivity {
private ApiInterface apiInterface;
private List<PromoDetails> promoDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getPromotionUpdate();
}
private void getPromotionUpdate() {
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<PromoDetails>> call = apiInterface.getPromotions();
call.enqueue(new Callback<List<PromoDetails>>() {
#Override
public void onResponse(Call<List<PromoDetails>> call, Response<List<PromoDetails>> response) {
promoDetails = response.body();
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView prDescription = (TextView)findViewById(R.id.TextView1) ;
prDescription.setText(promoDetails.get(0).getPromoId());
}
});
}
#Override
public void onFailure(Call<List<PromoDetails>> call, Throwable t) {
}
});
}}
My web service like this
[{"promoId":"7","companyName":"Pizza Hut","pName":"Connecting Dots TEDXCOLOMBO 2017","category":"EVENTS","pImg":"https:\/\/androidsra.000webhostapp.com\/img_ap\/tedx.png"},{"promoId":"6","companyName":"Subway","pName":"BUY any SUB & get another SUB FREE!","category":"FOODS & DRINKS","pImg":"https:\/\/androidsra.000webhostapp.com\/img_ap\/subway.png"},{"promoId":"5","companyName":"KFC ","pName":"40% off at Queens Hotel - Kandy for HSBC Credit cards.","category":"BANKS & CARDS","pImg":"https:\/\/androidsra.000webhostapp.com\/img_ap\/queens.png"},{"promoId":"4","companyName":"Pizza Hut","pName":"New sets of Furniture with special discounts.","category":"HOME & KITCHEN","pImg":"https:\/\/androidsra.000webhostapp.com\/img_ap\/singerfur_promo.png"},{"promoId":"3","companyName":"Browns Tours","pName":"Exclusive Offer !! Fly to Melbourne with Srilankan Airlines from Browns Tours","category":"TRAVEL","pImg":"https:\/\/androidsra.000webhostapp.com\/img_ap\/melbourne_promo.png"},{"promoId":"2","companyName":"KFC ","pName":"Hot Drumlets with 2L Pepsi for just Rs.1100\/- only","category":"FOODS & DRINKS","pImg":"https:\/\/androidsra.000webhostapp.com\/img_ap\/kfc_promo.png"},{"promoId":"1","companyName":"Pizza Hut","pName":"50% Off for Medium Pizzas.","category":"FOODS & DRINKS","pImg":"https:\/\/androidsra.000webhostapp.com\/img_ap\/pizza_promo.png"}]
I think it's because your pojo class variables doesn't match with your response variables. Either use #SerializedName annotation or basically change your pojo definitions as exactly as in your response. For example:
#SerializedName("promoId")
private String PromoId;
#SerializedName("pName")
private String PromoName;
or
private String promoId;
private String pName;
As you are not passing any data to getPromotions i presume its a get Method. make following changes in code
public interface ApiInterface {
change --------> #GET("ap/promotions.php")
Call<List<PromoDetails>> getPromotions();}
and change your pojo class to following
public class Example {
#SerializedName("promoId")
#Expose
private String promoId;
#SerializedName("companyName")
#Expose
private String companyName;
#SerializedName("pName")
#Expose
private String pName;
#SerializedName("category")
#Expose
private String category;
#SerializedName("pImg")
#Expose
private String pImg;
public String getPromoId() {
return promoId;
}
public void setPromoId(String promoId) {
this.promoId = promoId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getPName() {
return pName;
}
public void setPName(String pName) {
this.pName = pName;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPImg() {
return pImg;
}
public void setPImg(String pImg) {
this.pImg = pImg;
}
}
why your post method don't have any passing parameters???
Check method, is it GET or POST?
If it is GET,
then change it to #GET("ap/promotions.php") , other code will be same.
check response.isSuccessful() before getting the body, if it is false get response.errorBody() and that will show you the cause of error
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.