Display images from Firebase Realtime Database using recyclerView in Androidx - android

Guys i'm trying to build App like Instagram. I'm struck to fetch the data from the Firebase database and storage. The recyclerView is showing nothing. Help me out in fixing that.
all the data are store in Firebase database.
Recyclerview Adapter page in the fragment page
ProgressBar proBar;
private FirebaseAuth.AuthStateListener authStateListener;
Context context;
String cuurentUser;
FirebaseAuth firebaseAuth;
FirebaseRecyclerAdapter adapter;
RecyclerView recyclerView;
List<Post> postingList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_reviews, container, false);
PostAdapter postAdapter = new PostAdapter(context, postingList);
recyclerView = view.findViewById(R.id.recycView);
proBar = view.findViewById(R.id.proBar);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(postAdapter);
postAdapter.notifyDataSetChanged();
firebaseAuth = FirebaseAuth.getInstance();
cuurentUser = firebaseAuth.getCurrentUser().getUid();
getDetails();
return view;
}
private void getDetails() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Query query = FirebaseDatabase.getInstance().getReference().child("Posts").child(cuurentUser);
FirebaseRecyclerOptions<Post> options = new FirebaseRecyclerOptions.Builder<Post>()
.setQuery(query, new SnapshotParser<Post>() {
#NonNull
#Override
public Post parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Post(snapshot.child("id").getValue().toString(),
snapshot.child("profileImg").getValue().toString(),
snapshot.child("username").getValue().toString(),
snapshot.child("postImg").getValue().toString(),
snapshot.child("description").getValue().toString(),
snapshot.child("time").getValue().toString(),
snapshot.child("date").getValue().toString(),
snapshot.child("title").getValue().toString()
);
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(options) {
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_item, parent, false);
//PostViewHolder viewHolder = new PostViewHolder(view);
return new PostViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final PostViewHolder holder, final int position, #NonNull final Post model) {
// String uid = getRef(position).getKey();
holder.uname.setText(model.getUsername());
holder.descrip.setText(model.getDescription());
holder.ptime.setText(model.getTime());
holder.pdate.setText(model.getDate());
holder.ptitle.setText(model.getTitle());
Glide.with(getContext()).load(model.getProfileImg()).into(holder.profImg);
Glide.with(getContext()).load(model.getPostImg()).into(holder.postImage);
holder.linear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
}
}, 2000);
}
#Override
public void onStart() {
super.onStart();
if(postingList != null)
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
TextView uname, fname, descrip, ptime, pdate, ptitle;
CircleImageView profImg;
ImageView postImage;
View mview;
LinearLayout linear;
public PostViewHolder(#NonNull View itemView) {
super(itemView);
mview = itemView;
linear = itemView.findViewById(R.id.linearRoot);
uname = itemView.findViewById(R.id.username);
fname = itemView.findViewById(R.id.fullname);
descrip = itemView.findViewById(R.id.description);
ptime = itemView.findViewById(R.id.ptime);
pdate = itemView.findViewById(R.id.pdate);
ptitle = itemView.findViewById(R.id.ptitle);
profImg = itemView.findViewById(R.id.profImg);
postImage = itemView.findViewById(R.id.postImg);
}
}
model page as Post.java
public class Post implements Parcelable {
public Post() {
}
private String uid;
private String postImg;
private String description;
private String username;
private String date;
private String time;
private String profileImg;
private String title;
public Post(String uid, String postImg, String description, String username, String date, String time, String profileImg, String title) {
this.uid = uid;
this.postImg = postImg;
this.description = description;
this.username = username;
this.date = date;
this.time = time;
this.profileImg = profileImg;
this.title = title;
}
protected Post(Parcel in) {
uid = in.readString();
postImg = in.readString();
description = in.readString();
username = in.readString();
date = in.readString();
time = in.readString();
profileImg = in.readString();
title = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
#Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
#Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPostImg() {
return postImg;
}
public void setPostImg(String postImg) {
this.postImg = postImg;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getProfileImg() {
return profileImg;
}
public void setProfileImg(String profileImg) {
this.profileImg = profileImg;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(uid);
dest.writeString(postImg);
dest.writeString(description);
dest.writeString(username);
dest.writeString(date);
dest.writeString(time);
dest.writeString(profileImg);
dest.writeString(title);
}
}
xml page with recyclerView
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TabLayout.ReviewsFragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycView"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/proBar"/>
</FrameLayout>
Another xml page to show the details is post_item.xml

Related

RecyclerView shows only two textview?others are not display...items are not displaying

i have facing issue like only two items are displayed others two items are not displayed they are contact and flat no this items are not displaying...i tried also removing and adding others textview but through this only two items are displayed.... Now I want to display the data on a RecyclerView which doesn't seem to work, I'm pretty sure that my code is good but something doesn't seem to work and I can't find it.i also try all the things suggested by stackoverflow but nothing can happen so that i think i need to ask...
Here the file
public class RecieptFP extends AppCompatActivity {
private RecyclerView mFirestoreList;
private FirebaseFirestore firebasefirestore;
private FirestoreRecyclerAdapter adapter;
Button Back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reciept_fp);
Back = findViewById(R.id.btndashboard);
firebasefirestore = FirebaseFirestore.getInstance();
mFirestoreList = findViewById(R.id.firestore_list);
//query
Query query = firebasefirestore.collection("UserDataR");
//RecyclerOptions
FirestoreRecyclerOptions<RecieptModel> options = new FirestoreRecyclerOptions.Builder<RecieptModel>()
.setQuery(query, RecieptModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<RecieptModel, RecieptViewHolder>(options) {
#NonNull
#Override
public RecieptViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listsingleiteam, parent, false);
return new RecieptViewHolder(view);
}
#Override
protected void onBindViewHolder(RecieptViewHolder recieptViewHolder, int i, RecieptModel recieptModel) {
recieptViewHolder.list_name.setText(recieptModel.getName());
recieptViewHolder.list_amount.setText(recieptModel.getAmount());
recieptViewHolder.list_contact.setText(recieptModel.getContact());
recieptViewHolder.list_Flatno.setText(recieptModel.getFlatNo());
}
};
//viewholder
mFirestoreList.setHasFixedSize(false);
mFirestoreList.setLayoutManager(new LinearLayoutManager(this));
mFirestoreList.setAdapter(adapter);
Back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i1 = new Intent(RecieptFP.this, Dashboard.class);
startActivity(i1);
}
});
}
private class RecieptViewHolder extends RecyclerView.ViewHolder {
private TextView list_name;
private TextView list_amount;
private TextView list_contact;
private TextView list_Flatno;
public RecieptViewHolder(#NonNull View itemView) {
super(itemView);
list_name = itemView.findViewById(R.id.list_name);
list_amount = itemView.findViewById(R.id.list_amount);
list_contact = itemView.findViewById(R.id.list_contact);
list_Flatno = itemView.findViewById(R.id.list_Flatno);
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Recipet Model
package com.societypay;
public class RecieptModel {
private String Name;
private String Amount;
private String Contact;
private String FlatNo;
private RecieptModel(){}
private RecieptModel(String Name,String Amount,String Contact,String FlatNo){
this.Name=Name;
this.Amount=Amount;
this.Contact=Contact;
this.FlatNo=FlatNo;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAmount() {
return Amount;
}
public void setAmount(String amount) {
Amount = amount;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getFlatNo() {
return FlatNo;
}
public void setFlatNo(String flatNo) {
FlatNo = flatNo;
}
}
Please use following pojo and try.
public class RecieptModel
{
private String MobileNo;
private String Amount;
private String Flat_no;
private String Name;
public String getMobileNo ()
{
return MobileNo;
}
public void setMobileNo (String MobileNo)
{
this.MobileNo = MobileNo;
}
public String getAmount ()
{
return Amount;
}
public void setAmount (String Amount)
{
this.Amount = Amount;
}
public String getFlat_no ()
{
return Flat_no;
}
public void setFlat_no (String Flat_no)
{
this.Flat_no = Flat_no;
}
public String getName ()
{
return Name;
}
public void setName (String Name)
{
this.Name = Name;
}
#Override
public String toString()
{
return "ClassPojo [MobileNo = "+MobileNo+", Amount = "+Amount+", Flat_no = "+Flat_no+", Name = "+Name+"]";
}
}

RecyclerView is not being populated with items from firebase just a blank Activity Page

I'm still relatively new to Android and firebase and trying to populate recyclerview from firebase database but for some reasons that I can't get, the view is not populated.The activity loads but all I see is a blank activity page.I'd like to populate these views using data from a Firebase Database just to get three data(name,email,phonenos) of Users.
public class TestUsersActivity extends AppCompatActivity {
public TextView mname,email,phone;
private RecyclerView recyclerView;
FirebaseAuth mAuth;
DatabaseReference mDatabase;
private FirebaseRecyclerAdapter adapter;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_users);
recyclerView = findViewById(R.id.listuser);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
fetch();
}
private void fetch() {
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(mDatabase,Users.class)
.build();
adapter = new FirebaseRecyclerAdapter<Users, ViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ViewHolder myViewHolder, int i, #NonNull Users users) {
myViewHolder.setName(users.getFname() + " "+ users.getLname());
myViewHolder.setEmail(users.getEmail());
myViewHolder.setphone(users.getPhonenos());
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_list_row,parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onDataChanged() {
super.onDataChanged();
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
mname = itemView.findViewById(R.id.name);
email = itemView.findViewById(R.id.email);
phone = itemView.findViewById(R.id.phoneNos);
}
public void setName(String string) {
mname.setText(string);
}
public void setEmail(String string) {
email.setText(string);
}
public void setphone(String string){
phone.setText(string);
}
}
}
Below is my modelclass that i want to get just the name,email and phone nos from.
public class Users {
private String fname;
private String lname;
private String email;
private String phonenos;
private String jobTitle;
private String dateCreated;
private String lastlogin;
public Users(){
}
public Users(String fname, String lname, String email, String phonenos, String jobTitle, String dateCreated, String lastlogin) {
this.fname = fname;
this.lname = lname;
this.email = email;
this.phonenos = phonenos;
this.jobTitle = jobTitle;
this.dateCreated = dateCreated;
this.lastlogin = lastlogin;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenos() {
return phonenos;
}
public void setPhonenos(String phonenos) {
this.phonenos = phonenos;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public String getLastlogin() {
return lastlogin;
}
public void setLastlogin(String lastlogin) {
this.lastlogin = lastlogin;
}
}
I don't know if you must pass a query instead of a database reference
make the query a member variable
......
private Query query;
......
do this:
query = FirebaseDatabase.getInstance().getReference().child("Users");
and pass it like this to options
FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(query,Users.class)
.build();
ALSO MAKE SURE YOUR FIREBASE SECURITY RULES ARE NOT SET TO READ FALSE

com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.ArrayList to String

I'm doing a search in my firebase database (real time database), but I'm having these errors in return, could someone help me fix it?
this search is being done through an application I have the following error
PID: 15597
com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.ArrayList to String
MAINACTIVITY
public class SalasActivity extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_salas);
mUserDatabase = FirebaseDatabase.getInstance().getReference("grupos");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(SalasActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("nome").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.setDetails(getApplicationContext(), model.getName(), model.getStatus(), model.getImage());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userName, String userStatus, String userImage){
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_status = (TextView) mView.findViewById(R.id.status_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
user_name.setText(userName);
user_status.setText(userStatus);
Glide.with(ctx).load(userImage).into(user_image);
USERS.JAVA
public class Users {
public String nome, membros, id;
public Users(){
}
public String getName() {
return nome;
}
public void setName(String name) {
this.nome = name;
}
public String getImage() {
return membros;
}
public void setImage(String image) {
this.membros = image;
}
public String getStatus() {
return id;
}
public void setStatus(String status) {
this.id = status;
}
public Users(String name, String image, String status) {
this.nome = name;
this.membros = image;
this.id = status;
}
}
DATABASE
DATABASE IMAGE

Firebase RecyclerView not displaying Anything

I have the same code for another database and it works just fine, I have no Idea why it's not working here,
the onCreateViewHolder does not even get called.
(Appearently Stacks Overflow wants me to add more details to compensate for too much code so here's some unuseful Text , Text, Text , TEXT).
public class Course extends AppCompatActivity {
private RecyclerView mLocationView;
private DatabaseReference mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
mLocation = FirebaseDatabase.getInstance().getReference("FINISHEDCOURSES");
mLocation.keepSynced(true);
mLocationView = (RecyclerView) findViewById(R.id.my_recycler_view);
mLocationView.setHasFixedSize(true);
mLocationView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Courses> options = new FirebaseRecyclerOptions.Builder<Courses>().setQuery(mLocation, Courses.class).build();
FirebaseRecyclerAdapter<Courses, CourseViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Courses, CourseViewHolder>
(options) {
#Override
protected void onBindViewHolder(#NonNull CourseViewHolder holder, int position, #NonNull Courses model) {
holder.setText(model.getDate(), model.getDistance(), model.getDriver(), model.getPrice());
}
#NonNull
#Override
public CourseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.courses_rows, parent, false);
return new CourseViewHolder(view);
}
};
mLocationView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class CourseViewHolder extends RecyclerView.ViewHolder{
View mView;
public CourseViewHolder(View itemView){
super(itemView);
mView = itemView;
}
public void setText(String Date, String start, String end, String price){
TextView dateText = mView.findViewById(R.id.dateText);
TextView startText = mView.findViewById(R.id.depart_text);
TextView endText = mView.findViewById(R.id.end_text);
TextView priceText = mView.findViewById(R.id.price);
dateText.setText(Date);
startText.setText(start);
endText.setText(end);
priceText.setText(price);
}
}
The Courses Class
public class Courses {
private String driver, date, distance, preWaitTime, price, waitTime, client;
public Courses() {
}
public Courses(String driver, String date, String distance, String preWaitTime, String price, String waitTime, String client) {
this.driver = driver;
this.date = date;
this.distance = distance;
this.preWaitTime = preWaitTime;
this.price = price;
this.waitTime = waitTime;
this.client = client;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getPreWaitTime() {
return preWaitTime;
}
public void setPreWaitTime(String preWaitTime) {
this.preWaitTime = preWaitTime;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getWaitTime() {
return waitTime;
}
public void setWaitTime(String waitTime) {
this.waitTime = waitTime;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
}
Here's The Database Structure :
Sorry I should have commented but i do not have enough reputation to do so.
I cannot see anything similar to this in your code.
FirebaseRecyclerAdapter<Courses, CourseViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Courses, CourseViewHolder>(
Courses.class,
R.layout.Courses,// should be your layout name
CourseViewHolder.class,
mLocation
) {
#Override
protected void populateViewHolder(CourseViewHolder viewHolder, category model, final int position) {
viewHolder.setName(model.getName());
viewHolder.setImage(getApplicationContext(),model.getImage());

Android List item displaying package name and # instead of string value

I implemented parceable class to pass some data from one activity to the other. I managed to get the rest of the items in the class. But that class has a list object i want to display in another fragment. i think the problem has to do with my adapter. kindly help me out. i have attached my fragment class and my adapter class as well.
Fragment Class
public class ForumDetailFragment extends Fragment {
private TextView titleTV;
private TextView timeTV;
private TextView dateTV;
private TextView detailsTV;
private ListView answerListView;
private LinearLayout themeLayout;
private ImageView themeIMG;
private StoredForum currentQuestion;
private AnswerAdapter adapter;
SimpleDateFormat formatDate = new SimpleDateFormat("MMM-dd-yyyy");
SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm aaa");
public ForumDetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_forum_detail, container, false);
currentQuestion = getArguments().getParcelable(StoredForum.QUESTION_CLASS);
titleTV = (TextView) rootView.findViewById(R.id.titleTV);
timeTV = (TextView) rootView.findViewById(R.id.timeTV);
detailsTV = (TextView) rootView.findViewById(R.id.detailsTV);
answerListView = (ListView) rootView.findViewById(R.id.answerListView);
themeLayout = (LinearLayout) rootView.findViewById(R.id.eventTypeThemeLayout);
themeIMG = (ImageView) rootView.findViewById(R.id.eventTypeThemeIMG);
dateTV = (TextView) rootView.findViewById(R.id.dateTV);
titleTV.setText(currentQuestion.getTitle());
detailsTV.setText(currentQuestion.getDescription());
timeTV.setText(formatTime.format(currentQuestion.getQuestionDate()));
dateTV.setText(formatDate.format(currentQuestion.getQuestionDate()));
setupTheme();
setUpListView(rootView);
updateAnswer();
return rootView;
}
public void setUpListView(View rootView) {
answerListView = (ListView) rootView.findViewById(R.id.answerListView);
adapter = new AnswerAdapter(getActivity(), new ArrayList<Question>());
answerListView.setAdapter(adapter);
}
private void setupTheme() {
if (currentQuestion.getDescription().equals(StoredForum.FORUM_QUESTION)) {
themeLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.pink));
themeIMG.setImageResource(R.drawable.abc_ic_menu_copy_mtrl_am_alpha);
} else {
themeLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.orange));
themeIMG.setImageResource(R.drawable.abc_ic_menu_paste_mtrl_am_alpha);
}
}
public void updateAnswer() {
AuthUser user = AuthUser.getInstance(getActivity());
Retrofit retrofit = ApiHandle.getRetrofit(user.getToken());
QuestionService service = retrofit.create(QuestionService.class);
service.getQuestions().enqueue(new Callback<List<com.apps233.moja.packages.forum.Question>>() {
#Override
public void onResponse(Response<List<com.apps233.moja.packages.forum.Question>> response, Retrofit retrofit) {
if (response.isSuccess()) {
adapter.clear();
adapter.addAll(response.body());
adapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
Adapter Class
public class AnswerAdapter extends ArrayAdapter<Question> {
List<Question> answers = new ArrayList<Question>();
public AnswerAdapter(Context context, List<Question> answers) {
super(context, R.layout.item_answer, answers);
this.answers = answers;
}
public static class ViewHolder {
private TextView titleTV;
private TextView descriptionTV;
public ViewHolder(View view) {
titleTV = (TextView) view.findViewById(R.id.titleTV);
descriptionTV = (TextView) view.findViewById(R.id.descriptionTV);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Question question = answers.get(position);
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_answer, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleTV.setText("Doctor");
holder.descriptionTV.setText(question.getAnswers().toString());
return convertView;
}
}
The list is displayed in the activity below
the list is displaying the package name # some list of numbers
Question Class
public class Question {
private Long id;
private String title;
private Long userId;
private String description;
private Date questionDate;
private List<Answer> answers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getQuestionDate() {
return questionDate;
}
public void setQuestionDate(Date questionDate) {
this.questionDate = questionDate;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers (List<Answer> answers){
this.answers = answers;
}
}
Parceable Class
public class StoredForum implements Parcelable {
public static final String QUESTION_ID = "QUESTION_ID";
public static final String QUESTION_CLASS = "QUESTION";
public static final String FORUM_QUESTION = "forum-chat";
Long id;
Long userId;
String title;
String description;
Date questionDate;
List<Answer> answers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getQuestionDate() {
return questionDate;
}
public void setQuestionDate(Date questionDate) {
this.questionDate = questionDate;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers){
this.answers = answers;
}
private StoredForum() {
}
public static StoredForum fromQuestion(Question question) {
StoredForum storedForum = new StoredForum();
storedForum.setId(question.getId());
storedForum.setUserId(question.getUserId());
storedForum.setTitle(question.getTitle());
storedForum.setDescription(question.getDescription());
storedForum.setQuestionDate(question.getQuestionDate());
storedForum.setAnswers(question.getAnswers());
return storedForum;
}
protected StoredForum(Parcel in) {
id = in.readByte() == 0x00 ? null : in.readLong();
userId = in.readByte() == 0x00 ? null : in.readLong();
title = in.readString();
description = in.readString();
questionDate = new Date(in.readString());
answers = new ArrayList<Answer>();
answers = in.readArrayList(Answer.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (id == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeLong(id);
}
if (userId == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeLong(userId);
}
dest.writeString(title);
dest.writeString(description);
if(questionDate != null){
dest.writeString(questionDate.toString());
} else {
dest.writeString("0");
}
answers = new ArrayList<Answer>();
dest.writeList(answers);
}
public static final Parcelable.Creator<StoredForum> CREATOR = new Parcelable.Creator<StoredForum>() {
#Override
public StoredForum createFromParcel(Parcel in) {
return new StoredForum(in);
}
#Override
public StoredForum[] newArray(int size) {
return new StoredForum[size];
}
};
}
Answer Class
public class Answer {
Long id;
Long userId;
Long questionId;
String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getQuestionId() {
return questionId;
}
public void setQuestionId(Long questionId) {
this.questionId = questionId;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
}
You need to implement/override public String toString() method in Answer class.
#Override
public String toString() {
return description;
}

Categories

Resources