display json data letest record as per user id - android

i wont to display the list of chats of clients.the data is come from json,
the last message of chat is display on chat.but it displays all message of all clients in list.like
here is my ListMessage.class activity
public class ListMessage extends AppCompatActivity implements View.OnClickListener {
ImageButton btnFooter_Home, btnFooter_Message, btnFooter_Notification, btnFooter_More;
EditText textUser;
List<Msg_data> msgList;
ListView lv;
String uri = "http://staging.talentslist.com/api/user/23/chat";
LinearLayout linear_Home, linear_Message, linear_Notification, linear_More;
GlobalClass myGlog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_message);
myGlog = new GlobalClass(getApplicationContext());
setFooter();
lv = (ListView) findViewById(R.id.listView);
textUser = (EditText) findViewById(R.id.textUser);
// textUser.isFocused()
boolean inConnected = myGlog.isNetworkConnected();
if (inConnected) {
requestData(uri);
}
}
public void requestData(String uri) {
StringRequest request = new StringRequest(uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
lv.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ListMessage.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
}
MsgAdapter.java class
public class MsgAdapter extends BaseAdapter{
private Context context;
private List<Msg_data> nList;
private LayoutInflater inflater = null;
private LruCache<Integer, Bitmap> imageCache;
private RequestQueue queue;
String isread;
public MsgAdapter(Context context, List<Msg_data> list) {
this.context = context;
this.nList = list;
inflater = LayoutInflater.from(context);
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
imageCache = new LruCache<>(cacheSize);
queue = Volley.newRequestQueue(context);
}
public class ViewHolder {
TextView __isread;
TextView _username;
TextView _detais;
TextView _time;
ImageView _image;
}
#Override
public int getCount() {
return nList.size();
}
#Override
public Object getItem(int position) {
return nList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
final Msg_data msg = nList.get(position);
final ViewHolder holder;
isread = msg.getIs_read();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_notification, null);
if (isread.equals("0")) {
convertView.setBackgroundColor(Color.parseColor("#009999"));
}
holder = new ViewHolder();
holder._username = (TextView) convertView.findViewById(R.id.tvtitle);
holder._detais = (TextView) convertView.findViewById(R.id.tvdesc);
holder.__isread = (TextView) convertView.findViewById(R.id.tvplateform);
holder._time = (TextView) convertView.findViewById(R.id.createdTime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._username.setText(msg.getUser_name().toString());
holder._detais.setText(msg.getMessage().toString());
holder._time.setText(msg.getCreated_at().toString());
// holder.__isread.setText(notifi.getIs_read().toString());
holder._image = (ImageView) convertView.findViewById(R.id.gameImage);
Glide.with(context)
.load(msg.getImage_link().toString()) // Set image url
.diskCacheStrategy(DiskCacheStrategy.ALL) // Cache for image
.into(holder._image);
return convertView;
}
}
Msg_data.java class
public class Msg_data {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
}
MsgJSONParser.java class
public class MsgJSONParser {
static List<Msg_data> notiList;
public static List<Msg_data> parseData(String content) {
JSONArray noti_arry = null;
Msg_data noti = null;
try {
JSONObject jsonObject = new JSONObject(content);
noti_arry = jsonObject.getJSONArray("data");
notiList = new ArrayList<>();
for (int i = 0; i < noti_arry.length(); i++) {
JSONObject obj = noti_arry.getJSONObject(i);
//JSONObject obj = noti_arry.getJSONObject(i);
noti = new Msg_data();
noti.setId(obj.getInt("id"));
noti.setMessage(obj.getString("message"));
noti.setUser_name(obj.getString("user_name"));
noti.setFrom(obj.getString("from"));
noti.setTo(obj.getString("to"));
noti.setCreated_at(obj.getString("created_at"));
noti.setImage_link(obj.getString("image_link"));
noti.setIs_read(obj.getString("is_read"));
notiList.add(noti);
}
return notiList;
} catch (JSONException ex) {
ex.printStackTrace();
return null;
}
}
}
please give me some idea what to do and how to do

i guess, you should replace
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
with
msgList = MsgJSONParser.parseData(response);
ArrayList<Msg_data> userList=new ArrayList();
for (int i=0;i<msgList.size();i++){
if (!userList.contains(msgList.get(i)))
userList.add(msgList.get(i));
else {
int index=userList.indexOf(msgList.get(i));
if (userList.get(index).compareTo(msgList.get(i))>0)
userList.add(msgList.get(i));
}
}
MsgAdapter adapter = new MsgAdapter(ListMessage.this, userList);`
and implement Comparable and override equals method in your Msg_data class
public class Msg_data implements Comparable {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
try
{
return (this.getUser_id().equals(( (Msg_data)obj).getUser_id()));
}
catch(NullPointerException e){
return false;
}
}
#Override
public int compareTo(#NonNull Object o) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("your pattern here");
try {
Date date=simpleDateFormat.parse(created_at);
Date dateOtherObject=simpleDateFormat.parse(((Msg_data)o).getCreated_at());
return date.compareTo(dateOtherObject);
}
catch (ParseException e){
return -1;
}
}
something like this:) Dont forget replace simple date format in compare method

Related

Classmaper No setter found for the key generated by push

I want to display the messages of group chat in my recyclerview but i have this warning in logcat
I searched a lot for this error, I could not find the right solution ...
Model class
public class Groups {
private String groupName;
private String Admin;
private String push_id;
public MessageG messageG;
public Groups() {
}
public Groups(String groupName, String Admin, String push_id, MessageG messageG) {
this.groupName = groupName;
this.Admin = Admin;
this.push_id = push_id;
this.messageG = messageG;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getAdmin() {
return Admin;
}
public void setAdmin(String admin) {
Admin = admin;
}
public String getPush_id() {
return push_id;
}
public void setPush_id(String push_id) {
this.push_id = push_id;
}
public MessageG getMessageG() {
return messageG;
}
public void setMessageG(MessageG messageG) {
this.messageG = messageG;
}
}
For the child:
public class MessageG
{
public String id;
public String name;
public String userid;
public String msg;
public String date;
public long time;
public MessageG() {}
public MessageG(String id, String name, String userid, String msg, String date, long time) {
this.id = id;
this.name = name;
this.userid = userid;
this.msg = msg;
this.date = date;
this.time = time;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
Listener of the button (send message):
btn_send_message.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
String message = text_send.getText().toString();
if(message.equals(""))
{
Toast.makeText(GroupChatActivity.this, "Empty !", Toast.LENGTH_SHORT).show();
}
else
{
//SendMessageInfoToDatabase();
GroupNameRef = FirebaseDatabase.getInstance().getReference("Groups").child("Messages");
String id = GroupNameRef.push().getKey();
//---GET DATE
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDateFormat = new SimpleDateFormat("MMM dd, yyyy");
currentDate = currentDateFormat.format(calForDate.getTime());
//---------------------
//--- the time
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTimeFormat = new SimpleDateFormat("hh:mm");
currentTime = currentTimeFormat.format(calForTime.getTime());
//---------------------
assert id != null;
GroupMessageKeyRef = GroupNameRef.child(id);
Map<String, Object> messageInfoMap = new HashMap<>();
messageInfoMap.put("id", id);
messageInfoMap.put("name", CurrentUserName);
messageInfoMap.put("userid", fuser.getUid());
messageInfoMap.put("msg", message);
messageInfoMap.put("date", currentDate);
messageInfoMap.put("time", currentTime);
GroupMessageKeyRef.setValue(messageInfoMap);
text_send.setText("");
}
}
});
My adapter:
public class GroupMessageAdapter extends RecyclerView.Adapter<GroupMessageAdapter.GroupMessageViewHolder>
{
public static final int MSG_RECEIVERS = 1;
public static final int MSG_SENDER = 0;
private List<Groups> mMessageList;
private Context mContext;
public GroupMessageAdapter(List<Groups> mMessageList, Context mContext) {
this.mMessageList = mMessageList;
this.mContext = mContext;
}
#NonNull
#Override
public GroupMessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
if(viewType == MSG_SENDER)
{
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_sender, parent, false);
GroupMessageViewHolder gmvh = new GroupMessageViewHolder(view);
return gmvh;
}
else
{
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_receivers, parent, false);
GroupMessageViewHolder gm = new GroupMessageViewHolder(view);
return gm;
}
}
public class GroupMessageViewHolder extends RecyclerView.ViewHolder
{
private TextView messages_textView;
public GroupMessageViewHolder(#NonNull View itemView)
{
super(itemView);
messages_textView = itemView.findViewById(R.id.group_chat_text_display);
}
}
#Override
public void onBindViewHolder(#NonNull final GroupMessageViewHolder groupMessageViewHolder, int position)
{
Groups groups = mMessageList.get(position);
groupMessageViewHolder.messages_textView.setText(groups.getMessageG().getMsg());
}
#Override
public int getItemCount()
{
return mMessageList.size();
}
#Override
public int getItemViewType(int position)
{
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert firebaseUser != null;
if(mMessageList.get(position).getMessageG().getUserid().equals(firebaseUser.getUid()))
{
return MSG_SENDER;
}
else
{
return MSG_RECEIVERS;
}
}
}
The error is :
W/ClassMapper: No setter/field for (KEY generated by push) found on
class
My database:
enter image description here

getitemcount() return null in recyclerview with movie api

getitemcount() return null in RecyclerView adapter. When I run my app, it crashes and the error message is movies item size in getitemcount() returns null.
Here's the relevant code:
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder>
{
private Context context;
private List<Movie> movieList;
public MoviesAdapter(Context context, List<Movie> movieList) {
this.context = context;
this.movieList = movieList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_card,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.title.setText(movieList.get(position).getOriginal_title());
String vote = Double.toString(movieList.get(position).getVoteAverage());
holder.userrating.setText(vote);
Glide.with(context).load(movieList.get(position).getPosterpath()).placeholder(R.drawable.loading).into(holder.imageView);
}
#Override
public int getItemCount() {
return movieList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
private TextView title,userrating;
private ImageView imageView;
public MyViewHolder(final View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.movietitle);
userrating = (TextView) itemView.findViewById(R.id.userrating);
imageView = (ImageView) itemView.findViewById(R.id.thumbnail);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION)
{
Movie clickedDataItem = movieList.get(pos);
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("original_title" , movieList.get(pos).getOriginal_title());
intent.putExtra("poster",movieList.get(pos).getPosterpath());
intent.putExtra("overview",movieList.get(pos).getOverview());
intent.putExtra("vot_average",movieList.get(pos).getVote_count());
intent.putExtra("release_date",movieList.get(pos).getRelease_data());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Toast.makeText(view.getContext(),"you clicked "+clickedDataItem.getOriginal_title(),Toast.LENGTH_LONG).show();
}
}
});
}
}
}
public interface Service {
#GET("/3/movie/popular")
Call<MoviesResponse> getPopularMovies (#Query("api_key") String apikey);
}
public class MoviesResponse {
private int page;
private List <Movie> result;
private int totalresult;
private int totalpage;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public List<Movie> getResult() {
return result;
}
public void setResult(List<Movie> result) {
this.result = result;
}
public int getTotalresult() {
return totalresult;
}
public void setTotalresult(int totalresult) {
this.totalresult = totalresult;
}
public int getTotalpage() {
return totalpage;
}
public void setTotalpage(int totalpage) {
this.totalpage = totalpage;
}
}
public class Movie {
private String posterpath;
private boolean adult;
private String overview;
private String release_data;
private List<Integer> genre_ids = new ArrayList<Integer>();
private int id;
private String original_title;
private String original_language;
private String title;
private String backdroppath;
private Double popularity;
private int vote_count;
private boolean video;
private Double voteAverage;
public Movie(String posterpath, boolean adult, String overview, String release_data, List<Integer> genre_ids, int id, String original_title, String original_language, String title, String backdroppath, Double popularity, int vote_count, boolean video, Double voteAverage) {
this.posterpath = posterpath;
this.adult = adult;
this.overview = overview;
this.release_data = release_data;
this.genre_ids = genre_ids;
this.id = id;
this.original_title = original_title;
this.original_language = original_language;
this.title = title;
this.backdroppath = backdroppath;
this.popularity = popularity;
this.vote_count = vote_count;
this.video = video;
this.voteAverage = voteAverage;
}
String baseImageUrl = "https://image.tmdb.org/t/p/w500";
public String getPosterpath() {
return "https://image.tmdb.org/t/p/w500" + posterpath;
}
public void setPosterpath(String posterpath) {
this.posterpath = posterpath;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getRelease_data() {
return release_data;
}
public void setRelease_data(String release_data) {
this.release_data = release_data;
}
public List<Integer> getGenre_ids() {
return genre_ids;
}
public void setGenre_ids(List<Integer> genre_ids) {
this.genre_ids = genre_ids;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOriginal_title() {
return original_title;
}
public void setOriginal_title(String original_title) {
this.original_title = original_title;
}
public String getOriginal_language() {
return original_language;
}
public void setOriginal_language(String original_language) {
this.original_language = original_language;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBackdroppath() {
return backdroppath;
}
public void setBackdroppath(String backdroppath) {
this.backdroppath = backdroppath;
}
public Double getPopularity() {
return popularity;
}
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
public int getVote_count() {
return vote_count;
}
public void setVote_count(int vote_count) {
this.vote_count = vote_count;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public Double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(Double voteAverage) {
this.voteAverage = voteAverage;
}
public String getBaseImageUrl() {
return baseImageUrl;
}
public void setBaseImageUrl(String baseImageUrl) {
this.baseImageUrl = baseImageUrl;
}
}
public class Client {
public static final String BASE_URL = "https://api.themoviedb.org";
public static final String API_KEY = "5c723cbb6a71ce839dc704a80febe3fb";
public static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MoviesAdapter adapter;
private List<Movie> movieList;
ProgressDialog pd;
private TextView textView;
private SwipeRefreshLayout swipecontainer;
public static final String LOG_TAG = MoviesAdapter.class.getName();
#SuppressLint("ResourceAsColor")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initview();
swipecontainer = (SwipeRefreshLayout) findViewById(R.id.main_content);
swipecontainer.setColorSchemeColors(android.R.color.holo_orange_dark);
swipecontainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
initview();
Toast.makeText(MainActivity.this,"Movies Refreshed",Toast.LENGTH_LONG).show();
}
});
}
public Activity getActivity ()
{
Context context =this;
while (context instanceof ContextWrapper)
{
return (Activity) context;
}
context =((ContextWrapper) context).getBaseContext();
return null;
}
private void initview() {
pd = new ProgressDialog(this);
pd.setMessage("Fetching Movies");
pd.setCancelable(false);
pd.show();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
movieList = new ArrayList<>();
adapter = new MoviesAdapter(this,movieList);
if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
recyclerView.setLayoutManager(new GridLayoutManager(this,2));
}
else
{
recyclerView.setLayoutManager(new GridLayoutManager(this,4) );
}
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
loadjson();
}
private void loadjson() {
try {
if(BuildConfig.THE_MOVIE_DB_API_TOKEN.isEmpty())
{
Toast.makeText(getApplicationContext(),"please obtain API key",Toast.LENGTH_LONG).show();
return;
}
Client client= new Client();
Service apiservice = Client.getClient().create(Service.class);
Call<MoviesResponse> call = apiservice.getPopularMovies("5c723cbb6a71ce839dc704a80febe3fb");
call.enqueue(new Callback<MoviesResponse>() {
#Override
public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
List<Movie> movies = response.body().getResult();
recyclerView.setAdapter(new MoviesAdapter(getApplicationContext(),response.body().getResult()));
recyclerView.smoothScrollToPosition(0);
if (swipecontainer.isRefreshing()) {
swipecontainer.setRefreshing(false);
}
pd.dismiss();
}
#Override
public void onFailure(retrofit2.Call<MoviesResponse> call, Throwable t) {
Log.d("Error" ,t.getMessage());
Toast.makeText(MainActivity.this,"Error Fetching Data! " ,Toast.LENGTH_LONG).show();
}
});
}
catch (Exception e)
{
Log.d("Error" ,e.getMessage());
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.menu_setting :
return true;
default:return super.onOptionsItemSelected(item);
}
}
}

RecyclerView to Firebase database

I actually want cardView in my RecyclerView to retrieve data from firebase but it returns error. Please do help me to attach my RecyclerView to firebase and retrieve data from it.
Thanking you in advance.
Here is the mainActivity.java
mbloglist = findViewById(R.id.rv1);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
productAdapter adapter = new productAdapter(this);
mbloglist.setLayoutManager(layoutManager);
mbloglist.setAdapter(adapter);
Toast.makeText(getApplicationContext(),"Layout starting",Toast.LENGTH_SHORT).show();
database1 = FirebaseDatabase.getInstance();
myRef = database1.getReference("Users");
Toast.makeText(getApplicationContext(),"Database Done",Toast.LENGTH_SHORT).show();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e("pppp","onDataChange"+dataSnapshot.toString());
Toast.makeText(getApplicationContext(),"Done",Toast.LENGTH_SHORT).show();
for(DataSnapshot child : dataSnapshot.getChildren()){
ModelClass modelClass = child.getValue(ModelClass.class);
modelClassList.add(modelClass);
}
Toast.makeText(getApplicationContext(),"Done Done",Toast.LENGTH_SHORT).show();
adapter.addItems(modelClassList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("pppp","onCancelled");
}
});
}
Here is the Adapter which named ProductAdapter.java
public productAdapter(Context context) {
this.context = context;
this.productList = new ArrayList<>();
}
public void addItems(List<ModelClass> productList){
this.productList = productList;
this.notifyDataSetChanged();
}
#NonNull
#Override
public productViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new productViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false));
}
#Override
public void onBindViewHolder(#NonNull productViewHolder holder, int position) {
ModelClass modelClass = productList.get(position);
holder.shop_name.setText(modelClass.getStore_name());
holder.phone_number.setText(modelClass.getphone_number());
holder.v7b.setText(modelClass.getV7b());
holder.v7g.setText(modelClass.getV7g());
holder.y53b.setText(modelClass.getY53b());
holder.y53g.setText(modelClass.getY53g());
holder.v7pb.setText(modelClass.getV7pb());
holder.v7pg.setText(modelClass.getV7pg());
holder.y55sb.setText(modelClass.getY55sb());
holder.y55sg.setText(modelClass.getY55sb());
holder.i3b.setText(modelClass.getI3b());
holder.i3go.setText(modelClass.getI3go());
holder.i3gr.setText(modelClass.getI3gr());
holder.i3prob.setText(modelClass.getI3prob());
holder.i3progo.setText(modelClass.getI3progo());
holder.i3progr.setText(modelClass.getI3progr());
holder.i5b.setText(modelClass.getI5b());
holder.i5go.setText(modelClass.getI5go());
holder.i5gr.setText(modelClass.getI5gr());
holder.i5prob.setText(modelClass.getI5prob());
holder.i5progo.setText(modelClass.getI5progo());
holder.i5progr.setText(modelClass.getI5progr());
holder.i7b.setText(modelClass.getI7b());
holder.i7go.setText(modelClass.getI7go());
holder.i7gr.setText(modelClass.getI7gr());
holder.camonb.setText(modelClass.getCamonb());
holder.camongo.setText(modelClass.getCamongo());
holder.camonbl.setText(modelClass.getCamonbl());
}
#Override
public int getItemCount() {
return 0;
}
class productViewHolder extends RecyclerView.ViewHolder{
private TextView shop_name,phone_number,v7b,v7g,y53b,y53g,v7pb,v7pg,y55sb,y55sg,y69b,y69g,i3b,i3go,i3gr,i3prob,i3progo,i3progr,i5b,i5go,i5gr,i5prob,i5progo,i5progr,i7b,i7go,i7gr,camonb,camongo,camonbl;
public productViewHolder(View itemView){
super(itemView);
shop_name = itemView.findViewById(R.id.EditText2000);
phone_number=itemView.findViewById(R.id.EditText2001);
v7b=itemView.findViewById(R.id.EditText101);
v7g=itemView.findViewById(R.id.EditText102);
y53b=itemView.findViewById(R.id.EditText103);
y53g=itemView.findViewById(R.id.EditText104);
v7pb=itemView.findViewById(R.id.EditText105);
v7pg=itemView.findViewById(R.id.EditText106);
y55sb=itemView.findViewById(R.id.EditText107);
y55sg=itemView.findViewById(R.id.EditText108);
y69b=itemView.findViewById(R.id.EditText109);
y69g=itemView.findViewById(R.id.EditText110);
i3b=itemView.findViewById(R.id.EditText111);
i3go=itemView.findViewById(R.id.EditText112);
i3gr=itemView.findViewById(R.id.EditText113);
i3prob=itemView.findViewById(R.id.EditText114);
i3progo=itemView.findViewById(R.id.EditText115);
i3progr=itemView.findViewById(R.id.EditText116);
i5b=itemView.findViewById(R.id.EditText117);
i5go=itemView.findViewById(R.id.EditText118);
i5gr=itemView.findViewById(R.id.EditText119);
i5prob=itemView.findViewById(R.id.EditText120);
i5progo=itemView.findViewById(R.id.EditText121);
i5progr=itemView.findViewById(R.id.EditText122);
i7b=itemView.findViewById(R.id.EditText123);
i7go=itemView.findViewById(R.id.EditText124);
i7gr=itemView.findViewById(R.id.EditText125);
camonb=itemView.findViewById(R.id.EditText126);
camongo=itemView.findViewById(R.id.EditText127);
camonbl=itemView.findViewById(R.id.EditText128);
Here is the modelclass.java which attached to firebase
public class ModelClass {
String v7b;
String v7g;
String y53b;
String y53g;
String v7pb;
String v7pg;
String y55sb;
String y55sg;
String y69b;
String y69g;
String i3b;
String i3go;
String i3gr;
String i3prob;
String i3progo;
String i3progr;
String i5b;
String i5go;
String i5gr;
String i5prob;
String i5progo;
String i5progr;
String i7b;
String i7go;
String i7gr;
String camonb;
String camongo;
String camonbl;
String email;
String store_name;
String phone_number;
public ModelClass() {
}
public ModelClass(String v7b, String v7g, String y53b, String y53g, String v7pb, String v7pg, String y55sb, String y55sg, String y69b, String y69g, String i3b, String i3go, String i3gr, String i3prob, String i3progo, String i3progr, String i5b, String i5go, String i5gr, String i5prob, String i5progo, String i5progr, String i7b, String i7go, String i7gr, String camonb, String camongo, String camongr) {
this.v7b = v7b;
this.v7g = v7g;
this.y53b = y53b;
this.y53g = y53g;
this.v7pb = v7pb;
this.v7pg = v7pg;
this.y55sb = y55sb;
this.y55sg = y55sg;
this.y69b = y69b;
this.y69g = y69g;
this.i3b = i3b;
this.i3go = i3go;
this.i3gr = i3gr;
this.i3prob = i3prob;
this.i3progo = i3progo;
this.i3progr = i3progr;
this.i5b = i5b;
this.i5go = i5go;
this.i5gr = i5gr;
this.i5prob = i5prob;
this.i5progo = i5progo;
this.i5progr = i5progr;
this.i7b = i7b;
this.i7go = i7go;
this.i7gr = i7gr;
this.camonb = camonb;
this.camongo = camongo;
this.camonbl = camongr;
}
public ModelClass(String email, String store_name, String phone_number) {
this.email = email;
this.store_name = store_name;
this.phone_number = phone_number;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
String phone;
public String getV7b() {
return v7b;
}
public void setV7b(String v7b) {
this.v7b = v7b;
}
public String getV7g() {
return v7g;
}
public void setV7g(String v7g) {
this.v7g = v7g;
}
public String getY53b() {
return y53b;
}
public void setY53b(String y53b) {this.y53b = y53b;}
public String getY53g() {
return y53g;
}
public void setY53g(String y53g) {
this.y53g = y53g;
}
public String getV7pb() {
return v7pb;
}
public void setV7pb(String v7pb) {
this.v7pb = v7pb;
}
public String getV7pg() {
return v7pg;
}
public void setV7pg(String v7pg) {
this.v7pg = v7pg;
}
public String getY55sb() {
return y55sb;
}
public void setY55sb(String y55sb) {
this.y55sb = y55sb;
}
public String getY55sg() {
return y55sg;
}
public void setY55sg(String y55sg) {
this.y55sg = y55sg;
}
public String getY69b() {
return y69b;
}
public void setY69b(String y69b) {
this.y69b = y69b;
}
public String getY69g() {
return y69g;
}
public void setY69g(String y69g) {
this.y69g = y69g;
}
public String getI3b() {
return i3b;
}
public void setI3b(String i3b) {
this.i3b = i3b;
}
public String getI3go() {
return i3go;
}
public void setI3go(String i3go) {
this.i3go = i3go;
}
public String getI3gr() {
return i3gr;
}
public void setI3gr(String i3gr) {
this.i3gr = i3gr;
}
public String getI3prob() {
return i3prob;
}
public void setI3prob(String i3prob) {
this.i3prob = i3prob;
}
public String getI3progo() {
return i3progo;
}
public void setI3progo(String i3progo) {
this.i3progo = i3progo;
}
public String getI3progr() {
return i3progr;
}
public void setI3progr(String i3progr) {
this.i3progr = i3progr;
}
public String getI5b() {
return i5b;
}
public void setI5b(String i5b) {
this.i5b = i5b;
}
public String getI5go() {
return i5go;
}
public void setI5go(String i5go) {
this.i5go = i5go;
}
public String getI5gr() {
return i5gr;
}
public void setI5gr(String i5gr) {
this.i5gr = i5gr;
}
public String getI5prob() {
return i5prob;
}
public void setI5prob(String i5prob) {
this.i5prob = i5prob;
}
public String getI5progo() {
return i5progo;
}
public void setI5progo(String i5progo) {
this.i5progo = i5progo;
}
public String getI5progr() {
return i5progr;
}
public void setI5progr(String i5progr) {
this.i5progr = i5progr;
}
public String getI7b() {
return i7b;
}
public void setI7b(String i7b) {
this.i7b = i7b;
}
public String getI7go() {
return i7go;
}
public void setI7go(String i7go) {
this.i7go = i7go;
}
public String getI7gr() {
return i7gr;
}
public void setI7gr(String i7gr) {
this.i7gr = i7gr;
}
public String getCamonb() {
return camonb;
}
public void setCamonb(String camonb) {
this.camonb = camonb;
}
public String getCamongo() {
return camongo;
}
public void setCamongo(String camongo) {
this.camongo = camongo;
}
public String getCamonbl() {
return camonbl;
}
public void setCamongr(String camongr) {
this.camonbl = camongr;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStore_name() {
return store_name;
}
public void setStorename(String storename) {this.store_name = storename;}
public String getphone_number() {
return phone_number;
}
public void setphone_number(String phone_number) {
this.phone_number = phone_number;
}
}
Here is the Firebase Realtime Database Image
ModelClass class and your database doesn't have the same structure, because in your database you have a new node called "phone" inside each userID node.
You can try 3 approaches to solve this issue:
a.) Write data in your database just like ModelClass is, without "phone" node.
b.) Create a new class called "Phone" with same attributes you have inside "phone" node in the database, and make this new class part of ModelClass class.
c.) On myRef onDataChange method, inside for statement, check for each child key and fill ModelClass atributes one by one. When the child key is equal to "phone", start a new loop statement in "phone" children to fill these attributes.
Add the following code:
#Override
public int getItemCount() {
return productList.size();
}

ListVew Repeating same row from MySql database in Android

I had an ListVew where I have to show the orders List from Database.I have Multiple orders in Mysql Database but only one order is continuously repeating in ListVew.Any help regarding this is Appreciated.
Here is my Adapter Class
public class OrderApprovalAdapter extends ArrayAdapter
{
List list1 = new ArrayList();
Context context;
public OrderApprovalAdapter(#NonNull Context context, #NonNull int Resource)
{
super(context, Resource);
this.context = context;
}
#Override
public void add(#Nullable Object object)
{
super.add(object);
list1.add(object);
}
#Override
public int getCount()
{
return list1.size();
}
#Override
public Object getItem(int position)
{
return list1.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final OrderApprovalAdapter.ContactHolder contactHolder;
View row;
row = convertView;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.order_approval_format, parent, false);
contactHolder = new ContactHolder();
contactHolder.date = (TextView) row.findViewById(R.id.invoice_date);
contactHolder.orderid = (TextView) row.findViewById(R.id.invoice_no);
contactHolder.shopname = (TextView) row.findViewById(R.id.shop_name);
contactHolder.ownername = (TextView) row.findViewById(R.id.owner_name);
contactHolder.mobile=(TextView) row.findViewById(R.id.mobile_noo);
contactHolder.location=(TextView)row.findViewById(R.id.location);
contactHolder.itemscount=(TextView)row.findViewById(R.id.items);
contactHolder.amount=(TextView)row.findViewById(R.id.total);
contactHolder.Approval=(Button)row.findViewById(R.id.Approve_btn);
contactHolder.Decline=(Button)row.findViewById(R.id.decline_btn);
row.setTag(contactHolder);
} else
{
contactHolder = (ContactHolder) row.getTag();
}
final OrderApprovalDetails contacts = (OrderApprovalDetails) this.getItem(position);
contactHolder.date.setText(contacts.getDate());
contactHolder.orderid.setText(contacts.getOrderid());
contactHolder.shopname.setText(contacts.getShopname());
contactHolder.ownername.setText(contacts.getOwnername());
contactHolder.mobile.setText(contacts.getMobile());
contactHolder.location.setText(contacts.getLocation());
contactHolder.itemscount.setText(contacts.getItemscount());
contactHolder.amount.setText(contacts.getAmount());
contactHolder.Approval.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Approved", Toast.LENGTH_SHORT).show();
}
});
contactHolder.Decline.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Decline", Toast.LENGTH_SHORT).show();
}
});
return row;
}
static class ContactHolder
{
TextView date,orderid,shopname,ownername,mobile,location,itemscount,amount;
Button Approval,Decline;
}
}
Retriving Data From Database
class OrdersListBackgroundTask extends AsyncTask<Void,Void,String>
{
#Override
protected void onPreExecute()
{
OrdersList_url="http://10.0.2.2/accounts/OrderForm2.php";
}
#Override
protected String doInBackground(Void... params)
{
try {
URL url=new URL(OrdersList_url);
HttpURLConnection httpURLConnection=
(HttpURLConnection)url.openConnection();
InputStream is= httpURLConnection.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
StringBuilder sb=new StringBuilder();
while ((JSON_STRING4=br.readLine())!=null)
{
sb.append(JSON_STRING4+ "");
}
br.close();
is.close();
httpURLConnection.disconnect();
return sb.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
//TextView tv=(TextView)findViewById(R.id.tv);
//tv.setText(result);
json_string4=result;
}
}
Sending Through intent to Next Page
public void Orders_List(View v)//Button click
{
if (json_string4==null)
{
Toast.makeText(this, "Get Orders First", Toast.LENGTH_SHORT).show();
}else
{
Intent i1=new Intent(this,OrdersList.class);
i1.putExtra("json_data4",json_string4);
startActivity(i1);
}
}
Usage in MainActivity
json_string4=getIntent().getExtras().getString("json_data4");
listView_Orders=(ListView)findViewById(R.id.listViewOrderlist);
listView_Orders.setItemsCanFocus(true);
search_filter=(EditText)findViewById(R.id.search_et);
orderApprovalAdapter=new
OrderApprovalAdapter(this,R.layout.order_approval_format);
listView_Orders.setAdapter(orderApprovalAdapter);
//listView_Orders.setTextFilterEnabled(true);
try
{
jsonObject=new JSONObject(json_string4);
jsonArray=jsonObject.getJSONArray("orders");
int count=0;
for (int i=0;i<jsonArray.length();i++)
{
JSONObject jo=jsonArray.getJSONObject(i);
date=jo.getString("date");
orderid=jo.getString("orderid");
shopname=jo.getString("shopname");
ownername=jo.getString("ownername");
mobile=jo.getString("mobile");
location=jo.getString("location");
items=jo.getString("items_count");
amount=jo.getString("amount");
OrderApprovalDetails orderApprovalDetails=new OrderApprovalDetails(date,orderid,shopname,ownername,mobile,location,items,amount,Approve,Decline);
orderApprovalAdapter.add(orderApprovalDetails);
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
OrderApprovalDetails Class
public class OrderApprovalDetails
{
public static String
date,orderid,shopname,ownername,mobile,location,itemscount,amount;
public static Button Approval,Decline;
public OrderApprovalDetails(String date,String orderid,String shopname,String ownername,String mobile,String location,String itemscount,String amount,Button Approval,Button Decline)
{
this.setDate(date);
this.setOrderid(orderid);
this.setShopname(shopname);
this.setOwnername(ownername);
this.setMobile(mobile);
this.setLocation(location);
this.setItemscount(itemscount);
this.setAmount(amount);
this.setApproval(Approval);
this.setDecline(Decline);
}
public String getDate()
{
return date;
}
public static Button getApproval() {
return Approval;
}
public static void setApproval(Button approval) {
Approval = approval;
}
public static Button getDecline() {
return Decline;
}
public static void setDecline(Button decline) {
Decline = decline;
}
public void setDate(String date) {
this.date = date;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
public String getShopname() {
return shopname;
}
public void setShopname(String shopname) {
this.shopname = shopname;
}
public String getOwnername() {
return ownername;
}
public void setOwnername(String ownername) {
this.ownername = ownername;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getItemscount() {
return itemscount;
}
public void setItemscount(String itemscount) {
this.itemscount = itemscount;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Don't know where I did Mistake,Please Help me to findout that,Thanks in Advance.
You class members should never be declared static as you have done here -
public class OrderApprovalDetails
{
public static String date,orderid,shopname,ownername,mobile,location,itemscount,amount;
change this to
public class OrderApprovalDetails
{
public String date,orderid,shopname,ownername,mobile,location,itemscount,amount;

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