everyone.
Hello. I’ve created android application. I am retrieving data from real-time database and also using recycle view + view holder. But when I go to another activity and then go back - my list oh view holder items was reset. How I can save state view holder and restore them?
I looked at various topics on the site, but not one answer did not help me.
My Pojo Class
public class Post {
private String post_id;
private String post_title;
private long post_date;
private long post_desc;
public Post(String post_id, String post_title, long post_date, String post_desc) {
this.post_id = post_id;
this.post_title = post_title;
this.comments_count = comments_count;
this.post_date = post_date;
this.post_desc = post_desc;
}
public void setPost_id(String post_id) {
this.post_id = post_id;
}
public String getPost_title() {
return post_title;
}
public void setPost_title(String post_title) {
this.post_title = post_title;
}
public String getPost_date() {
String month = new java.text.SimpleDateFormat("MM").
format(new java.util.Date(post_date * 1000));
int monthnumber = Integer.parseInt(month);
String value = new java.text.SimpleDateFormat("dd ").
format(new java.util.Date(post_date * 1000));
value +=MonthName[monthnumber-1];
value+= new java.text.SimpleDateFormat(" HH:mm").
format(new java.util.Date(post_date * 1000));
return value;
}
public void setPost_date(long post_date) {
this.post_date = post_date;
}
public String getPost_desc() {
return post_desc;
}
public void setPost_desc(String post_desc) {
this.post_desc = post_desc;
}}
ViewHolderClass
public static class PostViewHolder extends RecyclerView.ViewHolder {
public PostViewHolder(View itemView) {
super(itemView); }
public void setTitle(String title) {
titleViewPost.setText(title);
}
public void setDate(String date) {
dateViewPost.setText(date);
}
public void setDesc(String desc) {
descViewPost.setText(desc);
}}}
FirebaseRecyleAdapter
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder >(
Post.class,
R.layout.post_row,
PostViewHolder.class,
mDatabase
) {#Override
protected void populateViewHolder(final PostViewHolder viewHolder,
Post model, final int position) {
viewHolder.mCommentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent commentActivity = new Intent(MainActivity.this, CommentActivity.class);
commentActivity.putExtra("post_id", post_key);
if(mUserId != null) {
commentActivity.putExtra("user_id", mUserId);
}
startActivity(commentActivity);
}
});
As I understand, the whole problem is that my adapter is reused and I can not return to that position in the tape - where I was before.
Its my app.https://play.google.com/store/apps/details?id=dev.arounda.chesnock
I want fix thiw trouble for this application
Try to call firebaseRecyclerAdapter.startListening(); in onCreate() instead of onStart and firebaseRecyclerAdapter.stopListening(); in onDestroy() instead of onStop()
Related
So below are the database of my cloud firestore. That DatePosted shows 2nd December, 2019 at 8.19 pm UTC +8. According to the code I used and I run my app, it shows an unreadable number. Is it correct on how I retrieve the data from cloud firebase? If its wrong, how do I retrieve that timestamp and make it readable?
ForumAdapter.java
public class ForumAdapter extends FirestoreRecyclerAdapter<Forum,ForumAdapter.ForumHolder> {
private OnItemClickListener listener;
public ForumAdapter(FirestoreRecyclerOptions<Forum> options) {
super(options);
}
#Override
public void onBindViewHolder(ForumHolder forumHolder, int i, Forum forum) {
forumHolder.textViewTitle.setText(forum.getTitle());
forumHolder.textViewDescription.setText(forum.getDescription());
forumHolder.timeStamp.setText(forum.getDatePosted().toString());
}
#NonNull
#Override
public ForumHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
android.view.View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforumtitle,parent,false);
return new ForumHolder(v);
}
class ForumHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDescription;
TextView timeStamp;
public ForumHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.tvTitle);
textViewDescription = itemView.findViewById(R.id.tvDescription);
timeStamp = itemView.findViewById(R.id.tvTimestamp);
textViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
// NO_POSITION to prevent app crash when click -1 index
if(position != RecyclerView.NO_POSITION && listener !=null ){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return super.getItemCount();
}
}
Forum.java
public class Forum {
private String Title;
private String Description;
private String User;
private com.google.firebase.Timestamp DatePosted;
public Forum() {
}
public Forum(String title, String description, Timestamp datePosted,String user) {
Title = title;
Description = description;
DatePosted = datePosted;
User = user;
}
public String getUser() {
return User;
}
public void setUser(String user) {
User = user;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public Timestamp getDatePosted() {
return DatePosted;
}
public void setDatePosted(Timestamp datePosted) {
DatePosted = datePosted;
}
}
When you query a document with a timestamp field, you will get a Timestamp object back. If you'd rather have a Date object, you can use its toDate method.
You will need to write some code to format this for display. This is a very common task for mobile and web apps.
I'm trying to learn how to load my recycler view from mySQL. Followed a few tutorials but the recycler view shows up but doesn't fill with anything. So I'm not sure what I did wrong.
What I'm trying to do is I have one app that allows me to take pictures and send some input to my xammp server. Then this app will let you use a recycler view to view the picture and some textfields, eventually being able to click them to get more info. Eventually I want to turn this into an app of some kind I give to local animal shelter or something. They take a picture of their dogs on one app, and then people can download the other app and see the dogs available.
Now I know the image stuff is messed up so I noted it out. My "url" is my path on my server not a http url, I haven't figured out how to get that to work yet I know it won't work with picasso(I thought it would, I'm kinda new to this), still learning that's why that picasso stuff is there.
TL;DR
But I can't get the recyclerview to show any data on the page aka firsname, lastname.
Here is my index.php
$app->get('/getprofilepic', function(request $request, Response $response){
$db = new profilepic;
$profiledata = $db->getprofilepic();
$response->getBody()>write(json_encode(array("profiledata"=>$profiledata)));
});
here is my php profilepic
private $con;
function __construct(){
require_once dirname(__FILE__) . '/DbConnect.php';
$db = new DbConnect;
$this->con = $db->connect();
}
public function getprofilepic(){
$stmt = $this->con->prepare("SELECT doginfohometab1db.ID, doginfohometab1db.firstnametxt, doginfohometab1db.lastnametxt, profilepicdb.picurl FROM doginfohometab1db LEFT JOIN profilepicdb ON doginfohometab1db.ID = profilepicdb.ID WHERE doginfohometab1db.ID in(SELECT ID FROM doginfohometab1db WHERE NOT EXISTS (SELECT ID FROM dogdischargeinfohometab1db WHERE doginfohometab1db.id = dogdischargeinfohometab1db.id))");
$stmt->execute();
$stmt->bind_result($ID, $firstnametxt, $lastnametxt, $picurl);
$profiledata = array();
while($stmt->fetch()){
$temp = array();
$temp ['ID'] = $ID;
$temp ['firstnametxt'] = $firstnametxt;
$temp ['lastnametxt'] = $lastnametxt;
$temp ['picurl'] = $picurl;
array_push($profiledata, $temp);
}
return $profiledata;
}
}
This is my postman response
{"profiledata":
[{"ID":"hvg766khhv","firstnametxt":"hvg","lastnametxt":"khhv","picurl":"C:\xampp\htdocs\pathways1\includes/uploads/1535685930271.jpg"},{"ID":"jdjd676jdjf","firstnametxt":"jdjd","lastnametxt":"jdjf","picurl":"C:\xapp\htdocs\pathways1\includes/uploads/1535686965814.jpg"}]}
here is my api call
#GET("getprofilepic")
Call<PtList> PtList();
PtList class
import java.util.ArrayList;
public class PtList {
#SerializedName("ptList")
private ArrayList<dogdata> ptList;
public ArrayList<dogdata> getdogArrayList(){
return ptList;
}
public void setdogArrayList(ArrayList<dogdata> dogArrayList){
this.ptList = dogArrayList;
}
}
this is my dogdata class
public class dogdata {
#SerializedName("firstnametxt")
private String firstnametxt;
#SerializedName("lastnametxt")
private String lastnametxt;
#SerializedName("ID")
private String ID;
private boolean isSelected = false;
#SerializedName("picurl")
private String picurl;
dogdata(String firstnametxt, String lastnametxt, String ID, String picurl){
this.ID = ID;
this.firstnametxt = firstnametxt;
this.lastnametxt = lastnametxt;
this.picurl = picurl;
}
public String getID(){
return ID;
}
public void setID(String ID){
this.ID = ID;
}
public String getPicurl(){
return picurl;
}
public void setPicurl (String picurl){
this.picurl = picurl;
}
public String getFirstnametxt(){
return firstnametxt;
}
public void setFirstnametxt(String firstnametxt){
this.firstnametxt = firstnametxt;
}
public String getLastnametxt(){
return lastnametxt;
}
public void setLastnametxt(String lastnametxt){
this.lastnametxt = lastnametxt;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
this my activity class
public class TreatmentMain extends AppCompatActivity implements View.OnClickListener {
private RecyclerView mptRecyclerView;
private RecyclerView.Adapter mptAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_treatment_main);
downdogdata();
}
private void generatePtList(ArrayList<dogdata> ptList){
mptRecyclerView = (RecyclerView) findViewById(R.id.ptrecycler_view);
mptAdapter = new TreatmentAdapter(this, ptList);
RecyclerView.LayoutManager ptmanager = new LinearLayoutManager(TreatmentMain.this);
mptRecyclerView.setHasFixedSize(true);
mptRecyclerView.setLayoutManager(ptmanager);
mptRecyclerView.setAdapter(mptAdapter);
}
public void downdogdata() {
Call<PtList> call = RetrofitClient.getInstance().getAPIService().PtList();
call.enqueue(new Callback<PtList>() {
#Override
public void onResponse(Call<PtList> call, Response<PtList> response) {
if (response.code() == 200) {
generatePtList(response.body().getdogArrayList());
}
else if (response.code() == 422)
Toast.makeText(TreatmentMain.this, "Opps your code don't work bro", Toast.LENGTH_LONG).show();
{
} }
#Override
public void onFailure(Call<PtList> call, Throwable t) {
Toast.makeText(TreatmentMain.this, "Opps your code don't work bro on failure toast", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.txmainback:
Intent txmainback = new Intent(this, MainActivity.class);
startActivity(txmainback);
}
}
}
and lastly my adapter class
public class TreatmentAdapter extends RecyclerView.Adapter<TreatmentAdapter.MyptViewHolder> {
private ArrayList<dogdata> mptModelList;
private myptAdapterListener mptListener;
String ID;
Context mptcontext;
public interface myptAdapterListener{
void ontextClick(int position);
}
public TreatmentAdapter(Context context, ArrayList<dogdata> mptModelList) {
this.mptModelList = mptModelList;
mptcontext = context;
}
#Override
public MyptViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.treatmentrow, parent, false);
return new MyptViewHolder(view);
}
#Override
public void onBindViewHolder(final MyptViewHolder holder, final int position) {
final dogdata ptmodel = mptModelList.get(position);
holder.Treatmentfirstname.setText(ptmodel.getFirstnametxt());
holder.Treatmentlastname.setText(ptmodel.getLastnametxt());
// Picasso.get().load(ptmodel.getPicurl()).fit().centerCrop().error(R.drawable.ic_launcher_foreground).into(holder.ptreatmentprofile);
ID = ptmodel.getID();
holder.view.setBackgroundColor(ptmodel.isSelected() ? Color.CYAN: Color.WHITE);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ptmodel.setSelected(!ptmodel.isSelected());
holder.view.setBackgroundColor(ptmodel.isSelected() ? Color.GREEN : Color.WHITE);
mptListener.ontextClick(position);
}
});
}
#Override
public int getItemCount() {
return mptModelList == null ? 0 : mptModelList.size();
}
public class MyptViewHolder extends RecyclerView.ViewHolder {
private View view;
private TextView Treatmentfirstname;
private TextView Treatmentlastname;
private ImageView ptreatmentprofile;
public MyptViewHolder(final View View) {
super(View);
view = View;
Treatmentfirstname = (TextView) View.findViewById(R.id.Treatmentfirstname);
Treatmentlastname =(TextView) View.findViewById(R.id.Treatmentlastname);
ptreatmentprofile = (ImageView) View.findViewById(R.id.ptreatmentprofile);
}
}
}
I am making an android app ,which is get order from customers,but i faced a problem . I am trying to Retrieve Data from Firebase and display in a list view. I can get the data back from Firebase but when it displays in the listview it just displays one data in many times. I want to be displayed on one line for each record. Can anyone see where i am going wrong??
Database Image
ListView Image
OrderHistory
public class OrderHistory
{
String ammount,photoId,trxId,name,copy,photoSize,date;
public OrderHistory(String name,String photoId,String trxId,String copy,String photoSize,String ammount,String date)
{
this.name = name;
this.ammount = ammount;
this.photoId = photoId;
this.copy = copy;
this.photoSize = photoSize;
this.trxId = trxId;
this.date = date;
}
public String getAmmount() {
return ammount;
}
public void setAmmount(String ammount) {
this.ammount = ammount;
}
public String getPhotoId() {
return photoId;
}
public void setPhotoId(String photoId) {
this.photoId = photoId;
}
public String getTrxId() {
return trxId;
}
public void setTrxId(String trxId) {
this.trxId = trxId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCopy() {
return copy;
}
public void setCopy(String copy) {
this.copy = copy;
}
public String getPhotoSize() {
return photoSize;
}
public void setPhotoSize(String photoSize) {
this.photoSize = photoSize;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
OrderHistoryAdapter
public class OrderHistoryAdapter extends BaseAdapter {
private List<OrderHistory> orderHistories;
Context context;
public OrderHistoryAdapter(Context context, List<OrderHistory> myOrderInformations) {
this.context = context;
this.orderHistories = myOrderInformations;
}
#Override
public int getCount() {
return orderHistories.size();
}
#Override
public Object getItem(int position) {
return orderHistories.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.show_my_order_history, parent, false);
final TextView txtName, txtdate, txtPhotoId, trxId,txtAmount,txtPhotoSize,txtCopy;
txtName = (TextView)view.findViewById(R.id.txtName);
txtdate = (TextView)view.findViewById(R.id.txtDate);
txtPhotoId = (TextView)view.findViewById(R.id.txtPhotoId);
trxId = (TextView)view.findViewById(R.id.txtTrx);
txtAmount = (TextView)view.findViewById(R.id.txtAmount);
txtPhotoSize = (TextView)view.findViewById(R.id.txtSize);
txtCopy = (TextView)view.findViewById(R.id.txtCopy);
txtName.setText(orderHistories.get(position).getName());
txtdate.setText(orderHistories.get(position).getDate());
txtPhotoId.setText(orderHistories.get(position).getPhotoId());
trxId.setText(orderHistories.get(position).getTrxId());
txtAmount.setText(orderHistories.get(position).getAmmount());
txtCopy.setText(orderHistories.get(position).getCopy());
txtPhotoSize.setText(orderHistories.get(position).getPhotoSize());
return view;
}
}
OrderHistoryList
public class OrderHistoryList extends AppCompatActivity
{
private DatabaseReference databaseReference;
private List<OrderHistory> orderHistories;
private static String phoneNumber;
private ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_my_order);
Firebase.setAndroidContext(this);
listView = (ListView)findViewById(R.id.listView);
getAllOrderFromFirebase();
}
private void getAllOrderFromFirebase()
{
orderHistories = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("order");
String phone = getIntent().getExtras().getString("phone");
databaseReference.orderByChild("phone").equalTo(phone).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String amount, photoId, trxId, name, copy, photoSize, date;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
name = snapshot.child("name").getValue(String.class);
photoId = snapshot.child("photoId").getValue(String.class);
amount = snapshot.child("totalAmount").getValue(String.class);
trxId = snapshot.child("trxId").getValue(String.class);
photoSize = snapshot.child("photoSize").getValue(String.class);
date = snapshot.child("date").getValue(String.class);
copy = snapshot.child("totalCopy").getValue(String.class);
orderHistories.add(new OrderHistory(name, photoId, trxId, copy, photoSize, amount, date));
}
OrderHistoryAdapter adapter;
adapter = new OrderHistoryAdapter(OrderHistoryList.this, orderHistories);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I guess your problem is by the way you refer to your data so instead of this
databaseReference = FirebaseDatabase.getInstance().getReference("order");
use this
databaseReference = FirebaseDatabase.getInstance().getReference().child("order");
and you didn't use a query object to query your database reference
so now you don't query directly from databaseReference like the way you did it
instead you do this:
Query query=databaseReference.orderByChild("phone").equalTo(phone);
once you have a query that fits you now add on child listener and continue the rest of your code:
query.addChildEventListener(new ChildEventListener() {
//the rest of your code goes here(on child added/changed/......)
)};
I am trying to show my integers saved in the firebase database in my Recyclerview. I have two Strings I can easily show in my App, but somehow it doesn't work with integers. Even more strange is that when I save a String where before there was an integer I got an error.
Here my database structure
Here I populate my Viewholder
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ListItem, ListViewHolder>(
ListItem.class,
R.layout.card_item,
ListViewHolder.class,
mDatabase.orderByChild("minusAccandShare").endAt(0)
) {
#Override
protected void populateViewHolder(ListViewHolder viewHolder, ListItem model, final int position) {
viewHolder.setImage(getActivity().getApplicationContext(), model.getImage());
viewHolder.setHeading(model.getHeading());
viewHolder.setStoreName(model.getStoreName());
viewHolder.setAcceptCount(model.getAcceptCount());
viewHolder.mView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(getActivity(), DetailActivity.class);
Bundle extras = new Bundle();
extras.putString(EXTRA_QUOTE, firebaseRecyclerAdapter.getRef(position).getKey());
i.putExtra(BUNDLE_EXTRAS, extras);
startActivity(i);
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
My ViewHolder
public static class ListViewHolder extends RecyclerView.ViewHolder {
View mView;
public ListViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setImage(Context ctx, String image){
ImageView postImage = (ImageView) mView.findViewById(R.id.im_item_icon);
Picasso.with(ctx).load(image).resize(200,200).into(postImage);
}
public void setHeading(String heading){
TextView card_heading = (TextView) mView.findViewById(R.id.lbl_item_sub_title);
card_heading.setText(heading);
}
public void setStoreName(String storeName){
TextView card_storeName = (TextView) mView.findViewById(R.id.lbl_item_text);
card_storeName.setText(storeName);
}
public void setAcceptCount(String accepts){
TextView accepts_count = (TextView) mView.findViewById(R.id.lbl_accepts_count);
accepts_count.setText(accepts);
}
}
And finally my model
public class ListItem {
private String heading, storeName, image;
private Long accepts;
public ListItem() {
}
public ListItem(String heading,String storeName, Long accepts, String image){
this.heading = heading;
this.storeName = storeName;
this.image = image;
this.accepts = accepts;
}
public String getHeading() {
return heading;
}
public String getStoreName() {
return storeName;
}
public String getImage() {return image;}
public String getAcceptCount() {
return String.valueOf(accepts);
}
In this way I see null where there should stand 200 instead. I tried everything. I even saved an String instead of an integer and tried to show it the same way as the heading String ( which works perfectly) but then I see a blank place... Please help. Thanks
you should create a getter and setter for accepts in ListItem.
public Long getAccepts() {
return accepts;
}
public void setAccepts(Long accepts) {
this.accepts = accepts;
}
In my application I should load data from server and for this job I use Retrofit library.
In my application i want load string data from server and i should load images from drawable folder .
I can load string from server and show it on textview, but when add images i don't know how can i it?!
DataModel:
public class Retrofit_ColoniesModel {
//Load from server
#SerializedName("id")
private Integer id;
#SerializedName("slug")
private String slug;
#SerializedName("title")
private String title;
#SerializedName("description")
private String description;
#SerializedName("parent")
private Integer parent;
#SerializedName("post_count")
private Integer post_count;
//Load from local
private int[] image;
public Retrofit_ColoniesModel(Integer id, String slug, String title, String description, Integer parent, Integer post_count,
int[] image) {
this.id = id;
this.slug = slug;
this.title = title;
this.description = description;
this.parent = parent;
this.post_count = post_count;
this.image = image;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
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 Integer getParent() {
return parent;
}
public void setParent(Integer parent) {
this.parent = parent;
}
public Integer getPost_count() {
return post_count;
}
public void setPost_count(Integer post_count) {
this.post_count = post_count;
}
public int[] getImage() {
return image;
}
public void setImage(int[] image) {
this.image= image;
}
DataModelResponse:
public class Retrofit_ColoniesModelResponse {
#SerializedName("status")
private String status;
#SerializedName("count")
private int count;
#SerializedName("categories")
private List<Retrofit_ColoniesModel> categories;
public List<Retrofit_ColoniesModel> getCategories() {
return categories;
}
public void setCategories(List<Retrofit_ColoniesModel> categories) {
this.categories = categories;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Retrofit code in activity:
// Retrofit //////////
Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
Call<Retrofit_ColoniesModelResponse> call = apiInterface.getResponse();
call.enqueue(new Callback<Retrofit_ColoniesModelResponse>() {
#Override
public void onResponse(Call<Retrofit_ColoniesModelResponse> call, Response<Retrofit_ColoniesModelResponse> response) {
List<Retrofit_ColoniesModel> models = response.body().getCategories();
mAdaper = new ColoniesAdapter(context, models);
colonies_RecyclerView.setAdapter(mAdaper);
}
#Override
public void onFailure(Call<Retrofit_ColoniesModelResponse> call, Throwable t) {
}
});
//////////////////////
I want save images into Array, such as :
final int[] colImages = {
R.drawable.colonies_image_food,
R.drawable.colonies_image_medical,
R.drawable.colonies_image_tecgnolegy,
R.drawable.colonies_image_entertenement,
R.drawable.colonies_image_car,
R.drawable.colonies_image_model,
R.drawable.colonies_image_sport,
};
Adapter:
public class ColoniesAdapter extends RecyclerView.Adapter<ColoniesAdapter.ViewHolder> {
private List<Retrofit_ColoniesModel> mDateSet;
private Context mContext;
private SparseBooleanArray expandState = new SparseBooleanArray();
public ColoniesAdapter(Context context, List<Retrofit_ColoniesModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
for (int i = 0; i < mDateSet.size(); i++) {
expandState.append(i, false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.colonies_title.setText(mDateSet.get(position).getTitle());
holder.colonies_title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
Retrofit_ColoniesModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getTitle())
.putExtra("categoryID", model.getId()));
}
});
Glide.with(mContext)
.load(mDateSet.get(position).getImage()[position])
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
holder.colonies_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
Retrofit_ColoniesModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getTitle())
.putExtra("categoryID", model.getId()));
}
});
holder.colonies_description.setText(mDateSet.get(position).getDescription());
holder.colonies_count.setText("مطالب موجود در کلونی : " + mDateSet.get(position).getPost_count());
holder.expandableLayout.setInterpolator(mDateSet.get(position).getInterpolator());
holder.expandableLayout.setExpanded(expandState.get(position));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
createRotateAnimator(holder.buttonLayout, 0f, 180f).start();
expandState.put(position, true);
}
#Override
public void onPreClose() {
createRotateAnimator(holder.buttonLayout, 180f, 0f).start();
expandState.put(position, false);
}
});
holder.buttonLayout.setRotation(expandState.get(position) ? 180f : 0f);
holder.buttonLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
onClickButton(holder.expandableLayout);
}
});
}
private void onClickButton(final ExpandableLayout expandableLayout) {
expandableLayout.toggle();
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<Retrofit_ColoniesModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<Retrofit_ColoniesModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView colonies_title, colonies_description, colonies_count;
private ImageView colonies_image;
private ExpandableLinearLayout expandableLayout;
private RelativeLayout buttonLayout;
public ViewHolder(View itemView) {
super(itemView);
colonies_title = (TextView) itemView.findViewById(R.id.colonies_colony_title_text);
colonies_image = (ImageView) itemView.findViewById(R.id.colonies_cover_image);
colonies_description = (TextView) itemView.findViewById(R.id.colonies_expandable_description_text);
colonies_count = (TextView) itemView.findViewById(R.id.colonies_count_title_text);
buttonLayout = (RelativeLayout) itemView.findViewById(R.id.colonies_expandable_button);
expandableLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.colonies_expandable_layout);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail()));*/
}
});
}
}
public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
animator.setDuration(300);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
}
I don't know how can i add int[] into my constructor, because in retrofit fill the constructor with List<Retrofit_ColoniesModel> models = response.body().getCategories(); .
How can i fix my issue? I really need this tutorial, please help me. Thanks all <3
If the array of images is static (don't depend on the server) then you could just do the following:
public class Retrofit_ColoniesModel {
...
private static final int[] colImages = {
R.drawable.colonies_image_food,
R.drawable.colonies_image_medical,
R.drawable.colonies_image_tecgnolegy,
R.drawable.colonies_image_entertenement,
R.drawable.colonies_image_car,
R.drawable.colonies_image_model,
R.drawable.colonies_image_sport,
};
But if this array is not static (depends on the server response) then I suggest you to map to an array of Strings that describe each image, and the server should respond with those Strings, for example:
"images":["IMAGE1", "IMAGE2"]
And then have a helper class that could map between those string keys to the actual R.drawable resources.
Let me know if you need sample code.
Non-static Nested Classes (Inner Classes)
Non-static nested classes in Java are also called inner classes. Inner classes are associated with an instance of the enclosing class. Thus, you must first create an instance of the enclosing class to create an instance of an inner class. Here is an example inner class definition:
public class Outer {
public class Inner {
}
}
Here is how you create an instance of the Inner class:
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
Notice how you put new after the reference to the outer class in order to create an instance of the inner class.
Non-static nested classes (inner classes) have access to the fields of the enclosing class, even if they are declared private. Here is an example of that: